\r\n \"\"\"\r\n\r\n menu_html = ''\r\n for item in menu_data:\r\n if not item['status']: # 如果用户权限不在某个菜单下,即item['status']=False, 不显示\r\n continue\r\n else:\r\n if item.get('url'): # 说明循环到了菜单最里层的url\r\n if item['title'] in list_title_blank:\r\n menu_html += url_str_blank.format(permission_url=item['url'],\r\n permission_title=item['title'])\r\n else:\r\n menu_html += url_str.format(permission_url=item['url'],\r\n permission_title=item['title'])\r\n else:\r\n menu_html += option_str.format(menu_title=item['title'],\r\n sub_menu=get_menu_html(item['children']))\r\n\r\n return menu_html\r\n\r\n\r\n@register.simple_tag\r\ndef rbac_menu(request):\r\n \"\"\"\r\n 显示多级菜单:\r\n 请求过来 -- 拿到session中的菜单,权限数据 -- 处理数据 -- 作显示\r\n 数据处理部分抽象出来由单独的函数处理;渲染部分也抽象出来由单独函数处理\r\n \"\"\"\r\n menu_data = get_structure_data(request)\r\n menu_html = get_menu_html(menu_data)\r\n\r\n # 因为标签无法使用safe过滤器,这里用mark_safe函数来实现\r\n # print(menu_html)\r\n return mark_safe(menu_html)\r\n","sub_path":"rbac/templatetags/custom_tag.py","file_name":"custom_tag.py","file_ext":"py","file_size_in_byte":6321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"401609860","text":"# Choice Plot --------------------------------------------------------\nimport pyqtgraph as pg\nimport numpy as np\nfrom config.gui_settings import choice_history_len,choice_plot_window,choice_plot_look_ahead\nfrom PyQt5.QtCore import Qt\n\nclass Sequence_Plot():\n def __init__(self, parent_plot, data_len=100):\n self.plot_widget = parent_plot\n correct_color = pg.mkColor(0,255,0) # green\n correct_no_liquid_color = pg.mkColor(0,255,0,80) # faded green\n incorrect_color = pg.mkColor(0,0,0) # black\n background_color = pg.mkColor(255,255,0) # yellow\n background_no_liquid_color = pg.mkColor(255,255,0,128) # faded yellow\n faulty_color = pg.mkColor(255,0,0) # red\n self.my_colors = (correct_color, incorrect_color,background_color,faulty_color,correct_no_liquid_color,background_no_liquid_color)\n self.my_symbols = ('o','+','s','t') # circle, plus, square,triangle\n self.is_active = False\n self.do_update = True\n self.data_len = choice_history_len\n self.new_bout_line = pg.InfiniteLine(angle=90,pen='#FF1FE6')\n self.bout_text = pg.TextItem(\"testing\", anchor=(0, .5))\n self.faulty_line = None\n self.faulty_drawn_in_center = False\n self.bout_info_ylocation = 4\n\n def set_state_machine(self,sm_info):\n if not self.is_active: return\n self.setup_plot_widget()\n \n def setup_plot_widget(self):\n self.last_choice = ''\n self.reward_seq = ''\n self.label_new_bout = False\n self.next_seq = ''\n self.bout_start_trial = 0\n self.next_block_start = 0\n\n self.rewarded_trials = 0\n \n self.plot_widget.hideAxis('right')\n self.plot_widget.showAxis('left')\n self.plot_widget.setRange(xRange=[-1,choice_plot_window+choice_plot_look_ahead], padding=0)\n self.plot_widget.setMouseEnabled(x=True,y=False)\n self.plot_widget.showGrid(x=True,alpha=0.75)\n self.plot_widget.setLimits(xMin=-1)\n\n self.plot_widget.clear()\n self.plot_widget.getAxis('bottom').setLabel('Rat Perceived Trial')\n self.plot_widget.getAxis('right').setWidth(75)\n self.plot_widget.getAxis('left').setWidth(50)\n\n self.plot_widget.setYRange(4,9, padding=0.1)\n self.plot = self.plot_widget.plot(pen=None, symbol='o', symbolSize=6, symbolPen=None)\n\n self.plot_widget.setTitle('Choices and Outcomes')\n self.plot_widget.getAxis('left').setTicks([[(7,'Left'),(6,'Right')]])\n\n def run_start(self):\n if not self.is_active: return\n self.plot.clear()\n self.trial_num = 0\n self.data = np.zeros([self.data_len,6])\n self.plot_widget.addItem(self.bout_text)\n self.plot_widget.addItem(self.new_bout_line)\n\n def process_data(self, new_data):\n if not self.is_active: return\n '''Store new data from board.'''\n faulty_msgs = [nd for nd in new_data if nd[0] == 'P' and nd[2].split(',')[0]=='faulty'] \n outcome_msgs = [nd for nd in new_data if nd[0] == 'P' and nd[2].split(',')[0]=='rslt'] \n new_block_msgs = [nd for nd in new_data if nd[0] == 'P' and nd[2].split(',')[0]=='NB']\n newBlock_var_update_msgs = [nd for nd in new_data if nd[0] == 'V' and nd[2].split(' ')[0].find('trials_until_change')>-1] \n if outcome_msgs:\n n_new = len(outcome_msgs)\n self.data = np.roll(self.data, -n_new, axis=0)\n for i, ne in enumerate(outcome_msgs):\n trial_num_string,self.reward_seq,choice,outcome,reward_vol,center_hold,side_delay,faulty_chance,faulty_maxcount,faulty_time_limit = ne[-1].split(',')[1:]\n self.trial_num = int(trial_num_string)\n if choice == 'L':\n if self.last_choice == 'L':\n self.consecutive_adjustment += .2\n else:\n self.consecutive_adjustment = 0\n side = 7 + self.consecutive_adjustment\n elif choice == 'R':\n if self.last_choice == 'R':\n self.consecutive_adjustment += .2\n else:\n self.consecutive_adjustment = 0\n side = 6 - self.consecutive_adjustment\n else:\n side = 0\n self.last_choice = choice\n self.last_side = side\n\n if outcome == 'C': # was rewarded\n self.rewarded_trials += 1\n color = 0\n symbol = 2 #square\n elif outcome == 'W': # correct sequence, but rewared was withheld\n color = 4\n symbol = 2 #square\n elif outcome == 'N' or outcome == 'P': # was not rewarded\n color = 1\n symbol = 2 #square\n elif outcome == 'B': # background reward\n color = 2\n symbol = 2 #square\n elif outcome == 'A': # abandoned trial\n color = 1\n symbol = 3 #triangle\n elif outcome == 'F': # this \"rat percieved trial\" occured after a faulty nosepoke\n color = 3\n symbol = 0\n self.next_block_start +=1\n self.new_bout_line.setValue(self.next_block_start)\n self.bout_text.setPos(self.next_block_start, self.bout_info_ylocation)\n self.bout_text.setText(str(self.next_block_start - self.trial_num))\n \n self.data[-n_new+i,0] = self.trial_num\n self.data[-n_new+i,1] = side\n self.data[-n_new+i,2] = color\n self.data[-n_new+i,3] = symbol\n \n self.plot.setData(self.data[:,0],self.data[:,1],\n symbol=[self.my_symbols[int(ID)] for ID in self.data[:,3]],\n symbolSize=10,\n symbolPen=pg.mkPen(color=(150,150,150),width=1),\n symbolBrush=[self.my_colors[int(ID)] for ID in self.data[:,2]]\n )\n \n if self.faulty_drawn_in_center:\n self.faulty_drawn_in_center = False\n self.plot_widget.removeItem(self.faulty_line)\n self.faulty_line = pg.ErrorBarItem(x=np.array([self.trial_num - .5]),y=np.array([self.last_side]),height=.5,pen = pg.mkPen(color='#FF1F1F',width=3))\n self.plot_widget.addItem(self.faulty_line)\n\n\n self.update_title()\n if self.do_update:\n self.plot_widget.setRange(xRange=[self.trial_num-choice_plot_window,self.trial_num+choice_plot_look_ahead], padding=0)\n if faulty_msgs and not self.faulty_drawn_in_center:\n self.faulty_line = pg.ErrorBarItem(x=np.array([self.trial_num + .5]),y=np.array([6.5]),height=.5,pen = pg.mkPen(color='#FF1F1F',width=3))\n self.plot_widget.addItem(self.faulty_line)\n self.faulty_drawn_in_center = True\n if new_block_msgs:\n for nb_msg in new_block_msgs:\n # label old bout change\n transition_line = pg.InfiniteLine(angle=90,pen=pg.mkPen(color='#FF1FE6',style=Qt.DashLine))\n transition_line.setValue(self.next_block_start + .5)\n self.plot_widget.addItem(transition_line)\n self.label_new_bout = True\n\n\n content = nb_msg[2].split(',')\n # add new bout change\n self.next_block_start = int(content[2]) + self.trial_num\n self.next_seq = content[3]\n self.new_bout_line.setValue(self.next_block_start + .5)\n self.bout_text.setPos(self.next_block_start + .5, self.bout_info_ylocation)\n\n # update title\n self.reward_seq = content[1]\n self.update_title()\n \n if newBlock_var_update_msgs:\n for block_start_update in newBlock_var_update_msgs:\n content = block_start_update[2].split(' ')\n self.next_block_start = int(content[1]) + self.trial_num\n self.new_bout_line.setValue(self.next_block_start)\n self.bout_text.setPos(self.next_block_start, self.bout_info_ylocation)\n self.bout_text.setText(str(self.next_block_start - self.trial_num))\n if newBlock_var_update_msgs:\n self.update_title()\n\n def toggle_update(self):\n self.do_update = not self.do_update\n if self.do_update:\n self.plot_widget.setRange(xRange=[self.trial_num-choice_plot_window,self.trial_num+choice_plot_look_ahead], padding=0)\n\n def update_title(self):\n if self.trial_num:\n reward_percentage = round(self.rewarded_trials/self.trial_num*100,2)\n else:\n reward_percentage = 0\n self.plot_widget.setTitle('{} Rat Perceived Choices made --- {:.1f}% Perceived Trials Rewarded --- Current Reward Sequence:{}'.format(\n self.trial_num,reward_percentage,self.create_color_string(self.reward_seq)))\n self.bout_text.setHtml('{} in {} real trials'.format(self.create_color_string(self.next_seq),str(self.next_block_start - self.trial_num)))\n if self.label_new_bout:\n self.label_new_bout = False\n current_seq_text = pg.TextItem(html = self.create_color_string(self.reward_seq), anchor=(0, .5))\n current_seq_text.setPos(self.trial_num +.5, self.bout_info_ylocation)\n self.plot_widget.addItem(current_seq_text)\n\n if self.trial_num != 0: #don't do this for start of session\n previous_bout_length_text = pg.TextItem(str(self.trial_num - self.bout_start_trial), anchor=(1, .5))\n previous_bout_length_text.setPos(self.trial_num +.5, self.bout_info_ylocation)\n self.plot_widget.addItem(previous_bout_length_text)\n self.bout_start_trial = self.trial_num\n\n def update_block_marker(self,xpos):\n pass\n\n def create_color_string(self,sequence_string):\n blue,orange = '#00DEFF','#FF9A00'\n output_string = ''\n for letter in sequence_string:\n if letter == 'L':\n color = orange\n else:\n color = blue\n output_string += '{}'.format(color,letter)\n return output_string\n","sub_path":"gui/sequence_gui/choice_plot.py","file_name":"choice_plot.py","file_ext":"py","file_size_in_byte":10505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"464358846","text":"import taco_vis as tv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\n\n########################\n# Create example dataset:\ndef flow_func(radius, theta, time):\n u = np.sin(2 * np.pi * radius) * np.sin(theta) * np.sin(2 * np.pi * time)\n return u\n\n\ntime = np.linspace(0, 1, 50)\nradius = np.linspace(0, 1, 10)\ntheta = np.linspace(0, 2 * np.pi, 50)\n\nTH, R, T = np.meshgrid(theta, radius, time)\ndata = flow_func(R, TH, T)\n\n# Read data into flow class\nf = tv.FLOW(data)\n\nassert np.min(f.data) < 0, 'Data has no negative values'\nassert np.max(f.data) > 0, 'Data has no positive values'\n\n\n# Test animate contour plot_contours\nf.colorbar_title = \"Non-dimensional\\nvelocity\"\nf.movie_filename = \"test_contour.mp4\"\nf.plot_contours(animate=True, save=True)\n# If plotting another image, close this animation figure first.\nplt.close(\"all\")\nassert os.path.isfile(f.movie_filename), 'File {} does not exist after saving'.format(f.movie_filename)\n\n\n# Test contour plot_contours\nf.colorbar_title = \"Non-dimensional\\nvelocity\"\nf.image_filename = \"test_contour.png\"\nf.plot_contours(save=True, time_idx=14)\n# If plotting another image, close this animation figure first.\nplt.close(\"all\")\nassert os.path.isfile(f.image_filename), 'File {} does not exist after saving'.format(f.movie_filename)\n\n\n#Create axisymmetric data\ndata_axisym = flow_func(R, np.pi/2, T)\n\nf_axisym = tv.FLOW(data_axisym)\n\nf_axisym.image_filename = \"test_cylinders.png\"\nf_axisym.colorbar_title = \"Non-dimensional\\nvelocity\"\nf_axisym.plot_cylinders(save=True, time_idx=14)\n# If plotting another image, close this animation figure first.\nplt.close(\"all\")\nassert os.path.isfile(f_axisym.image_filename), 'File {} does not exist after saving'.format(f_axisym.movie_filename)\n\n\nf_axisym.image_filename = \"test_cylinders_3D.png\"\nf_axisym.plot_cylinders_3D(save=True, time_idx=14)\n# If plotting another image, close this animation figure first.\nplt.close(\"all\")\nassert os.path.isfile(f_axisym.image_filename), 'File {} does not exist after saving'.format(f_axisym.movie_filename)\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"530846742","text":"def jump(A):\n if len(A) <= 1:\n return 0\n jumps = [-1]*(len(A)-1)\n jumps.append(0)\n lastPosition = len(A)-1\n for i in range(len(A)-2, -1, -1):\n if A[i] + i >= lastPosition:\n jumps[i] = min([1+jumps[j] for j in range(i+1, A[i]+i+1) if jumps[j] >= 0])\n lastPosition = i\n return jumps[0]\n\nprint(jump([1,2]))\n","sub_path":"week18/Jing/test_jump_2.py","file_name":"test_jump_2.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"479879602","text":"#!/usr/bin/env python\n# Copyright (c) 2020, NVIDIA CORPORATION. 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\n# 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 NVIDIA CORPORATION nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport argparse\nimport numpy as np\nimport sys\nimport random\n\nimport tritongrpcclient\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-v',\n '--verbose',\n action=\"store_true\",\n required=False,\n default=False,\n help='Enable verbose output')\n parser.add_argument('-m',\n '--model_name',\n type=str,\n required=True,\n help='Model name')\n parser.add_argument('-u',\n '--url',\n type=str,\n required=False,\n default='localhost:8001',\n help='Inference server URL. Default is localhost:8001.')\n\n FLAGS = parser.parse_args()\n try:\n triton_client = tritongrpcclient.InferenceServerClient(url=FLAGS.url,\n verbose=FLAGS.verbose)\n except Exception as e:\n print(\"channel creation failed: \" + str(e))\n sys.exit()\n\n model_name = FLAGS.model_name \n\n mconf = triton_client.get_model_config(model_name, as_json=True)\n print('config:\\n', mconf)\n \n for i in range(50):\n # Infer\n inputs = []\n outputs = []\n \n nnodes = random.randint(100, 4000)\n nedges = random.randint(8000, 15000)\n\n inputs.append(tritongrpcclient.InferInput('x__0', [nnodes, 1433], 'FP32'))\n inputs.append(tritongrpcclient.InferInput('edgeindex__1', [2, nedges], \"INT64\"))\n\n x = np.random.normal(-10, 4, (nnodes, 1433)).astype(np.float32)\n x[x < 0] = 0.\n x[x > 1] = 1.\n edge_index = np.random.randint(0, nnodes, (2, nedges), dtype=np.int64)\n \n print(x.shape)\n print(edge_index.shape)\n\n # prepare inputs\n inputs[0].set_data_from_numpy(x)\n inputs[1].set_data_from_numpy(edge_index)\n\n # prepare outputs\n outputs.append(tritongrpcclient.InferRequestedOutput('logits__0'))\n\n # get the output\n results = triton_client.infer(model_name=model_name,\n inputs=inputs,\n outputs=outputs)\n output0_data = results.as_numpy('logits__0')\n print(output0_data)\n\n statistics = triton_client.get_inference_statistics(model_name=model_name)\n print(statistics)\n if len(statistics.model_stats) != 1:\n print(\"FAILED: Inference Statistics\")\n sys.exit(1)\n\n print('PASS: infer')\n","sub_path":"client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"116246617","text":"import os\nimport sys\nimport random\n\nfrom not_directed_graph import NotDirectedGraph\nfrom graph_builder import buildGraphFromFile\nfrom breath_first_search import breadthFirstSearch\nfrom eulerian_cycle import getEulerianTour\nfrom dijkstra import dijkstra\nfrom floyd_warshall import floydWarshall\nfrom topological_sorting import topologialSort\nfrom minimum_spanning_tree import minimumSpanningTree\n\n# on the first call to this function you must be SURE that \"path\" exists in the actual os.listdir()\nfrom strongly_connected_components import stronglyConnectedComponentes\n\n\ndef buildEachInstance(path: str) -> 'dict of Graphs':\n\tgraphs = dict()\n\n\t# go into folder\n\tos.chdir(path)\n\n\tfor item in os.listdir():\n\t\tif os.path.isdir(item):\n\t\t\tgraphs.update(buildEachInstance(item))\n\t\telse: \n\t\t\tgraphs[item] = buildGraphFromFile(item)\n\n\t# return to the initial folder\n\tos.chdir(\"..\")\n\n\treturn graphs\n\n# run all implemented algorithms on some graph\ndef test_graph(path: str, graph: NotDirectedGraph) -> None:\n\tprint('\\nTest Results for Graph in ' + path + ':\\n')\n\n\trand_vertex_id = random.choice(list(graph.vertices.keys()))\n\trand_vertex_name = graph.getVertexLabel(rand_vertex_id)\n\trand_vertex_neighbors = graph.getVertexNeighbors(rand_vertex_id)\n\trand_vertex_rand_neighbor = random.choice(list(rand_vertex_neighbors))\n\tother_rand_vertex_id0 = random.choice(list(graph.vertices.keys()))\n\tother_rand_vertex_id1 = random.choice(list(graph.vertices.keys()))\n\n\tprint('Number of vertices = ' + str(graph.getNumberOfVertices()))\n\tprint('Number of edges = ' + str(graph.getNumberOfEdges()))\n\tprint('Vertex ' + rand_vertex_id + ' degree = ' + str(graph.getVertexDegree(rand_vertex_id)))\n\tprint('Vertex ' + rand_vertex_id + ' name = ' + rand_vertex_name)\n\tprint('Vertex ' + rand_vertex_id + ' neighbors = ' + str(rand_vertex_neighbors))\n\tprint('Vertex ' + rand_vertex_id + ' has edge with ' + rand_vertex_rand_neighbor + ' = ' + str(graph.hasEdge(rand_vertex_id, rand_vertex_rand_neighbor)))\n\tprint('Vertex ' + rand_vertex_id + ' has edge with ' + other_rand_vertex_id0 + ' = ' + str(graph.hasEdge(rand_vertex_id, other_rand_vertex_id0)))\n\tprint('Vertex ' + rand_vertex_id + ' has edge with ' + other_rand_vertex_id1 + ' = ' + str(graph.hasEdge(rand_vertex_id, other_rand_vertex_id1)))\n\tprint('Edge ' + rand_vertex_id + ' <-> ' + rand_vertex_rand_neighbor + ' weight(s) = ' + str(graph.weight(rand_vertex_id, rand_vertex_rand_neighbor)))\n\ndef main():\n\tmaybePath = sys.argv[len(sys.argv)-1]\n\n\tif maybePath == \"testAll\":\n\t\tgraphs = buildEachInstance(\"instances\")\n\n\t\tfor graph in graphs:\n\t\t\tif len(graphs[graph].vertices) == 0:\n\t\t\t\tprint(\"Graph in \" + graph + ' has a problem')\n\t\t\t\treturn\n\n\t\tprint(\"Nothing wrong with the inputs.\\n\")\n\telse:\n\t\t# atividade1()\n\t\tatividade2()\n\ndef atividade1():\n\t# Exercicio 1:\n\tprint('Exercicio 1 (Funções De Grafos):')\n\tgraph_path = \"./instances/caminho_minimo/fln_pequena.net\"\n\tgraph = buildGraphFromFile(graph_path)\n\ttest_graph(graph_path, graph)\n\n\t# Exercicio 2:\n\tprint('\\nExercicio 2 (Busca em largura):\\n')\n\tprint(breadthFirstSearch(graph, '1')[0])\n\n\t# Exercicio 3:\n\tprint('\\nExercicio 3 (Ciclo Euleriano):\\n')\n\tgraph_path = \"./instances/ciclo_euleriano/ContemCicloEuleriano.net\"\n\tgraph = buildGraphFromFile(graph_path)\n\tprint(getEulerianTour(graph))\n\n\t# Exercicio 4:\n\tprint('\\nExercicio 4 (Dijkstra):\\n')\n\tgraph_path = \"./instances/caminho_minimo/fln_pequena.net\"\n\tgraph = buildGraphFromFile(graph_path)\n\tprint(dijkstra(graph, '1', True))\n\n\t# Exercicio 5:\n\tprint('\\nExercicio 5 (Floyd-Warshall):\\n')\n\tgraph_path = \"./instances/caminho_minimo/fln_pequena.net\"\n\tgraph = buildGraphFromFile(graph_path)\n\tprint(floydWarshall(graph))\n\ndef atividade2():\n\t# Exercicio 1:\n\tprint('Exercicio 1 (Componentes Fortemente Conexas)')\n\tgraph_path = \"./instances/dirigidos/dirigido2.net\"\n\tgraph = buildGraphFromFile(graph_path, is_directed=True)\n\tprint(stronglyConnectedComponentes(graph))\n\n\t# Exercicio 2:\n\tprint('Exercicio 2 (Ordenação Topológica)')\n\tgraph_path = \"./instances/dirigidos/manha.net\"\n\tgraph = buildGraphFromFile(graph_path, is_directed=True)\n\tprint(topologialSort(graph))\n\n\t# Exercicio 2:\n\tprint('Exercicio 3 (Arvore geradora minima - Prim)')\n\tgraph_path = \"./instances/arvore_geradora_minima/agm_tiny.net\"\n\tgraph = buildGraphFromFile(graph_path, is_directed=True)\n\tprint(minimumSpanningTree(graph))\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"472219612","text":"import itertools\n\nimport numpy as np\n\nimport nbody.io\nimport nbody.mass\nfrom nbody import scale\n\n\nclass NBody:\n def __init__(self, data, n_bodies, virial_radius, total_mass, time=0.0):\n self._data = data\n self._n_bodies = n_bodies\n self._virial_radius = virial_radius\n self._total_mass = total_mass\n self._time = time\n\n def init_energy(self):\n # set scaling stuff\n T = self.kinetic_energy()\n V = self.potential_energy()\n \n for b in self._data:\n b.vel *= np.sqrt(abs(V) / T / 2)\n for b in self._data:\n beta = 0.5 * V / -0.25\n #b.pos *= 0.82*beta # scaling added to equalise energies\n b.pos *= beta # scaling added to equalise energies\n b.vel /= np.sqrt(beta)\n\n\n @property\n def data(self):\n return self._data\n @property\n def n_bodies(self):\n return self._n_bodies\n @property\n def virial_radius(self):\n return self._virial_radius\n @property\n def total_mass(self):\n return self._total_mass\n\n @property\n def time(self):\n return self._time\n\n def scale_distance(self, distance):\n return distance * self.virial_radius\n\n def scale_energy(self, energy):\n return energy * self.scale_mass(1) * self.scale_velocity(1)**2\n\n def scale_mass(self, mass):\n return mass * self.total_mass\n\n def scale_time(self, time):\n return time * 14.94 * np.sqrt(self.virial_radius**3 / self.n_bodies \n / self.total_mass)\n \n def scale_velocity(self, velocity):\n return velocity * 6.557e-2 * np.sqrt(self.n_bodies * self.total_mass \n / self.virial_radius)\n \n\n def crossing_time(self):\n return nbody.time.crossing()\n\n def half_mass_relaxation_time(self):\n n = len(self._data)\n hmr = self.half_mass_radius()\n return nbody.time.half_mass_relaxation(n, hmr)\n\n def core_collapse_time(self):\n hmr = self.half_mass_radius()\n return nbody.time.core_collapse(len(self._data), hmr)\n def core_radius(self):\n if not hasattr(self, \"_cached_core_radius\"):\n core_radius = 0\n\n densities = self._get_densities()\n density_center = self.density_center()\n \n for i, star in enumerate(self._data):\n central_distance = star.pos - density_center\n core_radius += densities[i] * np.linalg.norm(central_distance)\n core_radius /= np.sum(densities)\n\n self._cached_core_radius = core_radius\n return self._cached_core_radius\n\n def density_center(self):\n ds = self._get_densities()\n\n dc = np.zeros(3)\n for i, b in enumerate(self._data):\n dc += ds[i] * b.pos\n\n return dc / np.sum(ds)\n\n def mass_radius(self, factor):\n half_mass_radius = 0\n\n distances = []\n density_center = self.density_center()\n for star in self._data:\n distance = np.linalg.norm(star.pos-density_center)\n distances.append((star.mass, distance))\n sorted_distances = sorted(distances, key=lambda x: x[1])\n\n total_mass = np.sum([star.mass for star in self._data])\n contained_mass = 0\n iterator = iter(sorted_distances)\n while contained_mass < total_mass * factor:\n mass, distance = next(iterator)\n contained_mass += mass\n half_mass_radius = distance\n\n return half_mass_radius\n\n def half_mass_radius(self):\n return self.mass_radius(0.5)\n\n def kinetic_energy(self):\n e = 0.0\n for b in self._data:\n e += 1/2 * b.mass * np.linalg.norm(b.vel)**2\n return e\n\n def potential_energy(self, soft=True):\n e = 0.0\n for b1, b2 in itertools.combinations(self._data, 2):\n r = np.linalg.norm(b1.pos - b2.pos)\n e -= b1.mass * b2.mass / r\n return e\n\n def total_energy(self):\n return self.kinetic_energy() + self.potential_energy()\n\n\n @classmethod\n def from_file(cls, filename):\n data = nbody.io.read(filename)\n return cls(*data)\n\n @classmethod\n def from_plummer(cls, n_bodies, total_mass, virial_radius, mass_fn=nbody.mass.ktg):\n ms = mass_fn(n_bodies)\n rs, vs = nbody.dist.plummer(n_bodies)\n\n data = []\n for m, r, v in zip(ms, rs, vs):\n b = nbody.its.Body(m, r, v)\n data.append(b)\n nbody.its.init(data)\n\n return cls(data, n_bodies, virial_radius, total_mass)\n\n @classmethod\n def from_uniform(cls, n_bodies, total_mass, virial_radius, mass_fn=nbody.mass.ktg):\n ms = mass_fn(n_bodies)\n rs, vs = nbody.dist.uniform(n_bodies)\n\n data = []\n for m, r, v in zip(ms, rs, vs):\n b = nbody.its.Body(m, r, v)\n data.append(b)\n nbody.its.init(data)\n\n return cls(data, n_bodies, virial_radius, total_mass)\n\n def _get_densities(self):\n densities = np.empty( len(self._data) )\n\n ds = self._get_distances()\n sorted_distances = np.sort(ds, axis=1)\n\n for i, b in enumerate(self._data):\n density = 3 / (4 * np.pi)\n density *= 3.5 * b.mass\n density /= sorted_distances[i, 2]\n\n densities[i] = density\n return densities\n\n def _get_distances(self):\n distances = np.empty((len(self._data), len(self._data)))\n\n iterator = itertools.combinations(enumerate(self._data), 2)\n for (i, star1), (j, star2) in iterator:\n distance = np.linalg.norm(star1.pos - star2.pos)\n\n distances[i, j] = distance\n distances[j, i] = distance\n return distances\n","sub_path":"nbody/nbody.py","file_name":"nbody.py","file_ext":"py","file_size_in_byte":5727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"458124395","text":"from sys import argv\nimport sys\n\nsand_ingd = list(('ham', 'cheese', 'tomatoes'))\ncake_ingd = list(('flour', 'sugar', 'eggs'))\nsalad_ingd = list(('avocado', 'arugula', 'tomatoes', 'spinach'))\ns_dict = dict(ingredients=sand_ingd, meal='lunch', prep_time=10)\nc_dict = dict(ingredients=cake_ingd, meal='desert', prep_time=60)\ns_dict = dict(ingredients=salad_ingd, meal='lunch', prep_time=15)\ncookbook = dict(sandwich=s_dict, cake=c_dict, salad=s_dict)\n\n\ndef print_recipe(recipe_name):\n recipe_data = cookbook.get(recipe_name)\n print(f\"\"\"\\nRecipe for {recipe_name}:\nIngredients list: {recipe_data.get('ingredients')}\nTo be eaten for {recipe_data.get('meal')}\nTakes {recipe_data.get('prep_time')} of cooking.\"\"\")\n\n\ndef delete_recipe(recipe_name):\n del cookbook[recipe_name]\n\n\ndef add_recipe():\n print('Let\\'s add a new recipe!')\n print('Enter a name')\n new_name = str(input())\n print('Enter the ingredients (separate each one by a space)')\n raw_ing = str(input())\n new_ing = raw_ing.split(' ')\n print('Enter the meal type')\n new_meal = str(input())\n print('Enter the number of minutes needed (ex: 15)')\n new_time = str(input())\n new_rec = dict(ingredients=new_ing, meal=new_meal, prep_time=new_time)\n final_rec = {f\"{new_name}\": new_rec}\n print(final_rec)\n cookbook[f\"{new_name}\"] = new_rec\n print(f'{new_name} has successfuly been added to your cookbook!')\n\n\ndef print_all_recipes():\n output = \"\\nHere are all the recipes of your cookbook: \"\n len_book = len(cookbook)\n i = 0\n for n in cookbook:\n if i < len_book-1:\n cond = True\n else:\n cond = False\n liaison = ('.', ',')[cond]\n output += str(n) + liaison\n i += 1\n print(output)\n\n\nusage = \"\"\"Please select an option by typing one of the following numbers:\n1. Print a recipe\n2. Delete a recipe\n3. Add a recipe\n4. Print all recipes\n5. Quit\n \"\"\"\nprint(usage)\nwhile True:\n try:\n response = int(input())\n if response == 5:\n print('Cookbook closed.')\n sys.exit()\n if response == 4:\n print_all_recipes()\n continue\n if response == 3:\n add_recipe()\n continue\n if response == 1:\n print_all_recipes()\n print('Please chose one by writting it\\'s name')\n resp = input()\n # check if recipe exists in dict\n if cookbook.get(resp) is None:\n print('Sorry, this recipe is not in this cookbook.')\n print_all_recipes()\n continue\n else:\n print_recipe(resp)\n continue\n if response == 2:\n print_all_recipes()\n print(\"\"\"\n Please choose the one you wish to delete by writting it\\'s name\"\"\")\n resp = input()\n # check if recipe exixts in dict\n if cookbook.get(resp) is None:\n print('Sorry, this recipe is not in this cookbook.')\n print_all_recipes()\n continue\n else:\n del cookbook[resp]\n print(f'{resp} has been deleted.')\n continue\n else:\n print('This option does not exist.')\n print(usage)\n continue\n except SystemExit:\n sys.exit()\n except ValueError:\n print('This option does not exist.')\n print(usage)\n","sub_path":"ex06/recipe.py","file_name":"recipe.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"501629437","text":"import sys\nfrom pprint import pprint\nimport numpy as np\nimport re\nimport csv\nimport time\n\nclass Layers:\n def __init__(self):\n self.layertypes = []\n self.weights = []\n self.biases = []\n self.numlayer = 0\n self.ffn_counter = 0\n\ndef parse_bias(text):\n if len(text) < 1 or text[0] != '[':\n raise Exception(\"expected '['\")\n if text[-1] != ']':\n raise Exception(\"expected ']'\")\n v = np.array([*map(lambda x: np.double(x.strip()), text[1:-1].split(','))])\n #return v.reshape((v.size,1))\n return v\n\ndef parse_vector(text):\n if len(text) < 1 or text[0] != '[':\n raise Exception(\"expected '['\")\n if text[-1] != ']':\n raise Exception(\"expected ']'\")\n v = np.array([*map(lambda x: np.double(x.strip()), text[1:-1].split(','))])\n return v.reshape((v.size,1))\n #return v\n\ndef balanced_split(text):\n i = 0\n bal = 0\n start = 0\n result = []\n while i < len(text):\n if text[i] == '[':\n bal += 1\n elif text[i] == ']':\n bal -= 1\n elif text[i] == ',' and bal == 0:\n result.append(text[start:i])\n start = i+1\n i += 1\n if start < i:\n result.append(text[start:i])\n return result\n\ndef parse_matrix(text):\n i = 0\n if len(text) < 1 or text[0] != '[':\n raise Exception(\"expected '['\")\n if text[-1] != ']':\n raise Exception(\"expected ']'\")\n return np.array([*map(lambda x: parse_vector(x.strip()).flatten(), balanced_split(text[1:-1]))])\n\ndef parse_net(text):\n lines = [*filter(lambda x: len(x) != 0, text.split('\\n'))]\n i = 0\n res = Layers()\n while i < len(lines):\n if lines[i] in ['ReLU', 'Affine']:\n W = parse_matrix(lines[i+1])\n b = parse_bias(lines[i+2])\n res.layertypes.append(lines[i])\n res.weights.append(W)\n res.biases.append(b)\n res.numlayer+= 1\n i += 3\n else:\n raise Exception('parse error: '+lines[i])\n return res\n \ndef parse_spec(text):\n text = text.replace(\"[\", \"\")\n text = text.replace(\"]\", \"\")\n with open('dummy', 'w') as my_file:\n my_file.write(text)\n data = np.genfromtxt('dummy', delimiter=',',dtype=np.double)\n low = np.copy(data[:,0])\n high = np.copy(data[:,1])\n return low,high\n\ndef get_perturbed_image(x, epsilon):\n image = x[1:len(x)]\n num_pixels = len(image)\n LB_N0 = image - epsilon\n UB_N0 = image + epsilon\n \n for i in range(num_pixels):\n if(LB_N0[i] < 0):\n LB_N0[i] = 0\n if(UB_N0[i] > 1):\n UB_N0[i] = 1\n return LB_N0, UB_N0\n","sub_path":"src/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"585047210","text":"#!/usr/bin/env python\n\nimport os\nimport argparse\nimport ConfigParser\n\nconfigfile = None\nlogfile = None\nis_daemon = False\nbe_verbose = False\n\ndef parse_args() :\n \n global configfile, logfile, is_daemon, be_verbose\n ap = argparse.ArgumentParser(description=\"Collector and correlator of Netflow v5, v9 and IPFIX flows and Syslog messages\")\n ap.add_argument('-c', metavar='configfile', default='/usr/local/etc/collectord.conf', help=\"collectors' config file\")\n ap.add_argument('-l', metavar='logfile', default='/var/log/collectord.log', help='log file for collector own messages')\n ap.add_argument('-d', action='store_true', help='start as daemon')\n ap.add_argument('-v', action='store_true', help='verbose debug messages')\n args = ap.parse_args()\n\n configfile = args.c\n logfile = args.l\n is_daemon = args.d\n be_verbose = args.v\n return args\n\ndef parse_config(filename) :\n if not os.path.isfile(filename):\n print(\"File {0} not found\".format(filename))\n quit()\n\n cf = ConfigParser.SafeConfigParser()\n cf.read(filename)\n res = {}\n res['sections'] = cf.sections()\n for sect in res['sections'] :\n opts = {}\n for opt in ['address', 'port', 'type'] :\n opts[opt] = cf.get(sect, opt)\n res[sect] = opts\n return res\n\ndef print_args_config(config) :\n\n print(\"Running the following config:\")\n print(\" logfile name: {0}\".format(logfile))\n print(\" config file name: {0}\".format(configfile))\n print(\" is daemon: {0}\".format(is_daemon))\n print(\" be verbose: {0}\".format(be_verbose))\n print('Config file is:')\n for s in config['sections']:\n print(\"Section {0}:\".format(s))\n print(\" Collector type: {0}\".format(config[s]['type']))\n print(\" Listening on : {0}:{1}\".format(config[s]['address'], config[s]['port']))\n\nif __name__ == \"__main__\":\n parse_args()\n c = parse_config(configfile)\n if c == None :\n print('Error parsing config file')\n else :\n print_args_config(c)\n \n","sub_path":"collector_config.py","file_name":"collector_config.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"513694211","text":"# %load q04_plot_runs_by_balls/build.py\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nipl_df = pd.read_csv('data/ipl_dataset.csv', index_col=None)\n\n\n# Solution\ndef plot_runs_by_balls():\n runs = ipl_df.groupby(['match_code','batsman'])['runs'].sum()\n balls = ipl_df.groupby(['match_code','batsman'])['delivery'].count()\n plt.scatter(runs,balls)\n plt.show()\nplot_runs_by_balls() \n\n\n","sub_path":"q04_plot_runs_by_balls/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"374170183","text":"import soundfile as sf\nimport torch\nimport numpy as np\nfrom evaluator.music_demixing import MusicDemixingPredictor\nfrom demucs.model import Demucs\nfrom demucs.utils import apply_model\nfrom models import get_models, Mixer\nimport torchaudio\nfrom openunmix import data, predict\nimport onnxruntime as ort\nfrom time import time, sleep\n\ndevice = torch.device('cpu')\n\nclass Predictor(MusicDemixingPredictor):\n\n def prediction_setup(self):\n self.models = get_models(model_name, load=False, device=device)\n self.demucs = Demucs(sources=[\"drums\", \"bass\", \"other\", \"vocals\"], channels=48 if '48' in demucs_name else 64)\n self.demucs.load_state_dict(torch.load(f'model/{demucs_name}.ckpt'))\n self.mixer = Mixer(device)\n self.mixer.eval()\n\n def prediction(self, mixture_file_path, bass_file_path, drums_file_path, other_file_path, vocals_file_path):\n file_paths = [bass_file_path, drums_file_path, other_file_path, vocals_file_path]\n sources = self.demix(mixture_file_path)\n for i in range(len(sources)):\n sf.write(file_paths[i], sources[i].T, samplerate=44100)\n\n def demix(self, mix_path):\n start_time = time()\n mix = sf.read(mix_path)[0].T\n base_out = self.demix_base(mix)\n print(time() - start_time)\n demucs_out = self.demix_demucs(mix)\n print(time() - start_time)\n\n sources = base_out * b + demucs_out * (1 - b)\n return sources\n\n def demix_base(self, mix):\n sources = []\n n_sample = mix.shape[1]\n for model in self.models:\n trim = model.n_fft // 2\n gen_size = model.chunk_size - 2 * trim\n pad = gen_size - n_sample % gen_size\n mix_p = np.concatenate((np.zeros((2, trim)), mix, np.zeros((2, pad)), np.zeros((2, trim))), 1)\n\n mix_waves = []\n i = 0\n while i < n_sample + pad:\n waves = np.array(mix_p[:, i:i + model.chunk_size])\n mix_waves.append(waves)\n i += gen_size\n mix_waves = torch.tensor(mix_waves, dtype=torch.float32)\n\n with torch.no_grad():\n _ort = ort.InferenceSession(f'{onnx_name}/{model.target_name}.onnx')\n tar_waves = model.istft(torch.tensor(\n _ort.run(None, {'input': model.stft(mix_waves).numpy()})[0]\n ))\n tar_signal = tar_waves[:, :, trim:-trim].transpose(0, 1).reshape(2, -1).numpy()[:, :-pad]\n sources.append(tar_signal)\n\n with torch.no_grad():\n mix = torch.tensor(mix, dtype=torch.float32)\n sources = torch.tensor(sources).detach()\n x = torch.cat([sources, mix.unsqueeze(0)], 0)\n sources = self.mixer(x)\n\n return np.array(sources)\n\n def demix_demucs(self, mix):\n mix = torch.tensor(mix, dtype=torch.float32)\n mean, std = mix.mean(), mix.std()\n mix = (mix - mean) / std\n\n with torch.no_grad():\n sources = apply_model(self.demucs, mix, split=True, overlap=0.5)\n\n sources = (sources * std + mean).cpu().numpy()\n sources[[0, 1]] = sources[[1, 0]]\n return sources\n\n\nmodel_name = 'tdf+val'\ndemucs_name = 'demucs'\nonnx_name = 'onnx'\n\nb = np.array([[[0.5]], [[0.5]], [[0.7]], [[0.9]]])\n\nsubmission = Predictor()\nsubmission.run()\nprint(\"Successfully completed music demixing...\")\n","sub_path":"predict_blend.py","file_name":"predict_blend.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"644711720","text":"import urllib.request\nimport xmltodict\nimport json\nimport sys\nfrom urllib.request import urlopen\nfrom urllib.parse import urlencode, unquote, quote_plus\nimport urllib\nimport pandas as pd\nimport numpy as np\nimport requests\nfrom datetime import datetime, timedelta\n\n\nurl = 'http://apis.data.go.kr/1360000/AsosDalyInfoService/getWthrDataList'\nkey = \"6vFwBIO5ZKEEPDpVKwkmfssrPdCMNtDdPSff4szG9k4lVLL9qkYIfTxhw6gEggcK9CA6dCD8GsrCDXe%2FU1zKYQ%3D%3D\"\n\n\ndef weather_api(startdt):\n\n startdt = datetime.strptime(startdt, \"%Y-%m-%d\")\n\n addtime = timedelta(days=6)\n enddt = startdt + addtime\n\n startdt = startdt.strftime('%Y-%m-%d')\n enddt = enddt.strftime('%Y-%m-%d')\n\n startdt = int(startdt.replace('-', ''))\n enddt = int(enddt.replace('-', ''))\n\n startdt = str(startdt)\n enddt = str(enddt)\n\n print('step1 finished -------')\n queryParams_page1 = '?' + urlencode({\n\n \"ServiceKey\": unquote(key),\n \"dataCd\": \"ASOS\",\n \"dateCd\": \"DAY\",\n \"numOfRows\": \"600\",\n \"pageNo\": \"1\",\n \"startDt\": startdt,\n \"endDt\": enddt,\n \"stnIds\": \"159\",\n \"dataType\": \"JSON\"\n\n })\n\n queryURL_page1 = url + queryParams_page1\n response_page1 = requests.get(queryURL_page1)\n info_page1 = json.loads(response_page1.text)\n\n a = []\n for i in range(len(info_page1['response']['body']['items']['item'])):\n\n df = pd.DataFrame(info_page1['response']\n ['body']['items']['item'][i], index=[0])\n\n a.append(df)\n\n print('step2 finished -------')\n\n weather_api_1 = pd.concat(a)\n\n weather_api_1 = weather_api_1[['tm', 'avgTa', 'avgRhm', 'avgPa', 'sumRn']]\n weather_api_1 = weather_api_1.rename({'tm': 'date', 'avgTa': 'mean_temp',\n 'avgRhm': 'mean_humidity', 'avgPa': 'mean_pressure', 'sumRn': 'rain'}, axis=1)\n weather_api_1 = weather_api_1.reset_index(drop=True)\n weather_api_1 = weather_api_1.replace(r'', np.nan, regex=True)\n weather_api_1 = weather_api_1.fillna(0)\n weather_api_1 = weather_api_1.astype({'mean_temp': 'float', 'mean_humidity': 'float',\n 'mean_pressure': 'float', 'rain': 'float'})\n print('step3 finished -------')\n\n return weather_api_1\n\n\ndef utc_to_date(utc):\n date = datetime.utcfromtimestamp(utc).strftime('%Y-%m-%d')\n\n return date\n\n\ndef future7_weather_api():\n\n url = 'https://api.openweathermap.org/data/2.5/onecall'\n key = \"9688b3e45c54541ccc6c099da90380ab\"\n\n queryParams_page1 = '?' + urlencode({\n\n \"lat\": 35.1028,\n \"lon\": 129.0403,\n \"appid\": unquote(key),\n \"exclude\": \"hourly,minutely,current,alerts\",\n \"units\": \"metric\"\n\n })\n\n queryURL_page1 = url + queryParams_page1\n response_page1 = requests.get(queryURL_page1)\n info_page1 = json.loads(response_page1.text)\n\n a = []\n for i in range(len(info_page1['daily'])):\n\n utc_num = info_page1['daily'][i]['dt']\n\n if 'rain' in list(info_page1['daily'][i].keys()):\n\n dict = {\"date\": utc_to_date(utc_num), 'mean_temp': info_page1['daily'][i]['temp']['day'],\n 'mean_humidity': info_page1['daily'][i]['humidity'],\n 'mean_pressure': info_page1['daily'][i]['pressure'],\n 'rain': info_page1['daily'][i]['rain']}\n\n else:\n\n dict = {\"date\": utc_to_date(utc_num), 'mean_temp': info_page1['daily'][i]['temp']['day'],\n 'mean_humidity': info_page1['daily'][i]['humidity'],\n 'mean_pressure': info_page1['daily'][i]['pressure'],\n 'rain': 0}\n\n predict = pd.DataFrame(dict, index=[0])\n\n a.append(predict)\n\n weather_pre = pd.concat(a).reset_index(drop=True)\n\n return weather_pre\n","sub_path":"back_end/weather2.py","file_name":"weather2.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"77194471","text":"from datetime import datetime as dt\nfrom datetime import date, timedelta\nfrom datetime import datetime\nimport plotly.graph_objs as go\nfrom plotly import tools\nimport numpy as np\nimport pandas as pd\n\npd.options.mode.chained_assignment = None\n\ndf = pd.read_csv(\"data/performance_analytics_cost_and_ga_metrics.csv\")\ndf[\"Date\"] = pd.to_datetime(df[\"Date\"])\n\nnow = datetime.now()\ndatestamp = now.strftime(\"%Y%m%d\")\n\n\n# Data Table Update Function\ndef update_datatable(start_date, end_date):\n return df[(start_date <= df[\"Date\"]) & (df[\"Date\"] <= end_date)].to_dict(\"rows\")\n\n\n# Data Table Download Function\ndef update_download(start_date, end_date):\n return df[(start_date <= df[\"Date\"]) & (df[\"Date\"] <= end_date)]\n\n\n######################## FOR GRAPHS ########################\n\n\ndef update_graph(filtered_df, end_date):\n # Sessions Graphs\n sessions_scatter = go.Scatter(\n x=filtered_df[\"Travel Product\"], y=filtered_df[\"Sessions - This Year\"], text=\"Sessions - This Year\"\n )\n sessions_bar = go.Bar(\n x=filtered_df[\"Travel Product\"], y=filtered_df[\"Sessions - This Year\"], text=\"Sessions - This Year\", opacity=0.6\n )\n\n fig = tools.make_subplots(\n rows=2,\n cols=1,\n shared_xaxes=True,\n subplot_titles=(\"Line Chart\", \"Bar Chart\"), # Be sure to have same number of titles as number of graphs\n )\n\n fig.append_trace(sessions_scatter, 1, 1) # 0\n fig.append_trace(sessions_bar, 2, 1) # 1\n\n # integer index below is the index of the trace\n # yaxis indices below need to start from the number of total graphs + 1 since they are on right-side\n # overlaing and anchor axes correspond to the graph number\n\n fig[\"layout\"][\"xaxis\"].update(title=\"Travel Product\")\n for i in fig[\"layout\"][\"annotations\"]:\n i[\"font\"] = dict(\n size=12,\n # color='#ff0000'\n )\n fig[\"layout\"].update(\n height=500,\n # width=750,\n showlegend=False,\n xaxis=dict(\n # tickmode='linear',\n # ticks='outside',\n # tick0=1,\n dtick=5,\n ticklen=8,\n tickwidth=2,\n tickcolor=\"#000\",\n showgrid=True,\n zeroline=True,\n # showline=True,\n # mirror='ticks',\n # gridcolor='#bdbdbd',\n gridwidth=2,\n ),\n )\n updated_fig = fig\n return updated_fig\n","sub_path":"components/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"400094090","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 30 11:44:39 2021\n\n@author: qulab\n\"\"\"\nimport numpy as np\nfrom fpga_lib.dsl import *\nfrom fpga_lib.parameters import *\nfrom fpga_lib.experiments import *\nfrom fpga_lib import entities\nfrom fpga_lib.constants import Timing\n\nfrom gkp_exp.CD_gate.conditional_displacement_compiler import SBS_simple_compiler, ConditionalDisplacementCompiler, ECD_control_simple_compiler\n\n\nclass GKP(Calibratable):\n \"\"\"\n Args:\n cal_dir (str): directory with CD gate amplitude calibrations\n \"\"\"\n # Params for ECDC sequences\n qubit_pulse_pad = IntParameter(4)\n s_tau_ns = IntParameter(20)\n b_tau_ns = IntParameter(150)\n cal_dir = StringParameter(r'D:\\DATA\\exp\\2021-06-28_cooldown\\CD_fixed_time_amp_cal')\n plusX_file = StringParameter(r'D:\\DATA\\exp\\2021-06-28_cooldown\\gkp_prep\\plus_X.npz')\n plusY_file = StringParameter('')\n plusZ_file = StringParameter('')\n\n # Params for echoed feedback reset\n echo_delay = IntParameter(868)\n feedback_delay = IntParameter(0)\n final_delay = IntParameter(64)\n \n # Params for Kerr-cancelling drive\n Kerr_drive_time_ns = IntParameter(200)\n Kerr_drive_ramp_ns = IntParameter(200)\n Kerr_drive_detune_MHz = FloatParameter(15)\n \n # Params misc\n loop_delay = IntParameter(4e6)\n t_stabilizer_ns = IntParameter(150)\n init_tau_ns = IntParameter(50)\n t_mixer_calc_ns = IntParameter(600)\n \n \n \n def __init__(self, qubit, readout, name='gkp'):\n super(GKP, self).__init__(name)\n self.qubit, self.readout = qubit, readout\n \n @subroutine\n def reset_feedback_with_echo(self, echo_delay, final_delay, feedback_delay=0, log=False, res_name='default'):\n \"\"\"\n Feedback reset with echo during readout.\n \n Args:\n echo_delay (int): delay in [ns] from the beginning of the readout\n to the qubit echo pulse.\n final_delay (int): delay in [ns] after the feedback to cancel \n deterministic (state-independent) cavity rotation.\n feedback_delay (int): delay in [ns] of the feedback pulse. There \n will be additional processing time contribution on top of this.\n log (bool): flag to log the measurement outcome.\n res_name (str): name of the result if measurement is logged.\n \"\"\"\n sync()\n delay(echo_delay, channel=self.qubit.chan, round=True)\n self.qubit.flip() # echo pulse\n self.readout(wait_result=True, log=log, sync_at_beginning=False, **{res_name:'se'})\n sync()\n delay(feedback_delay, round=True)\n if_then_else(self.qubit.measured_low(), 'flip', 'wait')\n \n label_next('flip')\n self.qubit.flip()\n goto('continue')\n \n label_next('wait')\n delay(self.qubit.pulse.length)\n goto('continue')\n \n label_next('continue')\n delay(final_delay, round=True)\n sync()\n\n @subroutine\n def reset_feedback_with_phase_update(self, phase_reg, phase_g_reg, phase_e_reg,\n log=False, res_name='default', detune=0.0, drag=0.0):\n \"\"\"\n Feedback reset with echo during readout.\n \n Args:\n phase_reg (Register): phase register to be updated.\n phase_g_reg, phase_e_reg (Register): phases that will be added to \n the phase_reg depending on the measured outcome.\n log (bool): flag to log the measurement outcome.\n res_name (str): name of the result if measurement is logged.\n detune, drag (float): exra detuning and drag that will be added\n to the calibrated pulse values.\n \"\"\"\n sync()\n self.readout(wait_result=True, log=log, **{res_name:'se'})\n delay(4*Timing.send_ext_fn) # TODO: might not need this set_int_fn\n if_then_else(self.qubit.measured_low(), 'wait', 'flip')\n \n label_next('flip')\n self.qubit.flip(detune=self.qubit.pulse.detune+detune, drag=self.qubit.pulse.drag+drag)\n phase_reg += phase_e_reg\n goto('continue')\n \n label_next('wait')\n self.qubit.delay(self.qubit.pulse.length)\n phase_reg += phase_g_reg\n goto('continue')\n \n label_next('continue')\n sync()\n\n\n @subroutine\n def reset_feedback_with_phase_update_and_Kerr_drive(self, phase_reg, phase_g_reg, phase_e_reg,\n log=False, res_name='default', detune=0.0, drag=0.0, \n Kerr_g_amp=0.0, Kerr_e_amp=0.0):\n \"\"\"\n Feedback reset with phase update and Kerr-cancelling drive. Surprise.\n \n Args:\n phase_reg (Register): phase register to be updated.\n phase_g_reg, phase_e_reg (Register): phases that will be added to \n the phase_reg depending on the measured outcome.\n log (bool): flag to log the measurement outcome.\n res_name (str): name of the result if measurement is logged.\n detune, drag (float): exra detuning and drag that will be added\n to the calibrated pulse values.\n Kerr_g_amp, Kerr_e_amp (float): amplitude of the Kerr drive\n \"\"\"\n sync()\n self.readout(wait_result=True, log=log, **{res_name:'se'})\n delay(4*Timing.send_ext_fn) # TODO: might neeed set_int_fn?\n if_then_else(self.qubit.measured_low(), 'meas_g', 'meas_e')\n \n label_next('meas_e')\n sync()\n self.qubit.flip(detune=self.qubit.pulse.detune+detune, drag=self.qubit.pulse.drag+drag)\n phase_reg += phase_e_reg\n sync()\n self.qubit_detuned.smoothed_constant_pulse(self.Kerr_drive_time_ns,\n amp=Kerr_e_amp, sigma_t=self.Kerr_drive_ramp_ns)\n self.update_phase(phase_reg, self.cavity, self.t_mixer_calc_ns)\n sync()\n goto('continue')\n \n label_next('meas_g')\n sync()\n self.qubit.delay(self.qubit.pulse.length)\n phase_reg += phase_g_reg\n sync()\n self.qubit_detuned.smoothed_constant_pulse(self.Kerr_drive_time_ns,\n amp=Kerr_g_amp, sigma_t=self.Kerr_drive_ramp_ns)\n self.update_phase(phase_reg, self.cavity, self.t_mixer_calc_ns)\n sync()\n goto('continue')\n \n label_next('continue')\n sync()\n \n\n def reset_autonomous_Murch(self, qubit_detuned_obj, readout_detuned_obj,\n cool_duration_ns, qubit_ramp_ns, readout_ramp_ns,\n qubit_amp, readout_amp, qubit_detune_MHz, readout_detune_MHz,\n qubit_angle, qubit_phase, final_delay):\n \"\"\"\n Setup autonomous qubit cooling based on this Murch paper:\n https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.109.183602\n \n Args:\n qubit_detuned_obj (Mode): qubit mode to use in the protocol\n readout_detuned_obj (Mode): readout mode to use in the protocol\n cool_duration_ns (int): how long in [ns] to hold the constant\n Rabi drive on the qubit after ramping it up.\n qubit_ramp_ns (int): duration in [ns] of the qubit Rabi drive\n ramp up/down.\n readout_ramp_ns (int): duration in [ns] of the detuned readout\n drive ramp up/down. This can typically be shorter than the\n qubit ramp because the pulse is far detuned.\n qubit_amp (float): amplitude of the qubit Rabi pulse.\n readout_amp (float): amplitude of the detuned readout pulse.\n readout_detune_MHz (float): detuning of the readout pulse in [MHz]. \n Ideally equal to the qubit Rabi rate.\n qubit_detune_MHz (float): detuning of the qubit pulse in [MHz]\n qubit_angle, qubit_phase (float): final qubit rotation parameters\n final_delay (int): delay in [ns] after the cooling protocol\n \n Returns:\n cooling subroutine.\n \"\"\"\n self.qubit_detuned = qubit_detuned_obj\n self.readout_detuned = readout_detuned_obj\n\n sync()\n self.readout_detuned.set_detune(readout_detune_MHz*1e6)\n self.qubit_detuned.set_detune(qubit_detune_MHz*1e6)\n sync()\n \n qubit_pump_time = cool_duration_ns\n readout_pump_time = cool_duration_ns+2*qubit_ramp_ns-2*readout_ramp_ns\n \n @subroutine\n def cooling_Murch():\n sync()\n self.readout_detuned.smoothed_constant_pulse(\n readout_pump_time, amp=readout_amp, sigma_t=readout_ramp_ns)\n self.qubit_detuned.smoothed_constant_pulse(\n qubit_pump_time, amp=qubit_amp, sigma_t=qubit_ramp_ns)\n sync()\n self.qubit.rotate(qubit_angle, qubit_phase)\n sync()\n delay(final_delay, round=True)\n\n return lambda: cooling_Murch()\n\n\n def sbs(self, eps1, eps2, beta, s_tau_ns, b_tau_ns):\n \"\"\"\n Single step of SBS protocol based on this Baptiste paper:\n https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.125.260509\n \n The pulse sequence is compile based on the independent calibration of\n the conditional displacement amplitude. \n \n Args:\n eps1, eps2 (float): 1st/2nd small CD amplitude\n beta (float): big CD amplitude\n \n s_tau_ns, b_tau_ns (int): wait time in the small/big CD gate\n \"\"\"\n CD_compiler_kwargs = dict(qubit_pulse_pad=self.qubit_pulse_pad)\n C = SBS_simple_compiler(CD_compiler_kwargs, self.cal_dir)\n \n cavity_pulse, qubit_pulse = C.make_pulse(1j*eps1/2.0, 1j*eps2/2.0, beta,\n s_tau_ns, b_tau_ns)\n\n def sbs_step(s):\n \"\"\"\n Args:\n s (str): stabilization qudrature, either 'x' or 'p' \n \"\"\"\n phase = dict(x=0.0, p=np.pi/2.0)\n sync()\n self.cavity.array_pulse(*cavity_pulse, phase=phase[s])\n self.qubit.array_pulse(*qubit_pulse)\n sync()\n \n return sbs_step\n\n def load_sbs_sequence(self, s_tau, b_tau, ECD_filename, version):\n \"\"\"\n Args:\n version (str): \n - v1 is a simple version in which only ECD parameters beta & phi\n are loaded from the file.\n - v2 is a more complicated version in which qubit detunings and\n parameters of the pi-pulses are also used in addition to beta & phi.\n - v3 is like v2 but it returns an sbs_step that uses dynamix mixer.\n \"\"\"\n if version == 'v1':\n data = np.load(ECD_filename, allow_pickle=True)\n beta, phi = data['beta'], data['phi']\n tau = np.array([s_tau, b_tau, s_tau, 0])\n \n CD_compiler_kwargs = dict(qubit_pulse_pad=self.qubit_pulse_pad)\n C = ECD_control_simple_compiler(CD_compiler_kwargs, self.cal_dir)\n c_pulse, q_pulse = C.make_pulse(beta, phi, tau)\n if version in ['v2', 'v3']:\n data = np.load(ECD_filename, allow_pickle=True)\n beta, phi, phi_CD, alpha_correction = data['beta'], data['phi'], data['flip'], data['alpha_correction']\n detune, drag = data['qb_detune']*np.ones([4,2]), data['qb_drag']*np.ones([4,2])\n \n tau = np.array([s_tau, b_tau, s_tau, 0])\n \n CD_compiler_kwargs = dict(qubit_pulse_pad=self.qubit_pulse_pad)\n C = ECD_control_simple_compiler(CD_compiler_kwargs, self.cal_dir)\n c_pulse, q_pulse = C.make_pulse_v2(beta, phi, phi_CD, tau, detune, alpha_correction, drag)\n \n if version in ['v1', 'v2']:\n def sbs_step(s):\n \"\"\"\n Args:\n s (str): stabilizer direction, either 'x' or 'p'\n \"\"\"\n phase = dict(x=0.0, p=np.pi/2.0)\n sync()\n self.cavity.array_pulse(c_pulse.real, c_pulse.imag, phase=phase[s])\n self.qubit.array_pulse(q_pulse.real, q_pulse.imag)\n sync()\n \n if version == 'v3':\n def sbs_step():\n sync()\n self.cavity.array_pulse(c_pulse.real, c_pulse.imag, amp='dynamic')\n self.qubit.array_pulse(q_pulse.real, q_pulse.imag)\n sync() \n \n return sbs_step\n \n def export_ECDC_to_array_pulse(self, ecdc_filename, array_pulse_filename, **kwargs):\n \"\"\"\" Convert ECDC sequence to an array pulse and export it to a file.\n This is useful in case when different calibrated pulse parameters change\n and the previously optimized sequence becomes suboptimal. Saving the\n whole array pulse avoids this problem, since it no longer relies on cal.\"\"\"\n \n cond = 'qubit_pulse_pad' in kwargs.keys()\n qubit_pulse_pad = kwargs.pop('qubit_pulse_pad') if cond else self.qubit_pulse_pad\n \n cond = 'init_tau_ns' in kwargs.keys()\n init_tau_ns = kwargs.pop('init_tau_ns') if cond else self.init_tau_ns\n \n cond = 'cal_dir' in kwargs.keys()\n cal_dir = kwargs.pop('cal_dir') if cond else self.cal_dir \n \n CD_compiler_kwargs = dict(qubit_pulse_pad=qubit_pulse_pad)\n C = ECD_control_simple_compiler(CD_compiler_kwargs, cal_dir)\n data = np.load(ecdc_filename, allow_pickle=True)\n beta, phi = data['beta'], data['phi']\n tau = np.array([init_tau_ns]*len(data['beta']))\n c_pulse, q_pulse = C.make_pulse(beta, phi, tau)\n np.savez(array_pulse_filename, c_pulse=c_pulse, q_pulse=q_pulse)\n \n\n def stabilizer_phase_estimation(self, tau_ns):\n \n beta = np.sqrt(2*np.pi) # stabilizer CD amplitude\n C = ConditionalDisplacementCompiler(qubit_pulse_pad=self.qubit_pulse_pad)\n CD_params = C.CD_params_fixed_tau_from_cal(beta, tau_ns, self.cal_dir)\n cavity_pulse, qubit_pulse = C.make_pulse(*CD_params)\n \n def stabilizer_phase_estimation(s):\n phase = {'x' : 0.0, 'x+' : 0.0, 'x-' : np.pi, \n 'p' : np.pi/2.0, 'p+' : np.pi/2.0, 'p-' : -np.pi/2.0}\n sync()\n self.qubit.pi2_pulse(phase=np.pi/2.0)\n sync()\n self.cavity.array_pulse(*cavity_pulse, phase=phase[s])\n self.qubit.array_pulse(*qubit_pulse)\n sync()\n self.qubit.pi2_pulse(phase=-np.pi/2.0)\n sync()\n delay(24)\n self.readout(**{s:'se'})\n sync()\n \n return stabilizer_phase_estimation\n \n \n\n def displacement_phase_estimation(self, beta, tau_ns, res_name, \n echo_params=None, amp=1):\n \n C = ConditionalDisplacementCompiler(qubit_pulse_pad=self.qubit_pulse_pad)\n CD_params = C.CD_params_fixed_tau_from_cal(beta, tau_ns, self.cal_dir)\n cavity_pulse, qubit_pulse = C.make_pulse(*CD_params)\n \n sync()\n self.qubit.pi2_pulse(phase=np.pi/2.0)\n sync()\n self.cavity.array_pulse(*cavity_pulse, amp=amp)\n self.qubit.array_pulse(*qubit_pulse)\n sync()\n self.qubit.pi2_pulse(phase=-np.pi/2.0)\n sync()\n delay(24)\n if echo_params is not None:\n self.reset_feedback_with_echo(\n echo_params['echo_delay'], echo_params['final_delay'], \n log=True, res_name=res_name)\n else:\n self.readout(**{res_name:'se'})\n sync()\n \n\n def update_phase(self, phase_reg, mode, t_mixer_calc=400):\n c = FloatRegister()\n s = FloatRegister()\n c = af_cos(phase_reg)\n s = af_sin(phase_reg)\n DynamicMixer[0][0] <<= c\n DynamicMixer[1][0] <<= s\n DynamicMixer[0][1] <<= -s\n DynamicMixer[1][1] <<= c\n mode.delay(t_mixer_calc)\n mode.load_mixer()\n \n @subroutine\n def reset_mixer(self, mode, t_mixer_calc):\n sync()\n zero_phase_reg = FloatRegister(0)\n self.update_phase(zero_phase_reg, mode, t_mixer_calc)\n sync()\n ","sub_path":"gkp_qec/GKP.py","file_name":"GKP.py","file_ext":"py","file_size_in_byte":16249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"205844757","text":"n=int(input())\n\nfor _ in range(n):\n s=input()\n for i in range(len(s)-1):\n if s[i]!=s[i+1]:\n if s[i] in s[i+1:]:\n n-=1\n break\nprint(n)\n","sub_path":"boj(baekjoon)/boj_1316.py","file_name":"boj_1316.py","file_ext":"py","file_size_in_byte":188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"564377077","text":"from typing import Dict, Any, List, Optional, Union\n\n\ndef parse_topic(raw_topic: Dict[str, Any]) -> \"Topic\":\n topic_type = raw_topic[\"type\"]\n if topic_type == \"simple\":\n return Topic.from_dict(raw_topic)\n\n\nclass Topic:\n \"\"\"Topic to explain.\n\n Author: Bruno.\n \"\"\"\n\n def __eq__(self, other):\n return self._id == other._id\n\n @staticmethod\n def from_dict(raw_topic: Dict[str, Any]) -> \"Topic\":\n if raw_topic.get(\"examples\") is None:\n examples = []\n else:\n examples = raw_topic.get(\"examples\")\n if raw_topic.get(\"sub_topics\") is None:\n subtopics = []\n else:\n subtopics = [parse_topic(raw_topic) for raw_topic in raw_topic[\"sub_topics\"]]\n if raw_topic.get(\"questions\") is None:\n questions = []\n else:\n questions = raw_topic.get(\"questions\")\n return Topic(raw_topic[\"topic_id\"],\n raw_topic[\"utters\"],\n examples,\n subtopics,\n questions)\n\n # noinspection PyTypeChecker\n def __init__(\n self,\n topic_id: str,\n utters_explanations: List[str],\n examples: Optional[List[str]] = None,\n sub_topics: Optional[List[\"Topic\"]] = None,\n questions: Optional[List[str]] = None\n ):\n \"\"\"\n Constructor.\n\n Author: Bruno.\n\n Parameters\n ----------\n topic_id\n Identification for the topic.\n utters_explanations\n Possible explanations for the topic.\n examples\n Examples to give for the topic.\n sub_topics\n Sub topics of the topic.\n questions\n Questions to make to the user.\n \"\"\"\n self._id = topic_id\n self._utters_explanations = utters_explanations\n # Default detail level is the middle one.\n self._detail_level = int(len(utters_explanations) / 2)\n self.is_explained = False\n\n self._examples = [] if examples is None else examples\n self._current_example = 0\n\n self._sub_topics = [] if sub_topics is None else sub_topics\n self._current_sub_topic = 0\n\n self._questions = [] if questions is None else questions\n self._current_question = 0\n\n def get(self) -> Dict[str, \"Topic\"]:\n \"\"\"\n Get the current topic.\n\n Author: Tomas\n\n Returns\n -------\n Dictionary with the current topic's information and\n each subtopic within the main topic.\n \"\"\"\n topics = {self._id: self}\n for topic in self._sub_topics:\n topics.update(topic.get())\n return topics\n\n def set_current_example(self, example: int):\n \"\"\"\n Set the current examples' index.\n\n Author: Tomas\n\n Parameters\n ----------\n\n example\n new examples' index\n \"\"\"\n self._current_example = example\n\n def get_current_example(self) -> int:\n \"\"\"\n Get the current examples' index.\n\n Author: Tomas\n\n Returns\n -------\n The index of the current example.\n \"\"\"\n return self._current_example\n\n def get_explanation(self, mark_as_explained: bool = True) -> str:\n \"\"\"Explains the topic. Marks the topic as explained.\n\n Author: Bruno.\n\n Returns\n -------\n Utter associated to the explanation with current detail level.\n \"\"\"\n if mark_as_explained:\n self.is_explained = True\n if self._detail_level >= len(self._utters_explanations):\n self._detail_level = 0\n return self._utters_explanations[self._detail_level]\n \n\n def get_example(self) -> str:\n \"\"\"\n Get the utter associated to the next example to give.\n\n Author: Tomas\n\n Returns\n -------\n Utter associated to the next example if the topic has any example,\n otherwise it returns a default utter.\n \"\"\"\n if self._current_example < len(self._examples):\n example = self._examples[self._current_example]\n self._current_example += 1\n return example\n else:\n self._current_example = 0\n return \"utter_sin_ejemplos\"\n\n def get_question(self) -> str:\n \"\"\"\n Get the utter associated to the topic's next question.\n\n Author: Adrian\n\n Returns\n -------\n Utter associated to the next question if the topic has any,\n otherwise it returns a default utter.\n \"\"\"\n if self._current_question < len(self._questions):\n question = self._questions[self._current_question]\n self._current_question += 1\n return question\n else:\n self._current_question = 0\n return \"utter_sin_question\"\n\n def next(self) -> Union[\"Topic\", None]:\n \"\"\"Returns the next topic to explain.\n\n Author: Bruno.\n\n Returns\n -------\n Next topic to explain.\n \"\"\"\n if not self.is_explained:\n return self\n\n if self._current_sub_topic < len(self._sub_topics):\n topic = self._sub_topics[self._current_sub_topic]\n self._current_sub_topic += 1\n return topic\n\n return None\n\n def restart(self):\n \"\"\"Restarts the topic, so it can be explained again.\n\n Author: Bruno.\n \"\"\"\n self.is_explained = False\n self._current_example = 0\n self._current_sub_topic = 0\n for topic in self._sub_topics:\n topic.restart()\n\n def get_id(self) -> str:\n \"\"\"\n Get the current topic ID\n\n Author: Adrian\n\n Returns\n -------\n Topic's name.\n \"\"\"\n return self._id\n\n def set_explained(self, explained: bool):\n \"\"\"\n Set the current topic as explained or not explained.\n\n Author: Adrian\n\n Parameters\n ----------\n\n explained\n Boolean value to set if the current topic is explained or not.\n \"\"\"\n self.is_explained = explained\n\n @property\n def repeat(self) -> str:\n \"\"\"Repeats the explanation for the topic.\n\n Author: Bruno.\n\n Returns\n -------\n Utter associated to the explanation with next detail level if possible.\n Otherwise returns the utter for the maximum detail level.\n \"\"\"\n self._detail_level += 1\n\n \"\"\"Se marca como explicado aunque no esta explicado bien\"\"\"\n self.is_explained = True\n if self._detail_level >= len(self._utters_explanations):\n return self._utters_explanations[-1] # -1 = last element.\n\n return self._utters_explanations[self._detail_level]\n\n def get_amount_subtopics(self) -> int:\n \"\"\"\n Get the amount of subtopics of the current topic.\n\n Author: Tomas\n\n Returns\n -------\n Returns the amount of subtopics that the current topic has.\n \"\"\"\n return self._current_sub_topic\n","sub_path":"tour/topic/topics.py","file_name":"topics.py","file_ext":"py","file_size_in_byte":7074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"135076150","text":"from aiohttp import ClientSession\nimport aiohttp\nimport json\nfrom apps.NBL.tools import safe_get\nimport time\nfrom common.libs.log import LogMgr\n\n\n# 设置日志\nlogger = LogMgr.get('acb_score_svr')\n\n\nclass GetScores(object):\n async def get_scores(self, game_id):\n url = 'https://www.fibalivestats.com/data/%s/data.json' % str(game_id)\n conn = aiohttp.TCPConnector(verify_ssl=False)\n async with ClientSession(connector=conn) as session:\n try:\n logger.info('请求前。。。。')\n logger.info(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))\n async with session.get(url) as response:\n logger.info('请求后。。。。')\n logger.info(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))\n if response.status == 200:\n response = await response.text()\n player_stat = json.loads(response)\n try:\n scores_info = player_stat['pbp'][0]\n home_p1_score = safe_get(player_stat,'tm.1.p1_score')\n home_p2_score = safe_get(player_stat,'tm.1.p2_score')\n home_p3_score = safe_get(player_stat,'tm.1.p3_score')\n home_p4_score = safe_get(player_stat,'tm.1.p4_score')\n home_p5_score = safe_get(player_stat,'tm.1.p5_score')\n away_p1_score = safe_get(player_stat,'tm.2.p1_score')\n away_p2_score = safe_get(player_stat,'tm.2.p2_score')\n away_p3_score = safe_get(player_stat,'tm.2.p3_score')\n away_p4_score = safe_get(player_stat,'tm.2.p4_score')\n away_p5_score = safe_get(player_stat,'tm.2.p5_score')\n home_scores = [home_p1_score,home_p2_score,home_p3_score,home_p4_score,home_p5_score]\n away_scores = [away_p1_score,away_p2_score,away_p3_score,away_p4_score,away_p5_score]\n home_scores_total = sum(home_scores)\n away_scores_total = sum(away_scores)\n if player_stat['inOT'] != 0:\n period = scores_info['period'] + 4\n else:\n period = scores_info['period']\n match_time = scores_info['gt']\n minutes = match_time.split(':')[0]\n second = match_time.split(':')[1]\n seconds = int(minutes) * 60 + int(second)\n if period < 5:\n if match_time == '00:00':\n status_id = 2 * period + 1\n else:\n status_id = 2 * period\n else:\n status_id = 9\n if seconds == 0 and period >= 4 and home_scores_total != away_scores_total:\n status_id = 10\n data = {\n 'sport_id': 2,\n 'site': 'acb',\n 'matches': {\n game_id: {\n 'score': {\n 'tmr': {'ticking': 0, 'coundown': 1, 'addtime': 0, 'second': seconds},\n 'status_id': status_id,\n 'home_scores': home_scores,\n 'away_scores': away_scores,\n }\n }\n }\n }\n return data\n except:\n return 0\n else:\n return 0\n except:\n return 0\n","sub_path":"apps/ACB/acb_score.py","file_name":"acb_score.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"149692422","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO_BUZZER = 21\nGPIO.setwarning(False)\nGPIO.setmote(GPIO.BCM)\nGPIO.setup(GPIO_BUZZER, GPIO.OUT, initial = GPIO.LOW)\nHz = 440 * 3\np = GPIO.PWM(GPIO_BUZZER, 1)\np.ChangeFrequency(Hz)\np.start(50)\ntime.sleep(0.05)\np.stop()\ntime.sleep(0.05)\np.ChangeFrequency(Hz)\np.start(50)\ntime.sleep(0.05)\np.stop()\nGPIO.cleanup()\n","sub_path":"buzzer.py","file_name":"buzzer.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"195886800","text":"################################################################################\n# Artificial Neural Network #\n# Would a customer leave the bank? #\n# Featuring: #\n# * 10-fold cross validation evaluation schema #\n# * 2 hidden layers #\n# * BatchNormalization #\n################################################################################\n'''\nMake sure python supports tensorflow by installing python version 3.5.3.\nRead the \"py53\" text file\n'''\nimport os\nimport datetime\nimport numpy as np\nimport random\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.model_selection import cross_val_score, train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import confusion_matrix, accuracy_score\nimport keras\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers.normalization import BatchNormalization\nfrom tensorflow.contrib.keras import backend\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # filter out WARNING logs\n\n\n#########################\n# Define the ANN schema #\n#########################\ndef build_classifier():\n classifier = Sequential(layers=None) # the design of the layers would be manual\n # Add the input layer and the first hidden layer\n classifier.add(Dense(units=6, kernel_initializer='uniform', activation='relu', input_dim=11))\n classifier.add(BatchNormalization())\n # Add a second hidden layer\n classifier.add(Dense(units=6, kernel_initializer='uniform', activation='relu'))\n classifier.add(BatchNormalization())\n # Add the output layer\n classifier.add(Dense(units=1, kernel_initializer='uniform', activation='sigmoid'))\n # Compiling the ANN\n classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n # Return the classifier\n return classifier\n\n\nif __name__ == \"__main__\":\n ################\n # Get the Data #\n ################\n # Importing the dataset\n dataset = pd.read_csv(os.path.join('data', 'Churn_Modelling.csv')) # , index_col='RowNumber')\n # Keep only useful columns\n dataset.drop(['RowNumber', 'CustomerId', 'Surname'], axis=1, inplace=True)\n X = dataset.drop(['Exited'], axis=1).values # returns numpy.ndarry\n y = dataset.loc[:, 'Exited'].values\n\n ######################\n # Data Preprocessing #\n ######################\n # 1. Encoding the Independent (categorical) Variables\n # Convert labels [Germany, France, Spain] into levels [1, 2, 3]\n labelencoder_X_1 = LabelEncoder()\n X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])\n labelencoder_X_2 = LabelEncoder()\n X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])\n # 2. Convert levels [1, 2, 3] into one-hot representation [001, 010, 100]\n onehotencoder = OneHotEncoder(categorical_features=[1])\n X = onehotencoder.fit_transform(X).toarray()\n # 3. Remove a single one-hot variable to avoid the dummy variable trap\n X = X[:, 1:] # remove column 0\n\n #####################\n # Split the Dataset #\n #####################\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1633)\n\n ###################\n # Feature Scaling #\n ###################\n sc = StandardScaler()\n X_train = sc.fit_transform(X_train)\n X_test = sc.transform(X_test)\n\n #################\n # Train the ANN #\n #################\n random.seed(1553)\n # Global classifier variable\n classifier = KerasClassifier(\n # Supply the ANN architecture\n build_fn=build_classifier,\n # Supply the training parameters\n batch_size=10,\n epochs=100)\n\n # Execute cross validation\n time_0 = datetime.datetime.now()\n accuracies = cross_val_score(estimator=classifier,\n X=X_train, y=y_train,\n cv=8,\n n_jobs=-1)\n time_taken = datetime.datetime.now() - time_0\n\n ######################\n # Evaluate the Model #\n ######################\n mean = accuracies.mean()\n var = accuracies.std() ** 2\n\n #############################\n # Remove model form CPU/GPU #\n #############################\n backend.clear_session()\n\n #################\n # Print Results #\n #################\n print('\\n###########################################################')\n print('# Avg Accuracy: ' + str(mean)) # Avg Accuracy: 0.8361\n print('# Variance: ' + str(var)) # Variance: 0.0002\n print('# Time: ' + str(time_taken)) # Time: 0:03:38\n print('###########################################################\\n')\n","sub_path":"topic_1_ANN/banking_churn_basic_K_fold_CV.py","file_name":"banking_churn_basic_K_fold_CV.py","file_ext":"py","file_size_in_byte":4976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"178632369","text":"# This file is placed in the Public Domain.\n\n\n\"commands\"\n\n\nfrom ..objects import Object\n\n\ndef __dir__():\n return (\n 'Command',\n )\n\n\n__all__ = __dir__()\n \n\nclass Command(Object):\n\n cmds = Object()\n errors = []\n\n @staticmethod\n def add(cmd):\n setattr(Command.cmds, cmd.__name__, cmd)\n\n @staticmethod\n def dispatch(evt):\n if not evt.isparsed:\n evt.parse(evt.txt)\n func = getattr(Command.cmds, evt.cmd, None)\n if func:\n try:\n func(evt)\n except Exception as ex:\n exc = ex.with_traceback(ex.__traceback__)\n Command.errors.append(exc)\n evt.ready()\n return None\n evt.show()\n evt.ready()\n\n @staticmethod\n def remove(cmd):\n delattr(Command.cmds, cmd)\n","sub_path":"rssbot/runtime/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"298248598","text":"def split(line, types=None, delimiter=None):\n \"\"\"Splits a line of test and optionally performs type conversion.\n For example:\n\n >>> split('GOOD 100 490.50')\n ['GOOD', '100', '490.50']\n >>> split('GOOD 100 490.50', [str, int, float])\n ['GOOD', 100, 490.50]\n >>>\n By default, splitting is perfomed on whitespace, but a different delimiter\n can be selected with the delimiter keyword argument:\n\n >>> split('GOOD, 100, 490.50', delimiter=',')\n ['GOOOD', '100', '490.50']\n >>>\n \"\"\"\n\n fields = line.split(delimiter)\n if types:\n fields = [ty(val) for ty, val in zip(types, fields)]\n return fields\n\nif __name__ == '__main__':\n # test myself\n import doctest\n doctest.testmod(verbose=True)","sub_path":"pyDemo/doc_test/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"205899849","text":"import csv\n\nfrom django.test import TestCase\n\nfrom django_test_tools.file_utils import temporary_file\nfrom django_test_tools.mixins import TestOutputMixin\n\n\nclass TestTestOutputMixin(TestCase):\n @temporary_file('csv', delete_on_exit=True)\n def test_get_csv_content(self):\n outputfile = self.test_get_csv_content.filename\n with open(outputfile, 'w', encoding='utf-8') as csvfile:\n csv_writer = csv.writer(csvfile, delimiter=',')\n csv_writer.writerow(['Title 1', 'Title 2', 'Title 3', 'Title 4', 'Title 5'])\n for i in range(0, 6):\n csv_writer.writerow(['Data {0}'.format(i)] * 5)\n\n output_mixin = TestOutputMixin()\n data = output_mixin.get_csv_content(outputfile)\n self.assertEqual(7, len(data))\n self.assertEqual('Title 1', data[0][0])\n","sub_path":"tests/test_mixins.py","file_name":"test_mixins.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"553594505","text":"from ftw.testbrowser import browsing\nfrom opengever.bumblebee.events import PDFDownloadedEvent\nfrom opengever.journal.handlers import DOCUMENT_ADDED_ACTION\nfrom opengever.testing import IntegrationTestCase\nfrom opengever.testing.readonly import ZODBStorageInReadonlyMode\nfrom zope.event import notify\nimport transaction\n\n\nclass TestFileDownloadInReadOnly(IntegrationTestCase):\n\n features = ('bumblebee', )\n\n @browsing\n def test_file_download_journaling_doesnt_cause_readonly_error(self, browser):\n self.login(self.regular_user, browser)\n\n # Get other potential writes-on-read out of the way.\n # Those are not what we're testing here.\n browser.open(self.document,\n view='tabbed_view/listing',\n data={'view_name': 'overview'})\n transaction.commit()\n\n with ZODBStorageInReadonlyMode():\n browser.find('Download copy').click()\n browser.find('Download').click()\n transaction.commit()\n\n self.assertEqual(200, browser.status_code)\n self.assertEqual(self.document.file._data, browser.contents)\n\n self.assertEqual(\n len(self.document.file._data),\n int(browser.headers['Content-Length']))\n\n self.assertEqual(\n 'application/vnd.openxmlformats-officedocument.'\n 'wordprocessingml.document',\n browser.headers['Content-Type'])\n\n @browsing\n def test_downloading_doc_pdf_journaling_doesnt_cause_readonly_error(self, browser):\n self.login(self.regular_user, browser)\n\n with ZODBStorageInReadonlyMode():\n notify(PDFDownloadedEvent(self.document))\n transaction.commit()\n\n # Last journal entry should be document added, not 'PDF downloaded'\n msg = u'Document added: Vertr\\xe4gsentwurf'\n self.assert_journal_entry(self.document, DOCUMENT_ADDED_ACTION, msg)\n\n @browsing\n def test_downloading_mail_pdf_journaling_doesnt_cause_readonly_error(self, browser):\n self.login(self.regular_user, browser)\n\n with ZODBStorageInReadonlyMode():\n notify(PDFDownloadedEvent(self.mail_eml))\n transaction.commit()\n\n # Last journal entry should be document added, not 'PDF downloaded'\n msg = u'Document added: Die B\\xfcrgschaft'\n self.assert_journal_entry(self.mail_eml, DOCUMENT_ADDED_ACTION, msg)\n","sub_path":"opengever/readonly/tests/test_file_download.py","file_name":"test_file_download.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"177996109","text":"import pymel.core as pymel\nimport logging\n\n'''\nThis method facilitate the creation of utility nodes by connecting/settings automaticly attributes.\n'''\n__aBasicTypes = [int, float, bool, pymel.datatypes.Matrix, pymel.datatypes.Vector]\ndef _isBasicType(_val):\n global __aBasicTypes\n return type(_val) in __aBasicTypes\n\ndef ConnectOrSetAttr(_attr, _val):\n if isinstance(_val, list) or isinstance(_val, tuple):\n\n # Note: List attribute and compound attribute don't have the same way of iterating.\n if _attr.isArray():\n for i, val in enumerate(_val):\n ConnectOrSetAttr(_attr.elementByLogicalIndex(i), val)\n elif _attr.isCompound():\n children = _attr.getChildren()\n for child, val in zip(children, _val):\n ConnectOrSetAttr(child, val)\n else:\n raise Exception(\"Can't apply value {0} on attribute {1}, need an array or compound\".format(_val, _attr))\n\n '''\n for i, pSubValue in enumerate(_val):\n ConnectOrSetAttr(_attr.elementByLogicalIndex(i), pSubValue)\n '''\n else:\n if isinstance(_val, pymel.Attribute):\n pymel.connectAttr(_val, _attr, force=True)\n elif _isBasicType(_val):\n _attr.set(_val)\n else:\n logging.error(\n '[ConnectOrSetAttr] Invalid value for attribute {0} of type {1} and value {2}'.format(_attr.name(),\n type(_val),\n _val))\n raise TypeError\n\ndef CreateUtilityNode(_sClass, *args, **kwargs):\n uNode = pymel.shadingNode(_sClass, asUtility=True)\n for sAttrName, pAttrValue in kwargs.items():\n if not uNode.hasAttr(sAttrName):\n raise Exception('[CreateUtilityNode] UtilityNode {0} doesn\\'t have an {1} attribute. Skipping it.'.format(_sClass, sAttrName))\n else:\n ConnectOrSetAttr(uNode.attr(sAttrName), pAttrValue)\n return uNode\n\n#\n# CtrlShapes Backup\n#\ndef hold_ctrl_shapes(_oCtrl, parent=None):\n aShapes = filter(lambda x: isinstance(x, pymel.nodetypes.CurveShape), _oCtrl.getShapes())\n oSnapshot = pymel.duplicate(_oCtrl, parentOnly=True, returnRootsOnly=True)[0]\n for oShape in aShapes:\n oShape.setParent(oSnapshot, s=True, r=True)\n if parent:\n oSnapshot.setParent(parent)\n else:\n oSnapshot.setParent(world=True)\n oSnapshot.rename('_{0}'.format(_oCtrl.name()))\n return oSnapshot\n\ndef fetch_ctrl_shapes(source, target):\n # Remove any previous shapes\n pymel.delete(filter(lambda x: isinstance(x, pymel.nodetypes.CurveShape), target.getShapes()))\n for source_shape in source.getShapes():\n source_shape.setParent(target, r=True, s=True)\n source_shape.rename(target.name() + 'Shape')\n\n # TODO: Restore AnnotationShapes\n pymel.delete(source)\n\ndef BackupCtrlShapes(**kwargs):\n aCtrls = [o.getParent() for o in pymel.ls('anm_*', type='nurbsCurve')]\n return [hold_ctrl_shapes(oCtrl, **kwargs) for oCtrl in aCtrls]\n\n# TODO: Fix bug when two objects have the same name.\ndef RestoreCtrlShapes():\n aSources = [o.getParent() for o in pymel.ls('_anm_*', type='nurbsCurve')]\n\n for oSource in aSources:\n sTargetName = oSource.name()[1:]\n if pymel.objExists(sTargetName):\n oTarget = pymel.PyNode(str(sTargetName))\n\n fetch_ctrl_shapes(oSource, oTarget)\n #pymel.delete(oSource)\n\ndef create_squash_atts(attStretch, numSegments):\n import libFormula\n if not isinstance(attStretch, pymel.Attribute):\n raise IOError(\"Expected pymel Attribute, got {0} ({1})\".format(attStretch, type(attStretch)))\n return_vals = []\n for i in range(numSegments):\n pos = float(i)/(numSegments-1) * 2.0 - 1.0\n attSquash = libFormula.parse(\"s^(e^(x^2)))\", s=attStretch, x=pos)\n return_vals.append(attSquash)\n return return_vals\n","sub_path":"omtk/libs/libRigging.py","file_name":"libRigging.py","file_ext":"py","file_size_in_byte":4033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"109270016","text":"#!/usr/bin/python3\n\n'''module for shapes'''\n\n\nfrom .base import Base\nfrom sys import stdout\n\n\nclass Rectangle(Base):\n '''Rectangle Class that inherits from Base Class'''\n def __init__(self, width, height, x=0, y=0, id=None):\n '''Initialisation of the instance'''\n super().__init__(id)\n self.width = width\n self.height = height\n self.x = x\n self.y = y\n\n # *********** Properties Setters and Getters Section *************\n\n # width Property\n @property\n def width(self):\n '''retrieves the __width attribute value'''\n return self.__width\n\n @width.setter\n def width(self, value):\n '''sets the new value to the __width attribute'''\n if type(value) is not int:\n raise TypeError('width must be an integer')\n if value <= 0:\n raise ValueError('width must be > 0')\n self.__width = value\n\n # height Property\n @property\n def height(self):\n '''retrieves the __height attribute value'''\n return self.__height\n\n @height.setter\n def height(self, value):\n '''sets the new value to the __height attribute'''\n if type(value) is not int:\n raise TypeError('height must be an integer')\n if value <= 0:\n raise ValueError('height must be > 0')\n self.__height = value\n\n # x Property\n @property\n def x(self):\n '''retrieves the __x attribute value'''\n return self.__x\n\n @x.setter\n def x(self, value):\n '''sets the new value to the __x attribute'''\n if type(value) is not int:\n raise TypeError('x must be an integer')\n if value < 0:\n raise ValueError('x must be >= 0')\n self.__x = value\n\n # y Property\n @property\n def y(self):\n '''retrieves the __y attribute value'''\n return self.__y\n\n @y.setter\n def y(self, value):\n '''sets the new value to the __y attribute'''\n if type(value) is not int:\n raise TypeError('y must be an integer')\n if value < 0:\n raise ValueError('y must be >= 0')\n self.__y = value\n\n # **** End of Properties Setters and Getters Section *****\n\n # *************** Instance Methods Section ***************\n\n def area(self):\n '''calculates the rectangle area\n Returns:\n the calculation result \"the area\"\n '''\n return self.width * self.height\n\n def display(self):\n '''prints the rectangle instance with the # character'''\n buffer = [' ' * self.x + '#' * self.width for h in range(self.height)]\n print('\\n' * self.y + '\\n'.join(buffer))\n\n def update(self, *args, **kwargs):\n '''Updates the instance attributes from\n the arguments passed in a strict order\n or from the kwargs\n '''\n i = 0\n attributes = ['id', 'width', 'height', 'x', 'y']\n if len(args) > 0:\n for attr in attributes:\n if i > len(args) - 1:\n break\n setattr(self, attr, args[i])\n i += 1\n else:\n for key, value in kwargs.items():\n if key not in attributes:\n continue\n setattr(self, key, value)\n\n def to_dictionary(self):\n '''returns the dictionary representation of a Rectangle instance'''\n return {\n 'id': self.id,\n 'x': self.x,\n 'y': self.y,\n 'width': self.width,\n 'height': self.height\n }\n\n # *********** End of Instance Methods Section ************\n\n # **************** Magic Methods Section *****************\n\n def __str__(self):\n '''returns the string representation fo the instance'''\n return (f'[Rectangle] ({self.id}) {self.x}/{self.y}'\n f' - {self.width}/{self.height}')\n\n # ************ End of Magic Methods Section **************\n","sub_path":"0x0C-python-almost_a_circle/models/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":3975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"248031881","text":"import torch\nimport numpy as np\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, AutoMinorLocator\nfrom compress_training import DATASETS\nfrom glob import glob\n\n# These attribute are for retro compatibility with\n# Experiments that did not have them\nDEFAULT_EXTRA_PARAMS = ['compression']\n\ndef summarize_experiment(experiment, extra_params):\n val_acc = experiment[experiment.measure == 'val_acc']\n best_val = val_acc.sort_values(by='value', ascending=False).iloc[0]\n epoch = best_val.epoch\n summary = experiment[experiment.epoch==epoch].groupby('measure').mean()\n keys = list(summary.index) + ['time', 'epoch', 'lambda_start', 'lambda_decay', 'layers', 'iteration', 'algorithm']\n\n values = list(summary.value) + [float(best_val.time), int(epoch)] + list(extra_params)\n missing_values = len(keys) - len(values) # Computing the number of missin paramters\n # Adding default values for the missing parmaeters\n if missing_values > 0:\n values += DEFAULT_EXTRA_PARAMS[-missing_values:]\n result = pd.DataFrame([values], columns=keys)\n if min(experiment[experiment.measure == 'lambda'].epoch) == 0: # Solve bug\n test = experiment[experiment.epoch==epoch-1].groupby('measure').mean()\n result['lambda'] = pd.Series([test.loc['lambda'].value])\n return result\n\ndef merge_all_experiments(experiments):\n return pd.concat(experiments).fillna(0)\n\ndef get_experiments(experiment_name):\n files = glob('./experiments/%s/*.experiment' % experiment_name)\n experiments = [torch.load(x, 'rb') for x in files]\n ids = [x.split('/')[-1].replace('.experiment', '') for x in files]\n return ids, experiments\n\ndef get_summary(experiments):\n summarized = [summarize_experiment(x[1], x[0]) for x in experiments]\n summary = merge_all_experiments([x for x in summarized if x is not None])\n # summary['lambda_start'] = np.log10(summary['lambda_start'])\n summary.reset_index(drop=True, inplace=True)\n return summary\n\ndef best_experiment(summary, experiments, mode):\n s = summary.sort_values(by='val_acc')\n best = s.iloc[-1]\n return [x for x in experiments if x[1][x[1].measure == 'val_acc'].value.max() == best.val_acc][0]\n\ndef plot_experiment(experiment, prefix, mode):\n infos, x = experiment\n capacities = x[x.measure == 'capacity']\n train_acc = x[x.measure == 'mean_train_acc']\n test_acc = x[x.measure == 'test_acc']\n val_acc = x[x.measure == 'val_acc']\n best_val_acc_idx = val_acc.value.argmax()\n s = summarize_experiment(x, infos).iloc[0]\n best_val_acc = s.val_acc\n best_test_acc = s.test_acc\n best_capacity = s.capacity\n fig = plt.figure(figsize=(10, 5))\n a = fig.gca()\n a.grid()\n a.set_xlabel('Time (s)')\n b = a.twinx()\n b.set_yscale('log')\n b.set_ylabel('Capacity in neurons')\n b.plot(capacities.time, capacities.value, label='Total Capacity')\n if mode == 'classification':\n a.set_ylabel('Accuracy (%)')\n a.plot(train_acc.time, train_acc.value * 100, label='Train accuracy')\n a.plot(val_acc.time, val_acc.value * 100, label='Validation accuracy')\n a.plot(test_acc.time, test_acc.value * 100, label='Test accuracy')\n a.yaxis.set_minor_locator(MultipleLocator(0.1))\n a.yaxis.set_major_locator(MultipleLocator(1))\n a.legend(loc='lower left')\n else:\n a.set_ylabel('MSE')\n a.plot(train_acc.time, -train_acc.value, label='Train Error')\n a.plot(val_acc.time, -val_acc.value, label='Validation Error')\n a.plot(test_acc.time, -test_acc.value, label='Test Error')\n a.set_yscale('log')\n a.legend(loc='upper right')\n a.yaxis.grid(b=True, which='major', linestyle='-')\n a.yaxis.grid(b=True, which='minor', alpha=0.4, linestyle='--')\n a.xaxis.grid(b=True, which='major', linestyle='-')\n a.xaxis.grid(b=True, which='minor', alpha=0.4, linestyle='--')\n plt.title('%s - Best Model (%s layer(s), %s neurons, v=%s, t=%s)' % (prefix, infos[2], int(best_capacity), -best_val_acc, -best_test_acc))\n # plt.savefig('./plots/%s_compressor_accuracies_size.png' % prefix)\n # plt.close()\n\n\ndef remove_outliers(summaries, dataset_name):\n outlier_limit = (-np.inf, np.inf)\n if dataset_name == 'Add10':\n outlier_limit = (0, 1.3)\n elif dataset_name == 'Airfoil':\n outlier_limit = (0, 25)\n elif dataset_name == 'Poker':\n outlier_limit = (0.95, 1)\n tac = np.abs(summaries.test_acc)\n return summaries[np.bitwise_and(tac >= outlier_limit[0], tac <= outlier_limit[1])]\n\n\ndef plot_algorithm_comparison(summaries, dataset_name, mode='classification', metric='val_acc', first='compression', other='static'):\n cmap_first = 'Greens'\n cmap_second = 'Reds'\n\n first_summaries = summaries[summaries.algorithm == first]\n second_summaries = summaries[summaries.algorithm == other]\n plt.figure()\n if mode == 'classification':\n factor1 = 100\n factor2 = 100\n else:\n factor1 = -1\n factor2 = -1\n if metric != 'val_acc':\n factor1 = 1\n\n other = len(second_summaries[metric]) > 0\n sns.kdeplot(factor1 * first_summaries[metric], factor2 * first_summaries.test_acc, cmap=cmap_first, shade_lowest=False,shade=True, alpha=0.8, label=False)\n if other:\n sns.kdeplot(factor1 * second_summaries[metric], factor2 * second_summaries.test_acc, cmap=cmap_second, shade_lowest=False,shade=True, alpha=0.5, label=False)\n plt.scatter(factor1 * first_summaries[metric], factor2 * first_summaries.test_acc, alpha=1, color=sns.color_palette(cmap_first)[1], edgecolors='0.3', label=None)\n if other:\n plt.scatter(factor1 * second_summaries[metric], factor2 * second_summaries.test_acc, alpha=0.5, color=sns.color_palette(cmap_second)[1], edgecolors='0.3', label=None)\n a = plt.gca()\n a.yaxis.set_minor_locator(AutoMinorLocator())\n a.xaxis.set_minor_locator(AutoMinorLocator())\n if mode == 'classification':\n plt.ylabel('Testing accuracy (%)')\n if metric == 'val_acc':\n plt.xlabel('Validation accuracy (%)')\n # a.yaxis.set_minor_locator(MultipleLocator(0.1))\n # a.yaxis.set_major_locator(MultipleLocator(1))\n # a.xaxis.set_minor_locator(MultipleLocator(0.1))\n # a.xaxis.set_major_locator(MultipleLocator(1))\n elif metric == 'capacity':\n plt.xlabel('Capacity in neurons')\n else:\n plt.ylabel('Testing MSE')\n if metric == 'val_acc':\n plt.xlabel('Validation MSE')\n elif metric == 'capacity':\n plt.xlabel('Capacity in neurons')\n\n a.yaxis.grid(b=True, which='major', linestyle='-')\n a.yaxis.grid(b=True, which='minor', alpha=0.4, linestyle='--')\n a.xaxis.grid(b=True, which='major', linestyle='-')\n a.xaxis.grid(b=True, which='minor', alpha=0.4, linestyle='--')\n a.set_axisbelow(True)\n if 'reference' in DATASETS[dataset_name]:\n plt.axhline(abs(factor2) *DATASETS[dataset_name]['reference'], label='Best result for this architecture')\n handles, labels = [list(x) for x in a.get_legend_handles_labels()]\n else:\n handles = []\n labels = []\n\n first_rectangle = plt.Rectangle((0, 0), 1, 1, color=sns.color_palette(cmap_first)[-3])\n second_rectangle = plt.Rectangle((0, 0), 1, 1, color=sns.color_palette(cmap_second)[-3])\n plt.legend([first_rectangle, second_rectangle] + handles, ['Deterministic Compression Training', 'Classic Training'] + labels)\n plt.gcf().set_size_inches((10, 10))\n if metric == 'val_acc':\n plt.axes().set_aspect('equal', 'datalim')\n plt.title('%s - Algorithm comparision for testing and validation accuracies' % dataset_name)\n else:\n plt.title('%s - Algorithm comparision for testing and capacity' % dataset_name)\n plt.savefig('./plots/%s_test_%s_compression_static_comparison.png' % (dataset_name, metric))\n plt.close()\n\ndef plot_dataset(dataset_name, mode='classification'):\n ids, experiments = get_experiments(dataset_name)\n summaries = remove_outliers(get_summary(experiments), dataset_name)\n best = best_experiment(summaries, experiments, mode=mode)\n plot_experiment(best, dataset_name, mode)\n plot_algorithm_comparison(summaries, dataset_name, mode, metric='val_acc')\n plot_algorithm_comparison(summaries, dataset_name, mode, metric='capacity')\n try:\n pairs = find_closest_experiments(summaries)\n plot_compression_improvements(pairs, dataset_name, mode)\n except:\n pass # Pass if correspondig are not generated\n\ndef find_closest_experiments(summaries, first='compression', second='static'):\n first_summaries = summaries[summaries.algorithm == first].sort_values('val_acc', ascending=False).drop_duplicates(['capacity'])\n second_summaries = summaries[summaries.algorithm == second].sort_values('val_acc', ascending=False).drop_duplicates(['capacity'])\n first_cap = first_summaries.capacity\n second_cap = second_summaries.capacity\n\n result = []\n for i, x in enumerate(first_cap):\n index = np.argmin(np.abs(second_cap.values - x))\n a = first_summaries.iloc[i]\n b = second_summaries.iloc[index]\n result.append((a, b))\n return result\n\ndef plot_compression_improvements(pairs, dataset_name, mode='classification'):\n plt.figure(figsize=(10, 5))\n if mode == 'classification':\n factor = 100\n else:\n factor = 1\n plt.scatter([x[0].capacity for x in pairs], [(x[0].test_acc - x[1].test_acc) * factor for x in pairs],\n color='C1', linewidth=1, marker='o', s=100, edgecolor='black')\n a = plt.gca()\n plt.xscale('log')\n plt.title('%s - Improvement in testing accuracy for compress training at fixed capacity' % dataset_name)\n plt.axhline(y=0, color='black', linewidth=3)\n plt.xlabel('Model capacity (neurons)')\n if mode == 'classification':\n plt.ylabel('Absolute MSE delta')\n a.yaxis.set_minor_locator(AutoMinorLocator())\n a.yaxis.grid(b=True, which='minor', alpha=0.4, linestyle='--')\n a.xaxis.grid(b=True, which='minor', alpha=0.4, linestyle='--')\n a.yaxis.grid(b=True, which='major', linestyle='-')\n a.xaxis.grid(b=True, which='major', linestyle='-')\n plt.savefig('./plots/%s_compression_training_improvements.png' % dataset_name)\n plt.close()\n\n\nif __name__ == '__main__':\n # plot_dataset('MNIST')\n # plot_dataset('FashionMNIST')\n # plot_dataset('Poker')\n # plot_dataset('Add10', mode='regression')\n # plot_dataset('Airfoil', mode='regression')\n pass\n","sub_path":"expriment_summary.py","file_name":"expriment_summary.py","file_ext":"py","file_size_in_byte":10543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"190099789","text":"\"\"\"SysMonitor Database migration tool\"\"\"\n\nimport logging\nimport os\nimport importlib\nimport re\nimport ast\n\nfrom playhouse.db_url import connect\nfrom playhouse.migrate import PostgresqlMigrator, SqliteMigrator, MySQLMigrator\n\nfrom sysmonitor.configuration import Configuration\nfrom sysmonitor import release\n\nfrom sysmonitor.models.database import DatabaseVariable\nfrom sysmonitor.models.host import Host, Disk, Resource, Service, ServiceHistory\n\nLOGGER = logging.getLogger(__name__)\n\nclass Migrator():\n \"\"\"\n Migration Tool\n\n It executes migration scriptsw when needed.\n\n This scripts must be located inside a file named migrate.py, under a\n folder with the target version as name and inside the migrations folder.\n Example for a migration targeting version 1.0.0:\n migrations/1.0.1/migrate.py\n\n Inside the file, the migration code mut be inside a function called migrate\n and it receives one argument, the database object\n \"\"\"\n def __init__(self):\n self.config = Configuration()\n db_url = self.config.get(\"database\", \"url\")\n self.database = connect(db_url)\n if \"postgresql\" in db_url:\n self.migrator_class = PostgresqlMigrator\n elif \"mysql\" in db_url:\n self.migrator_class = MySQLMigrator\n elif \"sqlite\" in db_url:\n self.migrator_class = SqliteMigrator\n else:\n raise ValueError(\"Invalid database type for migrations\")\n\n\n def do_migration(self):\n \"\"\"\n Execute the migration.\n\n If no tables exists, it runs peewee create_table method.\n If tables exists, it runs the necessar migration scripts\n \"\"\"\n self.database.connect()\n if self.database.get_tables():\n self.upgrade()\n else:\n self.create()\n self.update_version()\n\n def create(self):\n \"\"\"Create tables using peewee create_tables method\"\"\"\n self.database.create_tables([DatabaseVariable, Host, Disk, Resource,\n Service, ServiceHistory])\n LOGGER.info(\"Created tables\")\n uname = os.uname()\n Host.create(name=uname.nodename, address=\"http://127.0.0.1:8068\",\n requires_authentication=False, active=False,\n nodename=uname.nodename, os=\" \".join(uname))\n LOGGER.info(\"Created a host for this machine\")\n\n def upgrade(self):\n \"\"\"Executes migration scripts\"\"\"\n # Check if upgrade is required\n db_version = ast.literal_eval(DatabaseVariable.get_variable(\"version\"))\n if db_version >= release.version_db:\n LOGGER.debug(\"Database in version %s. Nothing to do.\",\n \".\".join([str(x) for x in release.version_db]))\n return\n\n # Load all available migrations\n migrations_path = os.path.dirname(os.path.abspath(__file__))\n migrations_path = os.path.join(migrations_path, \"migrations\")\n migrations = set()\n for migration in os.listdir(migrations_path):\n # Migration folder must be in format x.x.x\n if not re.match(r\"^\\d.\\d.\\d$\", migration):\n LOGGER.error(\"Invalid migration %s\", migration)\n continue\n migration = [int(x) for x in migration.split(\".\")]\n migrations.add(tuple(migration))\n\n # Discard previous migrations and do a sort\n migrations = sorted([x for x in migrations if x > db_version])\n\n # Executes the required migrations\n migrator = self.migrator_class(self.database)\n for migration in migrations:\n migration_str = \".\".join([str(x) for x in migration])\n migration_file = os.path.join(migrations_path, migration_str,\n \"migrate.py\")\n spec = importlib.util.spec_from_file_location(migration_str,\n migration_file)\n module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(module)\n LOGGER.info(\"Upgrading database to version %s\", migration_str)\n with self.database.atomic():\n module.migrate(migrator)\n self.update_version(migration)\n LOGGER.info(\"Database migrated to version %s\", migration_str)\n\n @staticmethod\n def update_version(version=False):\n \"\"\"\n Update database migration\n\n :param tuple version: New version. If false uses release.version_db\n \"\"\"\n version = release.version_db if not version else version\n DatabaseVariable.set_variable(\"version\", version)\n","sub_path":"sysmonitor/orm/migrator.py","file_name":"migrator.py","file_ext":"py","file_size_in_byte":4639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"94107641","text":"import logging\nimport time\nfrom datetime import datetime, timedelta\n\nimport Data_storage as ds\nimport Offer\nimport config as cfg\nimport request_composition\nfrom constants import HOUSES_CATEGORY_ID\n\nlogging.basicConfig(level=logging.INFO)\n\n\n# TODO: implement changing user agent\n# TODO: compare prices of a same listing\n# TODO: add search parameters to look into smaller market\n# TODO: get exact address from a map\n# TODO: gather list of districts, categories for search\n# TODO: save a phone number\n\n\ndef main():\n \"\"\"Parse offers according to limitations set in config file and in request\n composition.py and create a list with results\"\"\"\n for query in ds.get_parsing_queries():\n offers_added = 0\n\n query_name = query.get(\"Name\")\n category_id = query.get(\"category_id\")\n\n cfg.category_id = category_id\n\n logging.info(f\"Parsing offers for query: {query_name}. \\n\")\n\n list_of_offers = parse_search_results_pages(\n query.get(\"city_id\"),\n query.get(\"region_id\"),\n query.get(\"district_id\"),\n query.get(\"distance\"),\n query.get(\"query_term\"),\n query.get(\"category_id\"),\n )\n\n filtered_list_of_offers = filter_out_existing_offers(\n list_of_offers, category_id\n )\n\n for offer in filtered_list_of_offers:\n time.sleep(4) # sleep before getting next offer details\n try:\n offer_details = Offer.get_offer_details(offer)\n except (Offer.PageNotValid, AttributeError):\n continue\n update_offer_record(offer_details)\n offers_added += 1\n\n logging.info(f\"{query_name} added: {offers_added}.\")\n\n\ndef filter_out_existing_offers(list_of_offers, category_id):\n ids_in_db = ds.existing_offer_ids(category_id)\n\n filtered_list_of_offers = list()\n for offer in list_of_offers:\n try:\n olx_offer_id = int(offer.table[\"data-id\"]) # Get id of an offer\n except TypeError:\n continue\n if olx_offer_id not in ids_in_db:\n filtered_list_of_offers.append(offer)\n\n return filtered_list_of_offers\n\n\ndef parse_search_results_pages(\n city_id, region_id, district_id, distance, query_term, category_id\n):\n \"\"\"\n This function parses all offers from search pages within given limits\n and creates a list of offers with limited info\n available (price, olx_id, title).\n :param city_id:\n :param region_id:\n :param district_id:\n :param distance:\n :param query_term:\n :param category_id:\n :return:\n \"\"\"\n list_of_offers = []\n\n # Don't search for houses on pages above 10, they don't exist.\n if category_id == HOUSES_CATEGORY_ID & cfg.search_pages_lower_limit > 10:\n return list_of_offers\n\n search_url = request_composition.compose_request(\n city_id, region_id, district_id, category_id, distance, query_term\n )\n for current_page in range(\n cfg.search_pages_lower_limit, cfg.search_pages_upper_limit\n ):\n time.sleep(2) # to slow down process for anti-parsing algorithms\n search_url[1][\"page\"] = current_page\n try:\n offers_set = Offer.get_set_of_offers(\n search_url\n ) # Parses offers from a page\n except Offer.PageNotValid:\n continue\n for offer in offers_set:\n list_of_offers.append(\n offer\n ) # Parses offers from all pages in a range and creates list\n logging.info(f\"Number of offers parsed from search: {len(list_of_offers)} \\n\")\n return list_of_offers\n\n\ndef update_offer_record(list_of_offers):\n \"\"\"\n Adds offer record if it doesn't exist in data storage\n :param list_of_offers:\n :return:\n \"\"\"\n for offer in list_of_offers:\n ds.write_to_db(offer)\n\n\nstart_time = datetime.now()\nmain()\nlogging.info(\n f\"--- Process finished in {str(timedelta(seconds=(datetime.now() - start_time).seconds))} ---\"\n)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"329829794","text":"import pandas as pd\nimport Text_Proc_Utils as TPU\n\n# This function returns a dataframe with 2 columns. Category of expenses column as a categorical variable \n# and expense description as string. \ndef Get_Data(File_Path):\n expenses = pd.DataFrame.from_csv(File_Path,index_col= None)\n \n expenses.category = expenses.category.astype(\"category\")\n \n Sentences = expenses['expense description'].tolist()\n \n return Sentences, expenses.category\n\n# This function takes the expenses decription sentences and returns sentence vectors\ndef Get_Feature_Vectors(Sentences,model):\n V=[]\n for sentence in Sentences:\n V.append(TPU.sent_vectorizer(sentence, model))\n return V\n\n","sub_path":"Data_Prep_Utils.py","file_name":"Data_Prep_Utils.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"233723264","text":"# _*_ coding:utf-8 _*_\nimport os,sys,json\nsys.path.append(os.path.dirname(os.path.dirname(__file__)))\nimport requests\nimport urllib3\nurllib3.disable_warnings()\n\nclass SendRequestsHeader():\n def sendRequestsheader(self,apiData):\n \"\"\"\n 发送接口请求\n :param apiData:接口请求数据\n :return: 返回接口响应信息,以json格式\n \"\"\"\n try:\n #发送请求数据\n method = apiData[\"method\"]\n # print(method)\n url = apiData[\"url\"]\n # print(url)\n if apiData[\"params\"] == \"\":\n par = None\n else:\n par = apiData[\"params\"]\n # print(par)\n if apiData[\"headers\"] == \"\":\n h = None\n else:\n h = apiData[\"headers\"]\n print(h)\n if apiData[\"body\"] == \"\":\n body_data = None\n else:\n body_data = apiData[\"body\"]\n\n type = apiData[\"type\"]\n #print(type)\n v = False\n if type == \"data\":\n body = body_data\n #print(body)\n elif type == \"json\":\n body =json.dumps(body_data)\n else:\n body = body_data\n #print(body)\n re =requests.request(method=method,url =url, headers =h,params = par,data=body,verify = v)\n print(re)\n msg = re.headers\n # print(msg)\n # msg['status_code']=re.status_code\n # header = re.headers\n # print(header)\n #print(msg)\n #print(re.status_code)\n return msg\n #print(re.text)\n # if method ==\"get\":\n # re = s.get(url =url, headers =h,params = par,data = body,verify = v)\n # print(re.text)\n # return re\n # elif method == \"post\":\n # re = s.post(url =url, headers =h,params = par,data = body,verify = v)\n # print(re.text)\n # return re\n except Exception as e:\n print(e)","sub_path":"lib/sendrequestheader.py","file_name":"sendrequestheader.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"468742684","text":"from dataAcquisition import User\nfrom dataAcquisition import Wiki\n\nuserIDs = open('UserIDs.txt', 'r')\nfeatures = open('feature.txt', 'w')\n\n\n\ndef reputationFeature(user):\n if user.reputation > 1:\n features.write('0 ')\n else:\n features.write('1 ')\n\ndef badgeCount(user):\n if user.total_badges:\n features.write('0 ')\n else:\n features.write('1 ')\n\nfor userID in userIDs:\n user = User(userID)\n\n #import functions for gathering here\n reputationFeature(user)\n badgeCount(user)\n\n features.write('\\n')\n\nfeatures.close()\nuserIDs.close()\n","sub_path":"featureCollection.py","file_name":"featureCollection.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"225115724","text":"import json\nimport glob\nfrom tqdm import tqdm\nimport statistics\nimport os\nimport math\nfrom collections import defaultdict, Counter, OrderedDict\nimport pickle\nfrom copy import deepcopy\n\n\ndef get_repre(pair):\n h, tmp = pair\n t = list(tmp)\n new_t = ''\n if len(t) == 1:\n new_t = t[0]\n elif len(t) == 2:\n new_t = t[0] + ' and ' + t[1]\n else:\n new_t = ', '.join(t[:-1]) + ', and ' + t[-1]\n return h, new_t\n\ndef get_repre_r(pair):\n h, t = pair\n t = list(t)\n new_t = ''\n if len(t) == 1:\n new_t = t[0]\n elif len(t) == 2:\n new_t = t[0] + ' and ' + t[1]\n else:\n new_t = ', '.join(t[:-1]) + ', and ' + t[-1]\n # print(new_t, h)\n return new_t, h\ndef get_whole(t):\n new_t = ''\n if len(t) == 1:\n new_t = t[0]\n elif len(t) == 2:\n new_t = t[0] + ' and ' + t[1]\n else:\n new_t = ', '.join(t[:-1]) + ', and ' + t[-1]\n return new_t\n\n\npath = 'data/ORIGINALITY/test.json'\npath_f = 'Novelty.txt'\nwf = open(path_f, 'w')\ncount_ = 0\nidds = []\nwith open(path, 'r') as f:\n for line in tqdm(f):\n data = json.loads(line)\n diff_c, diff_rel, txts_list, c2t, c2num, r2num = data['src']\n score = data['score']\n if len(diff_c) == 0 and len(diff_rel) != 0:\n continue \n output = []\n pid = data['pid']\n output.append('id: ' + pid + ' '+ data['title'] + '\\n')\n output.append('score: ' + str(data['score']) + '\\n')\n real_name = {}\n pair_used_for = defaultdict(set)\n compare = defaultdict(set)\n features = defaultdict(set)\n pair_e = defaultdict(set)\n output.append('Strengths:\\n')\n flag = True\n for h, t, r in diff_rel:\n if r == \"USED-FOR\":\n try:\n if c2t[t] in [\"Method\", \"Material\", \"Metric\"] and c2t[h] == 'Task':\n pair_used_for[h].add(t)\n except:\n pair_used_for[h].add(t)\n\n elif r == 'COMPARE':\n if h != t:\n if h in compare:\n compare[h].add(t)\n else:\n compare[t].add(h)\n elif r == 'FEATURE-OF':\n if h != t:\n features[t].add(h)\n elif r == \"EVALUATE-FOR\":\n try:\n if c2t[t] == \"Method\" and c2t[h] in [\"Material\", \"Metric\"]:\n pair_e[t].add(h)\n except:\n pass\n sorted_relation = []\n r = \"USED-FOR\"\n for h, ts in pair_used_for.items():\n pair = (h, ts)\n score = 0\n for t in ts:\n rel = str((h, t, r))\n score += r2num[rel] \n sorted_relation.append((get_repre(pair), score))\n sorted_relation.sort(key=lambda x: x[1], reverse=True)\n for pair, count in sorted_relation:\n if score > 3:\n output.append('\\tThis paper uses novel %s for %s . \\n' % pair)\n else:\n output.append('\\tThis paper uses %s for %s . \\n' % pair)\n # output.append('\\tTerm Frequency:'+ str(count) + '\\n\\n')\n flag = False\n \n if flag:\n sorted_relation = []\n r = \"COMPARE\"\n for h, ts in compare.items():\n pair = (h, ts)\n score = 0\n for t in ts:\n rel = str((h, t, r))\n if rel not in r2num:\n rel = str((t, h, r))\n score += r2num[rel] \n sorted_relation.append((get_repre(pair), score))\n sorted_relation.sort(key=lambda x: x[1], reverse=True)\n for pair, count in sorted_relation:\n output.append('\\tThe paper compare %s with %s . \\n' % pair)\n # output.append('\\tTerm Frequency:'+ str(count) + '\\n\\n')\n flag = False\n\n if flag:\n sorted_relation = []\n r = 'FEATURE-OF'\n for h, ts in features.items():\n pair = (h, ts)\n score = 0\n for t in ts:\n rel = str((t, h, r))\n score += r2num[rel] \n sorted_relation.append((get_repre_r(pair), score))\n sorted_relation.sort(key=lambda x: x[1], reverse=True)\n for pair, count in sorted_relation:\n output.append('\\tThe paper uses %s for %s . \\n' % pair)\n # output.append('\\tTerm Frequency:'+ str(count) + '\\n\\n')\n flag = False\n\n if flag:\n sorted_relation = []\n r = \"EVALUATE-FOR\"\n new_entities = []\n for h, ts in pair_e.items():\n pair = (h, ts)\n score = 0\n new_entities.append(h)\n for t in ts:\n rel = str((t, h, r))\n score += r2num[rel] \n sorted_relation.append((pair, score))\n sorted_relation.sort(key=lambda x: x[1], reverse=True)\n if len(new_entities) > 0:\n output.append('\\tThis paper proposes a new %s. \\n' % get_whole(new_entities))\n\n for pair, count in sorted_relation:\n output.append('\\tThe authors then evaluate %s using %s. \\n' % get_repre(pair))\n # output.append('\\tTerm Frequency:'+ str(count) + '\\n\\n')\n flag = False\n if flag:\n metric = []\n method = []\n task = []\n material = []\n other = []\n for e in diff_c:\n if e not in c2t:\n other.append(e)\n elif c2t[e] == \"Method\":\n method.append(e)\n elif c2t[e] == \"Material\":\n material.append(e)\n elif c2t[e] == \"Metric\":\n metric.append(e)\n elif c2t[e] == 'Task':\n task.append(e)\n else:\n other.append(e)\n method = sorted(method, key=lambda i: c2num[i], reverse=True)\n task = sorted(task, key=lambda i: c2num[i], reverse=True)\n material = sorted(material, key=lambda i: c2num[i], reverse=True)\n o = sorted(other, key=lambda i: c2num[i], reverse=True)\n if score > 3:\n if len(method[:5]) > 0:\n output.append('\\tThe paper proposes novel %s' % get_whole(method[:2] ))\n\n if len(task) > 0:\n output.append(' for %s.\\n' % task[0])\n else:\n output.append('.\\n')\n # output.append('\\tTerm Frequency:')\n for m in method[:5]:\n output.append(str(c2num[m])+ ' ')\n for m in task[:5]:\n output.append(str(c2num[m])+ ' ')\n output.append('\\n\\n')\n flag = False\n elif len(other) > 0:\n output.append('\\tThe paper proposes novel%s' % get_whole(other[:2]))\n\n if len(task) > 0:\n output.append(' for %s.\\n' % task[0])\n else:\n output.append('.\\n')\n # output.append('\\tTerm Frequency:')\n # for m in other[:2]:\n # output.append(str(c2num[m])+ ' ')\n # for m in task[:1]:\n # output.append(str(c2num[m])+ ' ')\n # output.append('\\n\\n')\n flag = False\n else:\n flag = True\n else:\n if len(method[:5]) > 0:\n output.append('\\tThe paper uses %s' % get_whole(method[:5] ))\n\n if len(task) > 0:\n output.append(' for %s.\\n' % task[0])\n else:\n output.append('.\\n')\n # output.append('\\tTerm Frequency:')\n # for m in method[:2]:\n # output.append(str(c2num[m])+ ' ')\n # for m in task[:1]:\n # output.append(str(c2num[m])+ ' ')\n # output.append('\\n\\n')\n flag = False\n elif len(other) > 0:\n output.append('\\tThe paper proposes novel%s' % get_whole(other[:2]))\n\n if len(task) > 0:\n output.append(' for %s.\\n' % task[0])\n else:\n output.append('.\\n')\n # output.append('\\tTerm Frequency:')\n # for m in other[:2]:\n # output.append(str(c2num[m])+ ' ')\n # for m in task[:1]:\n # output.append(str(c2num[m])+ ' ')\n # output.append('\\n\\n')\n flag = False\n else:\n flag = True\n if flag:\n if len(task) > 0:\n output.append('\\tThe paper proposes novel %s .\\n' % get_whole(task[:2]))\n # output.append('\\tTerm Frequency:')\n # for m in task[:2]:\n # output.append(str(c2num[m])+ ' ')\n # output.append('\\n\\n')\n else:\n continue\n \n output.append('\\n')\n output.append('Reference:\\n')\n for txt in data['tgt']:\n output.append(txt + '\\n')\n output.append('\\n\\n\\n')\n idds.append(pid)\n wf.writelines(output)\n count_ += 1\n if count_ %5 == 0:\n wf.write('-'*100)\n wf.write('\\n\\n')\n print(idds)\n idds = [] \nwf.close()","sub_path":"Comment Generation/novelty.py","file_name":"novelty.py","file_ext":"py","file_size_in_byte":9878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"201547748","text":"import bs4\nimport requests\n\nurl = 'https://jadwalsholat.pkpu.or.id/?id=266' # url tempat melakukan scraping\ncontents = requests.get(url)\n# print(contents.text)\nresponse = bs4.BeautifulSoup(contents.text, \"html.parser\")\n# bs4 = package, beautifulsoup = class, contents.text = suply contenst yg berisi request yg mengambil url dari web\ndata = response.find_all('tr','table_highlight')\ndata = data[0] # untuk menghilangkan kurung kurawal, agar data di mulai dari data ke 0\n\nsholat = {} # inisialisasi bahwa sholat merupakan dictionary, yg memiliki nama variabel yang memiliki\n # attribute jam sholatnya\ni = 0\nfor d in data:\n if i == 1: # kenapa di deklarasikan data ke 1, karena data ke 0 = tanggalnya\n sholat['shubuh'] = d.get_text()\n elif i == 2:\n sholat['dhuhur'] = d.get_text()\n elif i == 3:\n sholat['ashar'] = d.get_text()\n elif i == 4:\n sholat['maghrib'] = d.get_text()\n elif i == 5:\n sholat['isya'] = d.get_text()\n i += 1\nprint(sholat)\nprint(sholat['ashar'])","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"537435134","text":"# coding=utf-8\n# Copyright 2020 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Tests for flax modules.\"\"\"\n\nimport functools\nfrom absl.testing import parameterized\nimport tensorflow.compat.v1 as tf\nfrom protein_lm import domains\nfrom protein_lm import models\nfrom protein_lm import modules\n\nlm_cls = functools.partial(\n models.FlaxLM,\n num_layers=1,\n num_heads=1,\n emb_dim=64,\n mlp_dim=64,\n qkv_dim=64)\n\n\nclass ModulesTest(tf.test.TestCase, parameterized.TestCase):\n\n @parameterized.parameters(\n (modules.AddLearnedPositionalEncodings,),\n (modules.AddSinusoidalPositionalEncodings,))\n def test_positional_encodings(self, positional_encoding_module):\n \"\"\"Tests that the model runs with both types of positional encodings.\"\"\"\n domain = domains.FixedLengthDiscreteDomain(vocab_size=2, length=2)\n lm = lm_cls(domain=domain,\n positional_encoding_module=positional_encoding_module)\n lm.sample(1)\n\n\nif __name__ == '__main__':\n tf.test.main()\n","sub_path":"protein_lm/modules_test.py","file_name":"modules_test.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"313630562","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import Http404\nfrom django.shortcuts import render, redirect\nfrom django.template.defaultfilters import slugify\nfrom .forms import DashboardForm\nfrom .models import Dashboard\nfrom .forms import ContactForm\nfrom django.template.loader import get_template\nfrom django.core.mail import EmailMessage, send_mail\nfrom django.template import Context\n\n\n# Create your views here.\n\ndef index(request):\n\n\tdashboards = Dashboard.objects.all()\n\n\treturn render(request, 'collection/index.html', {\n\t\t'dashboards' : dashboards,\n\t\t })\n\ndef dashboard_detail(request, slug):\n\tdashboard = Dashboard.objects.get(slug=slug)\n\n\treturn render(request, 'collection/dashboard_detail.html', {\n\t\t'dashboard' : dashboard,\n\t\t})\n\n@login_required\ndef edit_dashboard(request, slug):\n\tdashboard = Dashboard.objects.get(slug=slug)\n\tif dashboard.user != request.user:\n\t\traise Http404\n\t\t\n\tform_class = DashboardForm\n\n\tif request.method == 'POST':\n\t\tform = form_class(data=request.POST, instance=dashboard)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn redirect('dashboard_detail', slug=dashboard.slug)\n\telse:\n\t\tform = form_class(instance=dashboard)\n\n\treturn render(request, 'collection/edit_dashboard.html', {\n\t\t'dashboard' : dashboard,\n\t\t'form' : form,\n\t\t})\n\n\ndef create_dashboard(request):\n\tform_class = DashboardForm\n\n\tif request.method == 'POST':\n\t\tform = form_class(request.POST)\n\t\tif form.is_valid():\n\t\t\tdashboard = form.save(commit=False)\n\t\t\tdashboard.user = request.user\n\t\t\tdashboard.slug = slugify(dashboard.name)\n\n\t\t\tdashboard.save()\n\n\t\t\treturn redirect('dashboard_detail', slug=dashboard.slug)\n\n\n\telse:\n\t\tform = form_class()\n\n\treturn render(request, 'collection/create_dashboard.html', {\n\t\t'form': form,\n\t\t})\n\ndef browse_by_name(request, initial=None):\n\tif initial:\n\t\tdashboards = Dashboard.objects.filter(name__istartswith=initial)\n\t\tdashboards = dashboards.order_by('name')\n\n\telse:\n\t\tdashboards = Dashboard.objects.all().order_by('name')\n\n\treturn render(request, 'collection/search.html', {\n\t\t'dashboards' : dashboards,\n\t\t'initial' : initial,\n\n\n\t\t})\n\n\n#Contact form:\n\ndef contact(request):\n\tform_class = ContactForm\n\n\tif request.method == 'POST':\n\t\tform = form_class(data=request.POST)\n\n\t\tif form.is_valid():\n\t\t\tcontact_name = form.cleaned_data['contact_name']\n\t\t\tcontact_email = form.cleaned_data['contact_email']\n\t\t\tform_content = form.cleaned_data['content']\n\n\t\t\ttemplate = get_template('contact_template.txt')\n\n\t\t\tcontext = Context({\n\t\t\t\t'contact_name' : contact_name,\n\t\t\t\t'contact_email' : contact_email,\n\t\t\t\t'form_content' : form_content,\n\t\t\t})\n\t\t\tcontent = template.render(context)\n\n\t\t\temail = EmailMessage(\n\t\t\t\t'New contact form submission', \n\t\t\t\tcontent, \n\t\t\t\t'Your website ',\n\t\t\t\t['danilopfe@gmail.com'],\n\t\t\t\theaders = {'Reply-To' : contact_email }\n\t\t\t)\n\t\t\temail.send()\n\t\t\treturn redirect('contact')\n\n\treturn render(request, 'collection/contact.html', {\n\t\t'form' : form_class,\n\n\t})\n\n\n","sub_path":"collection/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"570933801","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef logistic_loss(x):\n\n return np.log(1 + np.exp(1 - x))\n\n\ndef hinge_loss(x):\n\n tmp = 1 - x\n\n tmp[np.where(tmp <= 0)] = 0\n\n return tmp\n\n\ndef squared_hinge_loss(x):\n\n tmp = 1 - x\n\n tmp[np.where(tmp <= 0)] = 0\n\n return np.square(tmp)\n\n\nx = np.arange(-4, 4, 0.001)\n\nplt.plot(x, logistic_loss(x), 'r')\nplt.plot(x, hinge_loss(x), 'g')\nplt.plot(x, squared_hinge_loss(x), 'b')\nplt.legend([\"logistic loss\", \"hinge loss\", \"squared hinge loss\"])\nplt.title(\"Loss function\")\nplt.show()\n","sub_path":"machine_learning/loss_function_plot.py","file_name":"loss_function_plot.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"108592616","text":"# MIT License\r\n\r\n# Copyright (c) 2018 shotariya\r\n\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is\r\n# furnished to do so, subject to the following conditions:\r\n\r\n# The above copyright notice and this permission notice shall be included in all\r\n# copies or substantial portions of the Software.\r\n\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n# SOFTWARE.\r\n\r\n\r\nimport bpy\r\nimport time\r\nimport math\r\nimport os\r\nfrom PIL import Image\r\n\r\n\r\nclass GenTex(bpy.types.Operator):\r\n bl_idname = 'shotariya.gen_tex'\r\n bl_label = 'Save Textures by UVs'\r\n bl_description = ''\r\n bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}\r\n\r\n def execute(self, context):\r\n start_time = time.time()\r\n scn = context.scene\r\n save_path = scn.tex_path\r\n if not save_path:\r\n self.report({'ERROR'}, 'Please select Folder for Combined Texture')\r\n return {'FINISHED'}\r\n bpy.ops.shotariya.uv_fixer()\r\n work = []\r\n for obj in context.scene.objects:\r\n if obj.type == 'MESH':\r\n if not obj.data.uv_layers.active:\r\n continue\r\n mat_len = len(obj.material_slots)\r\n mat_info = [[] for x in range(mat_len)]\r\n tex_info = [[] for x in range(mat_len)]\r\n for face in obj.data.polygons:\r\n face_coords = [obj.data.uv_layers.active.data[loop_idx].uv for loop_idx in face.loop_indices]\r\n mat_info[face.material_index].append(face_coords)\r\n for mat, faces in enumerate(mat_info):\r\n x_list = [math.ceil(poly.x) for face in faces for poly in face if not math.isnan(poly.x)]\r\n y_list = [math.ceil(poly.y) for face in faces for poly in face if not math.isnan(poly.y)]\r\n tex_info[mat] = [max(x_list), max(y_list)]\r\n for index in range(mat_len):\r\n mat = obj.material_slots[index].material\r\n tex_slot = mat.texture_slots[0]\r\n if tex_slot:\r\n if (tex_info[index][0] > 1) or (tex_info[index][1] > 1):\r\n tex = tex_slot.texture\r\n if tex:\r\n if tex.to_save:\r\n tex_info[index].append(bpy.path.abspath(tex.image.filepath))\r\n tex_info[index].append(mat)\r\n if len([True for info in tex_info if len(info) > 2]) != 0:\r\n work.append(True)\r\n for info in tex_info:\r\n if len(info) > 3:\r\n img_name = info[2].split(os.sep)[-1].split('.')[0]\r\n img = Image.open(info[2])\r\n w, h = img.size\r\n if info[0] == 0:\r\n info[0] = 1\r\n if info[1] == 0:\r\n info[1] = 1\r\n if info[0] > 64:\r\n info[0] = 1\r\n if info[1] > 64:\r\n info[1] = 1\r\n result = Image.new('RGBA', (w * info[0], h * info[1]))\r\n for i in range(info[0]):\r\n for j in range(info[1]):\r\n x = i * w\r\n y = j * h\r\n result.paste(img, (x, y, x + w, y + h))\r\n result.save('{}{}{}_uv.png'.format(save_path, os.sep, img_name), 'PNG')\r\n mat = info[3]\r\n mat_index = 0\r\n for index in range(mat_len):\r\n if obj.material_slots[index].material == mat:\r\n mat_index = index\r\n tex_slot = mat.texture_slots[0]\r\n tex = tex_slot.texture\r\n tex.image = bpy.data.images.load('{}{}{}_uv.png'.format(save_path, os.sep, img_name))\r\n for face in obj.data.polygons:\r\n if face.material_index == mat_index:\r\n face_coords = [obj.data.uv_layers.active.data[loop_idx].uv for loop_idx in\r\n face.loop_indices]\r\n for z in face_coords:\r\n z.x = z.x / info[0]\r\n z.y = z.y / info[1]\r\n if not work:\r\n self.report({'ERROR'}, 'All Selected texture UVs bounds are 0-1')\r\n return {'FINISHED'}\r\n bpy.ops.shotariya.list_actions(action='GENERATE_MAT')\r\n bpy.ops.shotariya.list_actions(action='GENERATE_TEX')\r\n print('{} seconds passed'.format(time.time() - start_time))\r\n self.report({'INFO'}, 'Textures were created.')\r\n return{'FINISHED'}\r\n","sub_path":"gen_tex.py","file_name":"gen_tex.py","file_ext":"py","file_size_in_byte":5684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"300736311","text":"import numpy as np\n\nclass PrepareData:\n\n def __init__(self):\n pass\n\n def read_files(self, path, num_samples):\n input_texts = []\n target_texts = []\n input_words = set([])\n target_words = set([])\n\n with open(path, 'r', encoding='utf-8') as file:\n lines = file.readlines()\n for line in lines[: min(num_samples, len(lines) -1)]:\n input_text, target_text = line.split(\"\\t\")[:2]\n target_text = '\\t' + target_text + '\\n'\n input_texts.append(input_text)\n target_texts.append(target_text)\n\n for word in input_text.split(\" \"):\n if word not in input_words:\n input_words.add(word)\n for word in target_text.split(\" \"):\n if word not in target_words:\n target_words.add(word)\n\n return input_texts, target_texts, input_words, target_words\n\n def vocab_generation(self, path, num_samples):\n\n input_texts, target_texts, input_words, target_words = self.read_files(path, num_samples)\n input_words = sorted(list(input_words))\n target_words = sorted(list(target_words))\n self.num_encoder_words = len(input_words)\n self.num_decoder_words = len(target_words)\n self.max_encoder_seq_length = max([len(text.split(\" \")) for text in input_texts])\n self.max_decoder_seq_length = max([len(text.split(\" \")) for text in target_texts])\n\n self.input_word_index = dict([(word ,i) for i, word in enumerate(input_words)])\n self.target_word_index = dict([(word ,i) for i, word in enumerate(target_words)])\n self.reverse_input_word_dict = dict((i,word) for word, i in self.input_word_index.items())\n self.reverse_target_word_dict = dict((i,word) for word, i in self.target_word_index.items())\n\n def process_inputs(self, input_texts, target_texts=None):\n encoder_input_data = np.zeros((len(input_texts), self.max_encoder_seq_length, self.num_encoder_words), dtype='float32')\n decoder_input_data = np.zeros((len(input_texts), self.max_decoder_seq_length, self.num_decoder_words), dtype='float32')\n decoder_target_data = np.zeros((len(input_texts), self.max_decoder_seq_length, self.num_decoder_words), dtype='float32')\n\n if self.mode == 'train':\n for i,(input_text, target_text) in enumerate(zip(input_texts, target_texts)):\n for t, word in enumerate(input_text.split(\" \")):\n try:\n encoder_input_data[i, t, self.input_word_index[word]] = 1.\n except:\n print(f'word {word} encountered for the 1st time, skipped')\n for t, word in enumerate(target_text.split(\" \")):\n decoder_input_data[i, t, self.target_word_index[word]] = 1.\n if t > 0:\n try:\n decoder_target_data[i,t-1, self.target_word_index[word]] = 1.\n except:\n print(f'word {word} encountered for the 1st time, skipped')\n return encoder_input_data, decoder_input_data, decoder_target_data, np.array(input_texts), np.array(target_texts)\n else:\n for i, input_text in enumerate(input_texts):\n for t, word in enumerate(input_text.split(\" \")):\n try:\n encoder_input_data[i, t, self.input_word_index[word]] = 1.\n except:\n print(f'word {word} encountered for the 1st time, skipped')\n\n return encoder_input_data, None, None, np.array(input_texts), None\n\n\n\n\n\n\nif __name__ == \"__main__\":\n prepare_data = PrepareData()\n input_words, target_words = prepare_data.read_files('./fra.txt',10e13)\n print(input_words)\n print(target_words)\n\n","sub_path":"NMT_data_preperation.py","file_name":"NMT_data_preperation.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"448148367","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nfrom natasha import NamesExtractor\r\nimport matplotlib.pyplot as plt\r\n\r\ndata = []\r\ntitles = []\r\ndic = {}\r\n\r\nextractor = NamesExtractor()\r\nr = requests.get('https://yandex.ru/news/export')\r\nhtml = BeautifulSoup(r.content, \"html.parser\")\r\ndata = html.find_all('a', class_=\"link link_theme_normal i-bem\")\r\nfor i in range(len(data)):\r\n data[i] = str(data[i])\r\n index1 = data[i].find(\"href\", 0, len(data[i]))\r\n index2 = data[i].find(\"rss\", 0, len(data[i]))\r\n r = requests.get(data[i][index1 + 6:index2 + 3])\r\n data[i] = BeautifulSoup(r.content, \"html.parser\")\r\n data[i] = str(data[i].findAll('title'))\r\n titles.append(extractor(data[i]))\r\n for match in titles[i]:\r\n start, stop = match.span\r\n if (dic.get(data[i][start:stop], -1) == -1):\r\n dic[data[i][start:stop]] = 1\r\n else:\r\n dic[data[i][start:stop]] += 1\r\ngis = plt.subplot()\r\ngis.bar(dic.keys(), dic.values())\r\nplt.show()\r\n","sub_path":"news_collection.py","file_name":"news_collection.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"420870279","text":"#!/usr/bin/python3\n\nimport pigpio # using this for hardware PWM, software is not stable!!!\nimport signal\nimport time\nimport math\nimport signal\nimport RPi.GPIO as GPIO # using RPi.GPIO for non-PWM\nimport random\n\n# GPIO pin numbers\nSTR = 17\nDATA = 27\nCLK = 22\nPWM_PIN = 12\nPWM_FREQ = 400 # frequency of PWM\nCHANNELS = 32; # number of output channels\nFPS = 30; # main refresh rate = frames per second\ncounter = 0\nvalue = 0b11111111111111111111111111111111 # testing purposes\n\n\nPWM = pigpio.pi()\nif not PWM.connected:\n\texit()\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(STR, GPIO.OUT, initial=GPIO.LOW) # make pin into an output\nGPIO.setup(DATA, GPIO.OUT, initial=GPIO.LOW) # make pin into an output\nGPIO.setup(CLK, GPIO.OUT, initial=GPIO.LOW) # make pin into an output\n\ndef regClear():\n\tGPIO.output(DATA, 0)\n\tfor i in range(CHANNELS):\n\t\tGPIO.output(CLK, 0)\n\t\tGPIO.output(CLK, 1)\n\tGPIO.output(CLK, 0)\n\tGPIO.output(STR, 1)\n\tGPIO.output(STR, 0)\n\ndef regOutput(value):\n\tfor i in range(CHANNELS):\n\t\tGPIO.output(CLK, 0)\n\t\tGPIO.output(DATA, value >> (CHANNELS - i - 1) & 1)\n\t\tGPIO.output(CLK, 1)\n\tGPIO.output(CLK, 0)\n\tGPIO.output(STR, 1)\n\tGPIO.output(STR, 0)\n\tGPIO.output(DATA, 0)\n\ndef keyboardInterruptHandler(signal, frame):\n\tprint()\n\tprint(\"KeyboardInterrupt (ID: {}) has been caught. Cleaning up...\".format(signal))\n\tregClear()\n\tGPIO.cleanup()\n\tPWM.hardware_PWM(PWM_PIN, PWM_FREQ, 0)\n\tPWM.stop()\n\texit(0)\n\ndef main():\n\n\tprint(\"Ctrl C to quit\")\n\n\tglobal counter\n\tglobal value\n\n\tregClear()\n\n\twhile True:\n\n\t\tregOutput( 1 << (counter % 32) )\n\n\t\tif (counter % 300 == 150):\n\t\t\tPWM.hardware_PWM(PWM_PIN, PWM_FREQ, 1000000 )\n\t\telif (counter % 300 == 0):\n\t\t\tPWM.hardware_PWM(PWM_PIN, PWM_FREQ, 100000 )\n\n\t\tcounter += 1\n\t\ttime.sleep(1)\n\nsignal.signal(signal.SIGINT, keyboardInterruptHandler)\n\nmain()","sub_path":"Python/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"360792806","text":"# Modules\nimport os\nimport csv\n\n#Set up path for file\ncsvpath=os.path.join(\"..\", \"Resources\", \"budget_data.csv\" )\n#print(csvpath)\n\ntotal_months=0\ntotal_profit=0\nprevious_value=0\ncurrent_value=0\nlist_changes=[]\nlist_dates=[]\n\nprint(\"Financial Analysis\")\nprint(\"---------------------\")\n\n#Open the csv file\nwith open(csvpath, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n#print(csvreader)\n\n#Read the header row\n csv_header=next(csvreader)\n#print(f\"CSV Header: {csv_header}\")\n\n#Read each row of data after the header\n for row in csvreader:\n\n #Determine total number of months\n total_months=total_months+1\n #current_value=(row[0])\n\n #Determine total profit over entire period\n total_profit=total_profit+int(row[1])\n current_value=int(row[1])\n\n # Calculate the average of the changes in Profit/Lossess over the entire period, first calculate change\n monthly_diff=current_value-previous_value\n \n #Store changes in list\n list_changes.append(monthly_diff)\n \n #Store dates in list\n list_dates.append(row[0])\n \n previous_value=current_value\n #avg_monthly_diff=sum[list_changes]\n\ndel list_changes[0]\ndel list_dates[0]\n#print(list_changes)\n#print(list_dates)\n\n# Calculate the average of the changes in Profit/Lossess over the entire period\naverage = sum(list_changes) / len(list_changes)\n\n# Determine the greatest increase in profits (date and amount) over the entire period\nmaximum=list_changes.index(max(list_changes))\n\n# Determine the greatest decrease in losses (datea and amount) ove the entire period\nminimum=list_changes.index(min(list_changes))\n\nprint(\"Total Months: \" + str(total_months))\nprint(\"Total: $\"+str(total_profit))\nprint(\"Average Change: $\" +str(round(average, 2)))\nprint(\"Greatest Increase in Profits: \" + str(list_dates[maximum]) +\" \"+str(list_changes[maximum]))\nprint(\"Greatest Decrease in Profits: \" + str(list_dates[minimum]) +\" \"+ str(list_changes[minimum]))\n#print(list_changes)\n\n#print(row)","sub_path":"PyBank/Homework/main_1.py","file_name":"main_1.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"74518575","text":"# coding=utf-8\r\n\r\n\"\"\"\r\n309. Best Time to Buy and Sell Stock with Cooldown My Submissions QuestionEditorial Solution\r\nTotal Accepted: 13833 Total Submissions: 37785 Difficulty: Medium\r\nSay you have an array for which the ith element is the price of a given stock on day i.\r\n\r\nDesign an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:\r\n\r\nYou may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).\r\nAfter you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)\r\nExample:\r\n\r\nprices = [1, 2, 3, 0, 2]\r\nmaxProfit = 3\r\ntransactions = [buy, sell, cooldown, buy, sell]\r\nhttps://discuss.leetcode.com/topic/31349/7-line-java-only-consider-sell-and-cooldown\r\n\"\"\"\r\n\r\n\r\nclass Solution(object):\r\n def maxProfit(self, prices):\r\n \"\"\"\r\n :type prices: List[int]\r\n :rtype: int\r\n \"\"\"\r\n if prices is None or len(prices) <= 1:\r\n return 0\r\n if len(prices) == 2:\r\n return max(prices[1] - prices[0], 0)\r\n profit1 = 0\r\n profit2 = 0\r\n for i in range(1, len(prices)):\r\n copy = profit1\r\n profit1 = max(profit1 + prices[i] - prices[i - 1], profit2)\r\n profit2 = max(copy, profit2)\r\n\r\n return max(profit1, profit2)\r\n\r\n\r\nif __name__ == '__main__':\r\n print ((Solution().maxProfit([1, 2, 3, 0, 2, 4])))\r\n","sub_path":"zishell/solution/medium/solution309_maxProfit.py","file_name":"solution309_maxProfit.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"347635577","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*\nfrom os.path import basename\nfrom unittest import main, TestCase\nfrom assert_is import *\nfrom pgvcsddl import ddl, parent_path\n\n\nclass Test(TestCase):\n def test(self):\n path=\"SCHEMA/public/TABLE/tablename\"\n oid=88\n sql=\"sql\"\n _ddl=ddl(path=path,oid=oid,sql=sql)\n eq_(_ddl.files[\"%s.oid\" % path],oid)\n eq_(_ddl.files[\"%s.sql\" % path],sql)\n refs=[parent_path(path)]\n eq_(_ddl.files[\"%s.references\" % path],\"\\n\".join(refs))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tests/ddl/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"176660686","text":"__author__ = \"Poonam Yadav\"\n__copyright__ = \"Copyright 2017, The Databox Project\"\n__credits__ = [\"Databox team\"]\n__license__ = \"GPL\"\n__version__ = \"0.0.1\"\n__maintainer__ = \"Poonam Yadav\"\n__email__ = \"p.yadav@acm.org\"\n__status__ = \"Development\"\n\n#This code is setup for testing python library outside databox. Inside Databox, STORE_URI Will be extrated from env DATABOX_ZMQ_ENDPOINT.\n# ARBITER URI will be drived from that as well (todo)\n\nimport sys\nfrom flask import Flask\nimport ssl\nimport os\nimport time\n\nsys.path.insert(1, '../')\nfrom lib import core_store as databox #main function as providing the storeclient of core store.\nfrom lib import config as config\nimport datetime as datetime\n\nTEST_STORE_URI = os.environ.get('DATABOX_ZMQ_ENDPOINT') or \"tcp://127.0.0.1:5555\"\nTEST_ARBITER_URI = os.environ.get('DATABOX_ARBITER_ENDPOINT') or \"tcp://127.0.0.1:4444\"\nDATA_SOURCE_ID = str(datetime.date.today())\n\n#newKVStore = databox.newKeyValueClient(TEST_STORE_URI, TEST_ARBITER_URI, False)\n#res = newKVStore.write(\"testdata1\", 'KeyWrite', '{\\\"TEST\\\": \\\"data\\\"}', 'JSON')\n#res = newKVStore.read(\"testdata1\", 'KeyWrite','JSON')\n#print(\"Read data from store \" + str(res))\n\nnewTSStore = databox.newTimeSeriesBlobClient(TEST_STORE_URI, TEST_ARBITER_URI, False)\ntimeline = databox.newDataSourceMetadata()\ntimeline['Description'] = 'Twitter user timeline data'\ntimeline['ContentType'] = 'application/json'\ntimeline['Vendor'] = 'Databox Inc.'\ntimeline['DataSourceType'] = 'testdata1'\ntimeline['DataSourceID'] = 'testdata1'\ntimeline['StoreType'] = 'ts'\n\ntry:\n newTSStore.RegisterDatasource(timeline)\nexcept ValueError:\n print(\"error in registoring datastore\")\ncat = newTSStore.GetDatasourceCatalogue()\n\nres = newTSStore.write('testdata1','{\\\"idx\\\": \\\"16\\\"}', contentFormat ='JSON')\n\nres1 = newTSStore.latest('testdata1')\nif(res1):\n print(\"Data res1 latest from the store \" + str(res1))\n\nres2 = newTSStore.earliest('testdata1')\nif(res2):\n print(\"Data res2 earliest from the store \" + str(res2))\n\nres = newTSStore.write('testdata1','{\\\"idx\\\": \\\"17\\\"}', contentFormat ='JSON')\n\nres3 = newTSStore.lastN('testdata1', 1)\nif(res3):\n print(\"Data res3 last 1 from the store \" + str(res3))\n\nres4 = newTSStore.lastN('testdata1', 2)\nif(res4):\n print(\"Data res4 last 2 from the store \" + str(res4))\n\nres5 = newTSStore.since('testdata1', 1570575084924)\nif(res5):\n print(\"Data res5 since the time<1570575084924> from the store \" + str(res5))\n\n\nres6 = newTSStore.range('testdata1', 1570575084924, 1570575441326)\nif(res6):\n print(\"Data res6 in range<1570575084924, 1570575441326> from the store \" + str(res6))\n\n\nres7 = newTSStore.writeAt('testdata1',1570575084925,'{\\\"idx\\\": \\\"20\\\"}')\n\nres8 = newTSStore.latest('testdata1')\n\nif(res8):\n print(\"Data res8 lastest from the store \" + str(res8))\n\n\n#app = Flask(__name__)\n#credentials = config.getHttpsCredentials()\n#fp_cert = open(os.path.abspath(\"certnew.pem\"), \"w+\")\n#fp_cert.write(str(credentials['cert']))\n#fp_cert.close()\n\n#fp_key = open(os.path.abspath(\"keynew.pem\"), \"w+\")\n#fp_key.write(str(credentials['key']))\n#fp_key.close()\n\n#ctx = ('certnew.pem', 'keynew.pem')\n\n#@app.route(\"/ui\")\n#def hello():\n# return \"Hello World!\"\n\n#if __name__ == \"__main__\":\n# print(\"A Databox Driver\")\n #time.sleep(500)\n #app.run(host='0.0.0.0', port=8080, ssl_context=ctx)\n\n","sub_path":"python/driver/drivertest.py","file_name":"drivertest.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"262890362","text":"#!/usr/bin/python3\n\"\"\"\nSet of functions used to call a series of algorithms used to visualize the object localization of a pre-trained \nnetwork in PyTorch. The different algorithms are discussed in several papers, while the implementation is based, \nroughly, on work in the following repository (https://github.com/sar-gupta/weakly-supervised-localization-survey)\n\"\"\"\n\nimport numpy as np\nimport PIL\n\n\nimport torch\nimport torchvision\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\ndef saliency_map_general(model, input, label, plot = False):\n \"\"\"\n saliency_map_general: implementation to return the most general form of the saliency map, informing\n on the regions of interest that activate a specific label.\n Args:\n - model: (PyTorch) Trained model trying to understand \n - input: Image to be classfied and understood, passed as a PyTorch tensor (C x W x H)\n - label: Class to identify the regions of interest\n return: numpy array with heatmap data\n \"\"\"\n input = Variable(input.unsqueeze_(0),requires_grad = True)\n output = model.forward(input)\n model.zero_grad()\n\n output[0][label].backward()\n\n grads = input.grad.data.clamp(min=0)\n grads.squeeze_()\n grads.transpose_(0,1)\n grads.transpose_(1,2)\n grads = np.amax(grads.cpu().numpy(), axis=2)\n \n grads -= grads.min()\n grads /= grads.max()\n \n grads *= 255\n grads = grads.astype(int)\n \n return grads\n\n\ndef guided_saliency_map(model, input, label, plot = False):\n \"\"\"\n guided_saliency_map: implementation to return a guided saliency map, informing\n on the regions of interest that activate a specific label.\n Args:\n - model: (PyTorch) Trained model trying to understand \n - input: Image to be classfied and understood, passed as a PyTorch tensor (C x W x H)\n - label: Class to identify the regions of interest\n return: numpy array with heatmap data \n \"\"\"\n input = Variable(input.unsqueeze_(0), requires_grad=True)\n \n try:\n h = [0]*len(list(model.modules()))\n\n def hookfunc(module, gradInput, gradOutput):\n return tuple([(None if g is None else g.clamp(min=0)) for g in gradInput])\n\n for j, i in enumerate(list(model.modules())):\n h[j] = i.register_backward_hook(hookfunc)\n\n output = model.forward(input)\n model.zero_grad()\n\n\n output[0][label].backward()\n\n for i in range(len(list(model.modules()))):\n h[i].remove()\n except Exception as e:\n print(e)\n for i in range(len(list(model.modules()))):\n h[i].remove()\n \n grads = input.grad.data.clamp(min=0)\n grads.squeeze_()\n grads.transpose_(0,1)\n grads.transpose_(1,2)\n grads = np.amax(grads.cpu().numpy(), axis=2)\n \n grads -= grads.min()\n grads /= grads.max()\n \n grads *= 255\n grads = grads.astype(int)\n\n return grads\n\ndef gradcam(model, input, label, layer_name, plot=False):\n \"\"\"\n gradcam: implementation to return a class activation map using the gradient of class score with each \n of last conv layer filters. Calculate weighted sum of gradients and filters to finally obtain a map \n of size equal to size of filters.\n Args:\n - model: (PyTorch) Trained model trying to understand \n - input: Image to be classfied and understood, passed as a PyTorch tensor (C x W x H)\n - label: Class to identify the regions of interest\n - layer_name: Name of the layer to target, should be the last CNN.\n return:\n PIL image with cativation map\n \"\"\"\n imgs_shape = (input.shape[1], input.shape[2])\n rs = torchvision.transforms.Resize( imgs_shape )\n\n #find the right layer\n last_conv = None\n for name, item in model._modules.items():\n if name == layer_name:\n last_conv = item\n\n if last_conv == None:\n print('Cant find target layer')\n return None\n\n pre_image = input\n global gcdata\n global gcgrads\n\n def bhook(module, gradInputs, gradOutputs):\n global gcgrads\n gcgrads = gradOutputs\n\n def fhook(module, input, output):\n global gcdata\n gcdata = output\n \n hb = last_conv.register_backward_hook(bhook)\n hf = last_conv.register_forward_hook(fhook)\n \n out = model(input.unsqueeze_(0))\n model.zero_grad()\n out[0, label].backward()\n \n hb.remove()\n hf.remove()\n \n gcdata = gcdata[0]\n gcgrads = gcgrads[0].squeeze()\n \n gcgrads = gcgrads.mean(dim=2, keepdim=True)\n gcgrads = gcgrads.mean(dim=1, keepdim=True)\n #\n gcdata = gcdata.mul(gcgrads)\n gcdata = gcdata.sum(dim=0, keepdim=True)\n gcdata = gcdata.clamp(min=0)\n \n gcdata -= gcdata.min()\n gcdata /= gcdata.max()\n\n toi = torchvision.transforms.ToPILImage()\n gcdata = np.array(rs(toi(gcdata.data.cpu())))\n\n input.squeeze()\n \n return gcdata\n\ndef guided_gradcam(model, input, label,layer_name, plot = False):\n \"\"\"\n guided_gradcam: returns a combination of a guided saliency map and class activation map. this combines \n the sensitivity to different classes from gradcam toguether with the greater resolution of the\n saliency map.\n Args:\n - model: (PyTorch) Trained model trying to understand \n - input: Image to be classfied and understood, passed as a PyTorch tensor (C x W x H)\n - label: Class to identify the regions of interest\n - layer_name: Name of the layer to target, should be the last CNN.\n return:\n PIL image with cativation map\n \"\"\"\n gc = gradcam(model, input, label, layer_name, plot=False)\n\n guided = guided_saliency_map(model=model, input=input[0], label=label, plot=False)\n gc = gc * guided\n \n rs = torchvision.transforms.Resize((32,32))\n\n \n gc -= gc.min()\n gc = np.divide(gc, gc.max())\n gc *= 255\n gc = gc.astype(int)\n\n return gc\n\ndef smooth_guided_saliency_map(model, input, label, transform,x=10, percent_noise=10, plot = True):\n \"\"\"\n smooth_guided_saliency_map: Implementation of guided saliency map accounting for the fact \n small, local variations in the local derivatives lead to the apparent noise one sees. This implementation smooths\n these.\n Args:\n - model: (PyTorch) Trained model trying to understand \n - input: Image to be classfied and understood, passed as a PyTorch tensor (C x W x H)\n - x: Number fo times to sample for the smoothing\n - percent_nois: Percentage of noise to be itroduced during sampling for smoothing\n return:\n PIL image with cativation map\n \"\"\"\n tensor_input = input\n \n final_grad = torch.zeros(input.shape).cuda()\n final_grad = final_grad.unsqueeze(0)\n \n h = [0]*len(list(model.modules()))\n\n def hookfunc(module, gradInput, gradOutput):\n return tuple([(None if g is None else g.clamp(min=0)) for g in gradInput])\n\n for j, i in enumerate(list(model.modules())):\n h[j] = i.register_backward_hook(hookfunc)\n \n for i in range(x):\n temp_input = tensor_input\n noise = torch.from_numpy(np.random.normal(loc=0, scale=(percent_noise/100) * \n (tensor_input.max() - tensor_input.min()), \n size=temp_input.shape)).type(torch.cuda.FloatTensor)\n temp_input = (temp_input.cuda() + noise).cpu().numpy()\n temp_input = np.transpose(temp_input, (1,2,0) )\n temp_input = PIL.Image.fromarray(temp_input.astype(np.uint8))\n temp_input = Variable(transform(temp_input).unsqueeze(0).cuda(), requires_grad=True)\n\n output = model.forward(temp_input)\n model.zero_grad()\n output[0][label].backward()\n final_grad += temp_input.grad.data\n \n for i in range(len(list(model.modules()))):\n h[i].remove()\n \n grads = final_grad/x\n grads = grads.clamp(min=0)\n grads.squeeze_()\n grads.transpose_(0,1)\n grads.transpose_(1,2)\n grads = np.amax(grads.cpu().numpy(), axis=2)\n \n grads -= grads.min()\n grads /= grads.max()\n \n grads *= 255\n grads = grads.astype(int)\n\n return grads\n\ndef smooth_guided_gradcam(model, input, label, transform, layer_name, plot = False ):\n guided = smooth_guided_saliency_map(model, input, label,transform = transform, plot = False)\n gc = gradcam(model, input, label, layer_name = layer_name, plot=False)\n gc = gc * guided\n \n rs = torchvision.transforms.Resize((32,32))\n\n \n gc -= gc.min()\n gc = np.divide(gc, gc.max())\n gc *= 255\n gc = gc.astype(int)\n\n return gc\n","sub_path":"Utils/visualize_object_survey.py","file_name":"visualize_object_survey.py","file_ext":"py","file_size_in_byte":8615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"179635448","text":"# html to markdown\n# tistory(hmtl) 블로그를 github(markdown) 블로그로 옮기는 자동화 작업\n\n# 참고 자료\n# https://kimdoky.github.io/python/2017/06/12/python-urllib.html\n# https://jungwoon.github.io/python/crawling/2018/04/12/Crawling-2/\n# convert HTML to Markdown (https://www.browserling.com/tools/html-to-markdown)\n# python-markdownify (https://github.com/matthewwithanm/python-markdownify)\n\nfrom selenium import webdriver as wd\nfrom bs4 import BeautifulSoup as bs\n\n# Convert HTML to Markdown\nfrom markdownify import markdownify as md\n\nimport os\nimport urllib.request as req\n\n# 절대적 대기\nimport time\n\n# 선수 데이터\nmain_url = \"https://pakpark.tistory.com/\"\nstart = \"6\"\n\n# 드라이버 로드\ndriver = wd.Chrome(executable_path='/Users/parkyounghwan/git/Crawling/BlogTransfer/chromedriver')\n\n# 사이트 접속\ndriver.get(main_url + start)\n\narticle = driver.find_element_by_css_selector('#cMain>#mArticle')\n\n# 제목 찾기\ntitle = article.find_element_by_css_selector('.area_title>h3').text\ntitle = title.replace(' ', '-')\n\n# 카테고리 나누기\nif title.find('[') == 0:\n category = title[title.find('[') + 1:title.find(']')]\nelse:\n category = 'pakpark'\n\n# 날짜 찾기\nuserDateInfo = article.find_element_by_css_selector('.area_title>.info_post').text\ndate = userDateInfo[14:25]\ndate = date.replace(\".\", \"-\")\n\n# 내용 찾기\nsite = bs(req.urlopen(main_url + start), \"html.parser\")\narticle = site.find(\"div\", {\"class\":\"area_view\"})\n\ncontent = \"\"\nfor tag in article.findAll(\"p\"):\n content += md(str(tag)) # html to markdown\n\n# 지킬 content 형식\njekyllform = '''---\nlayout: post\ntitle: input-title\ndate: input-date\ncategories: pakpark\ncomments: false\n---\n\n'''\n\njekyllform = jekyllform.replace('input-title', '\"' + title + '\"')\njekyllform = jekyllform.replace('input-date', date)\n\nif category != 'pakpark':\n jekyllform = jekyllform.replace('pakpark', category)\n\n# 파일 이름\nfilename = date + \"-\" + title\nfilename = filename.replace(\" \", \"\")\n\n# 파일 저장 (디렉터리 확인 -> (디렉터리 생성))\ndir_path = '/Users/parkyounghwan/git/parkyounghwan.github.io/_posts/'\n\ntry:\n if not os.path.exists(dir_path + category):\n os.makedirs(os.path.join(dir_path + category))\n print(\"디렉토리 생성: \", category)\n\n dir_path += category\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n print(\"Failed to create directory!!!!\")\n raise\n\n# 파일 쓰기(write)\nfile_path = os.path.join(dir_path, filename + '.md')\nfid = open(file_path, 'w')\n\nif os.path.isfile(file_path):\n fid.write(jekyllform)\n fid.write(content)\n\nfid.close()\n\n# 다음 사이트 접속\n\n# 절대적 대기\ntime.sleep(3)\n\n# 종료\ndriver.close()\ndriver.quit()","sub_path":"BlogTransfer/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"386892405","text":"#!/usr/local/bin/python3\n# -*- coding: UTF-8 -*-\n\nimport requests\n\ntaskListURL = 'http://pm.jieniu.cc/issues?assigned_to_id=me&set_filter=1&sort=priority%3Adesc%2Cupdated_on%3Adesc'\n\ndef close():\n\tresponse = requests.get(taskListURL)\n\tprint(response.json())\n\nif __name__ == '__main__':\n\tclose()\n","sub_path":"Util/ClosePMTask.py","file_name":"ClosePMTask.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"575922303","text":"from django.http import JsonResponse, QueryDict\nfrom django.utils import timezone\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom chat_bot.models import Dictionary\n\nimport json\n\n@csrf_exempt\ndef dictionaries(request):\n if request.method == \"GET\":\n _dictionaries = Dictionary.objects.all()\n\n # hanle bot_id\n if 'bot_id' in request.session:\n bot_id = request.session['bot_id']\n _dictionaries = _dictionaries.filter(bot_id__exact=bot_id)\n\n return JsonResponse(list(_dictionaries.values()), safe=False)\n elif request.method == \"POST\":\n params = json.loads(request.body)\n Dictionary.objects.create(\n bot_id=bot_id,\n word=params.get(\"word\"),\n synonym=params.get(\"synonym\"),\n created_time=timezone.now()\n )\n return JsonResponse({\"status\": 200}, safe=False)\n\n\n@csrf_exempt\ndef dictionary_detail(request, id):\n if request.method == 'GET':\n _dictionaries = list(Dictionary.objects.filter(id=id).values())\n\n if not _dictionaries:\n return JsonResponse(None, safe=False)\n\n return JsonResponse(_dictionaries[0], safe=False)\n elif request.method == \"PUT\":\n params = json.loads(request.body)\n dictionary = Dictionary.objects.get(id=id)\n dictionary.word = params.get('word')\n dictionary.synonym = params.get('synonym')\n dictionary.updated_time = timezone.now()\n dictionary.save()\n return JsonResponse({\"status\": 200}, safe=False)\n elif request.method == \"DELETE\":\n dictionary = Dictionary.objects.get(id=id)\n dictionary.delete()\n return JsonResponse({\"status\": 200}, safe=False)\n\n","sub_path":"tdai/api/views/view_dictionary.py","file_name":"view_dictionary.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"17654673","text":"#!/usr/bin/env python3\n\n# Libraries\nimport time\nimport pika\nimport ot_data_pb2\nimport hiota_message_pb2\nimport common_pb2\nimport os\nimport json\nfrom datetime import datetime\nfrom influxdb import InfluxDBClient\nimport urllib3\nimport hiota_alert\n\n# Disable the warnings\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n# Configurables\nrabbit_username = str(os.environ['AMQP_USERNAME'])\nrabbit_password = str(os.environ['AMQP_PASSWORD'])\namqp_broker = str(os.environ['AMQP_HOSTNAME'])\namqp_port = int(os.environ['AMQP_PORT'])\ndebug = int(os.environ['AMQP_DEBUG_BOOLEAN'])\nthreshold_value = float(os.environ[\"THRESHOLD_VALUE\"])\ntrace_id = str(os.environ['TRACE_ID'])\ninput_binding_key = str(os.environ['INPUT_BINDING_KEY'])\ninput_queue = str(os.environ['INPUT_QUEUE'])\noutput_binding_key = str(os.environ['OUTPUT_BINDING_KEY'])\nexchange_name = str(os.environ[\"EXCHANGE_NAME\"])\ndiscard_alert_value = int(os.environ[\"DISCARD_ALERT_VALUE\"])\nsave_to_influx = int(os.environ[\"STORE_ALERTS\"])\ninflux_hostname = str(os.environ[\"DEMO_INFLUX_HOSTNAME\"])\ninflux_port = int(os.environ[\"DEMO_INFLUX_PORT\"])\ninflux_username = str(os.environ[\"INFLUX_USERNAME\"])\ninflux_password = str(os.environ[\"INFLUX_PASSWORD\"])\ndata_source = str(os.environ[\"SOURCE\"])\ndata_to_process = str(os.environ[\"DATA_MODEL\"])\ndatabase = str(os.environ[\"DATA_BASE_NAME\"])\nalerts_table = str(os.environ[\"ALERTS_TABLE_NAME\"])\nseverity_level = int(os.environ[\"ALERT_SEVERITY\"])\n\n# Create a handler to process each message as it comes in\ndef processmessage(ch, method, properties, body):\n\n if debug:\n print(\"Processing a message.\")\n\n # Recieve the message and parse out the data\n message = hiota_message_pb2.HiotaMessage()\n message.ParseFromString(body)\n pay_load = (hiota_message_pb2.HiotaMessage(id=message.id, created=message.created, trace_id=[trace_id], ot_data=message.ot_data))\n\n if debug:\n print(pay_load)\n\n # Handle roll, pitch, yaw data from iPhone\n if data_source == \"iphone\" and data_to_process == \"json\":\n # Get the value\n json_data = json.loads(message.ot_data.data_point.value.binary)\n\n try:\n yaw = json_data[\"yaw\"]\n roll = json_data[\"roll\"]\n pitch = json_data[\"pitch\"]\n\n # Debug\n if debug:\n print(json_data)\n\n # If the user wants to discard the alerted value\n if abs(yaw) > threshold_value or abs(roll) > threshold_value or abs(pitch) > threshold_value:\n # Log the value out to the terminal\n alert_msg = \"ALERT!! The absolute value is over \" + str(threshold_value) + \\\n \". Current values are (yaw: \" + str(yaw) + \", roll: \" + str(roll) + \", pitch: \" + \\\n str(pitch) + \")\"\n print(alert_msg)\n hiota_alert.hiota_alert_message_pop(alert_msg, severity=severity_level)\n # If the user wants to save the data to an influx table\n if save_to_influx:\n # Create local time variable\n local_time = datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%S.%fZ\")\n # Switch to Database\n client.switch_database(database)\n # Influx data\n influx_data = [\n {\n \"measurement\": alerts_table,\n \"tags\": {},\n \"time\": local_time,\n \"fields\": {\n \"yaw\": yaw,\n \"roll\": roll,\n \"pitch\": pitch\n }\n }\n ]\n # Write the data to influx\n client.write_points(influx_data)\n except KeyError:\n print(\"Data does not include 'yaw,' 'pitch,' and 'roll.' Your configuration is set up to read iPhone-JSON data for yaw, pitch, and roll.\")\n\n # Handle data coming from the data pump in xhiota format\n elif data_source == \"datapump\":\n # Get the value\n value = message.ot_data.data_point.value.sint64\n\n # Debug\n if debug:\n print(pay_load)\n\n # If the user wants to discard the alerted value\n if value > threshold_value:\n # Log the value out to the terminal\n alert_msg = \"ALERT!! The value is over \" + str(threshold_value) + \". Current value is \" + str(value)\n print(alert_msg)\n hiota_alert.hiota_alert_message_pop(alert_msg, severity=severity_level)\n if not discard_alert_value:\n # Serialize the payload (must use Protobuf serialization)\n pay_load = pay_load.SerializeToString()\n # Publish the message back to the Lumada system so it can be sent to the database\n channel.basic_publish(exchange=exchange_name, routing_key=output_binding_key, body=pay_load)\n else:\n # Serialize the payload (must use Protobuf serialization)\n pay_load = pay_load.SerializeToString()\n # Publish the message back to the Lumada system so it can be sent to the database\n channel.basic_publish(exchange=exchange_name, routing_key=output_binding_key, body=pay_load)\n\n# Connect to RabbitMQ AMQP instance\ncredentials = pika.PlainCredentials(username=rabbit_username, password=rabbit_password)\nconnection_params = pika.ConnectionParameters(host=amqp_broker, port=amqp_port, credentials=credentials, connection_attempts=5, socket_timeout=5, ssl=True)\n\n# Create a client to connect with Influxdb\nclient = InfluxDBClient(host=influx_hostname, port=influx_port, username=influx_username, password=influx_password, ssl=True, verify_ssl=False)\n\n# Infinite loop\ntry:\n\n if debug:\n print(\"Threshold app starting.\")\n\n connection = pika.BlockingConnection(connection_params)\n channel = connection.channel()\n\n if debug:\n print(\"Pika connections set.\")\n\n # Create a queue and bind to it\n channel.queue_declare(queue=input_queue)\n channel.queue_bind(exchange=exchange_name, queue=input_queue, routing_key=input_binding_key)\n\n if debug:\n print(\"Bound to pika queue.\")\n\n # Create a callback method to handle incoming messages\n channel.basic_consume(processmessage, queue=input_queue, no_ack=True)\n channel.start_consuming()\n\nexcept KeyboardInterrupt:\n connection.close()\n print(\"Script Exited\")\n\nexcept pika.exceptions.ConnectionClosed:\n print(\"Unable to connect to AMQP broker. The connection timed out.\")\n print(\"Input Binding Key: \" + input_binding_key)\n print(\"Input Queue: \" + input_queue)\n print(\"Output Binding Key: \" + output_binding_key)\n print(\"Trace ID: \" + trace_id)\n print(\"Exchange Name: \" + exchange_name)\n print(\"Rabbit User Name: \" + rabbit_username)\n print(\"Rabbit Password: \" + rabbit_password)\n print(\"Broker IP: \" + amqp_broker)\n print(\"Broker Port: \" + str(amqp_port))\n print(\"Debug Flag: \" + str(debug))\n print(\"Threshold Value: \" + str(threshold_value))","sub_path":"threshold_demo/thresholdapp.py","file_name":"thresholdapp.py","file_ext":"py","file_size_in_byte":7134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"616361169","text":"# -*- coding: utf-8 -*-\n\nimport socket\nimport struct\n\nfrom threading import Lock, Thread\n\nclass DataBank:\n\n \"\"\" Data class for thread safe access to bits and words space \"\"\"\n\n bits_lock = Lock()\n bits = [False] * 0x10000\n words_lock = Lock()\n words = [0] * 0x10000\n\n @classmethod\n def get_bits(cls, address, number=1):\n with cls.bits_lock:\n if (address >= 0) and (address + number <= len(cls.bits)):\n return cls.bits[address: number + address]\n else:\n return None\n\n @classmethod\n def set_bits(cls, address, bit_list):\n with cls.bits_lock:\n if (address >= 0) and (address + len(bit_list) <= len(cls.bits)):\n cls.bits[address: address + len(bit_list)] = bit_list\n return True\n else:\n return None\n\n @classmethod\n def get_words(cls, address, number=1):\n with cls.words_lock:\n if (address >= 0) and (address + number <= len(cls.words)):\n return cls.words[address: number + address]\n else:\n return None\n\n @classmethod\n def __get_word(cls, address): # with no lock, internal function\n if (address >= 0) and (address <= len(cls.words)):\n return cls.words[address]\n else:\n return None\n\n @classmethod\n def set_words(cls, address, word_list):\n with cls.words_lock:\n if (address >= 0) and (address + len(word_list) <= len(cls.words)):\n cls.words[address: address + len(word_list)] = word_list\n return True\n else:\n return None\n\n @classmethod\n def __set_word(cls, address, word):\n if (address >= 0) and (address <= len(cls.words)):\n cls.words[address] = word\n return True\n else:\n return None\n\n @classmethod\n def set_words_v2(cls, address, word_list):\n with cls.words_lock:\n if (address >= 0) and (address + len(word_list) <= len(cls.words)):\n index = 0\n for new_word in word_list:\n current_address = address + index\n old_word = cls.__get_word(current_address)\n if new_word == old_word:\n continue\n else:\n cls.__set_word(current_address, new_word)\n index += 1\n return True\n else:\n return None\n","sub_path":"data_source.py","file_name":"data_source.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"578494564","text":"from typing import List\n\n\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n s = 0\n\n stock = self.stom(chars)\n\n for w in words:\n usage = self.stom(w)\n good = True\n for i, c in usage.items():\n if i not in stock or stock[i] < c:\n good = False\n break\n if good:\n s += len(w)\n\n return s\n\n def stom(self, s):\n stock = {}\n for c in s:\n if c not in stock:\n stock[c] = 0\n stock[c] += 1\n\n return stock\n\n\nprint(Solution().countCharacters([\"cat\",\"bt\",\"hat\",\"tree\"], \"atach\"))\nprint(Solution().countCharacters(words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"))","sub_path":"leetcode/char_stock.py","file_name":"char_stock.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"155911569","text":"# -*- coding:utf-8 -*-\nimport os,sys,csv\n\nsys.path.append(\"/share/WebSite/\")\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"WebSite.settings\")\n\nfrom django.contrib.auth.models import User as AuthUser\nfrom User import models as UserModels\n\nclass User(object):\n \"\"\"docstring for App\"\"\"\n def __init__(self):\n self.users = self._read()\n \n def _read(self):\n users = []\n for user in AuthUser.objects.all():\n try:\n UserModels.UserInfo.objects.get(user = user)\n except:\n users.append(user)\n print(\"user info read finish\")\n return users\n\n def _store(self):\n for user in self.users:\n try:\n institution = UserModels.Institution.objects.get(name=\"北京希望组\")\n except:\n institution = UserModels.Institution(\n name = \"北京希望组\",\n description = \"未定义\"\n )\n institution.save()\n userinfo = UserModels.UserInfo(\n user = user,\n institution = institution,\n title = '未定义'\n )\n userinfo.save()\n print(\"user info store finish\")\n def _institution(institution):\n return UserModels.Institution.objects.all()\n","sub_path":"lib/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"384493885","text":"from collections import deque\n\n# https://e-maxx.ru/algo/bfs\ndef bws(A, si):\n used = [0] * len(A)\n d = [0] * len(A)\n p = [0] * len(A)\n used[si] = True\n p[si] = -1\n\n q = deque([si])\n while len(q) > 0:\n vert = q.popleft()\n for vi in range(len(A)):\n if vi == vert:\n continue\n if vi == p[vert]:\n continue\n if A[vi] & A[vert] == 0:\n continue\n \n if used[vi] == False:\n used[vi] = True\n q.append(vi)\n d[vi] = d[vert] + 1\n p[vi] = vert\n else:\n # restore paths s -> vi and vert -> s\n cycle = set()\n k = vert\n while k != si:\n cycle.add(k)\n k = p[k]\n k = vi\n while k != si:\n cycle.add(k)\n k = p[k]\n cycle.add(si)\n return cycle\n \n return set()\n\ndef main():\n n = int(input())\n A = list(map(int, input().split()))\n assert n == len(A)\n\n\n A = list(filter(lambda x: x > 0, A))\n n = len(A)\n\n to_check = set(range(n))\n\n res = -1\n while (len(to_check) > 0):\n si = to_check.pop()\n cycle = bws(A, si)\n r = len(cycle)\n if r != 0:\n res = min(res, r) if res != -1 else r\n if res == 3: # bootleg\n print(res)\n return\n #to_check = to_check - cycle\n\n \n print(res)\n\n\nimport sys\ninput = sys.stdin.readline\nif __name__ == \"__main__\":\n main()","sub_path":"580/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"436794130","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom models import Document\n\nclass DocumentForm(forms.ModelForm):\n \"\"\"Form for editing a document\"\"\"\n revision = forms.IntegerField(widget=forms.HiddenInput())\n \n class Meta:\n model = Document\n fields = ('subject', 'content')\n widgets = {\n 'subject': forms.TextInput(attrs={'class':'span4'}),\n 'content': forms.Textarea(),\n }\n\nclass VisibilityForm(forms.ModelForm):\n \"\"\"Form for managing visibility option of a document\"\"\"\n class Meta:\n model = Document\n fields = ('visibility',)\n\n\n","sub_path":"wadharkka/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"90154169","text":"from __future__ import absolute_import, division, print_function\r\n\r\nimport os\r\n\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\n\r\n# TensorFlow and tf.keras\r\nimport tensorflow as tf\r\nimport random\r\nimport pandas as pd\r\n\r\n# Helper libraries\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\r\n\r\n\r\nclass NasdaqGenerator(object):\r\n\r\n def createTestData_nparray(self, data, seqLength, predLength=1):\r\n i = 0\r\n dataX = []\r\n dataY = []\r\n while (i < (len(data) - seqLength - predLength)):\r\n dataX.append(data[i:i + seqLength])\r\n dataY.append(data[i + seqLength:(i + seqLength + predLength)])\r\n i += predLength\r\n\r\n return np.array(dataX), np.array(dataY)\r\n\r\n def createTrainData_nparray(self, data, seqLength, predLength=1):\r\n i = 0\r\n dataX = []\r\n dataY = []\r\n while (i < (len(data) - seqLength - predLength)):\r\n dataX.append(data[i:i + seqLength])\r\n dataY.append(data[i + seqLength:(i + seqLength + predLength)])\r\n i += 1\r\n\r\n return np.array(dataX), np.array(dataY)\r\n\r\n def normalize(self, data):\r\n numerator = data - np.min(data, 0)\r\n denominator = np.max(data, 0) - np.min(data, 0)\r\n return numerator / (denominator + 1e-7)\r\n\r\n def standardize(self, data):\r\n m = np.mean(data)\r\n stdev = np.std(data)\r\n return (data - m) / stdev\r\n\r\n def deStandardize(self, prevData, currentData):\r\n m = np.mean(prevData)\r\n stdev = np.std(prevData)\r\n return currentData * stdev + m\r\n\r\n def DeNormalize(self, prevData, currentData):\r\n min = np.min(prevData, 0)\r\n denominator = np.max(prevData, 0) - np.min(prevData, 0)\r\n return currentData * denominator + min\r\n\r\n def getMinTimeStep(self, data):\r\n min = data[0].shape[0]\r\n for i in range(len(data)):\r\n if (min > data[i].shape[0]):\r\n min = data[i].shape[0]\r\n return min\r\n\r\n def get_delta(self, Y):\r\n Y_shiftright = np.concatenate(([Y[0]], Y), axis=0)\r\n Y_shiftright = np.delete(Y_shiftright, len(Y) - 1, axis=0)\r\n return np.subtract(Y_shiftright, Y)\r\n\r\n def __init__(self, train_ratio, seq_length, output_count, batch_size):\r\n\r\n nasdaq100_small_raw = pd.read_csv(\r\n filepath_or_buffer=\"D:/Projects/tensor2/NASDAQ100/nasdaq100/small/nasdaq100_padding.csv\")\r\n dataset = []\r\n\r\n for i in range(len(nasdaq100_small_raw.values[0])):\r\n temp = nasdaq100_small_raw.values[:, i]\r\n dataset.append(temp)\r\n dataset = np.stack(dataset, axis=1)\r\n # dataset = np.reshape(dataset, [dataset.shape[0], dataset.shape[1], 1])\r\n print(dataset.shape)\r\n self.dataset = dataset\r\n dataset = np.diff(dataset, axis=0)\r\n plt.plot(dataset[:1000, -1])\r\n plt.show()\r\n plot_acf(dataset[:1000, -1])\r\n plt.show()\r\n\r\n train_size = int(len(dataset) * train_ratio)\r\n train_dataset = dataset[:train_size]\r\n test_dataset = dataset[train_size:]\r\n\r\n self.trainX, self.trainY = self.createTrainData_nparray(train_dataset, seq_length, output_count)\r\n self.testX, self.testY = self.createTestData_nparray(test_dataset, seq_length, output_count)\r\n\r\n self.batch_size = batch_size\r\n self.input_dim = self.trainX.shape[1:] # dimension of inputs\r\n self.output_dim = self.trainY.shape[1:]\r\n\r\nif __name__ == \"__main__\":\r\n a = NasdaqGenerator(0.8, 64, 8, 16)\r\n","sub_path":"DataCookers/NASDAQ100dataset.py","file_name":"NASDAQ100dataset.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"634441439","text":"from sardana.macroserver.macro import Macro, Type\nimport time\nimport taurus\n\nclass get_oav_iba_beam(Macro):\n \"\"\"Save fitted oav iba beam in bl13 variables\"\"\"\n \n def run(self):\n oav_iba = taurus.Device('bl13/eh/oav-01-iba')\n bl13vars = taurus.Device('bl13/ct/variables')\n \n if oav_iba.XProjFitConverged and oav_iba.YProjFitConverged:\n XProjFitCenter = oav_iba.XProjFitCenter\n YProjFitCenter = oav_iba.YProjFitCenter\n XProjFitFWHM = oav_iba.XProjFitFWHM\n YProjFitFWHM = oav_iba.YProjFitFWHM\n # Center should be relative to center not to the origin\n # Because changing zoom should not\n else:\n self.warning('beam not fitted')\n","sub_path":"ALBA_BL13_XALOC_USER_MACROS/oav_iba.py","file_name":"oav_iba.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"601693928","text":"# pyOCD debugger\n# Copyright (c) 2018-2020 Arm Limited\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport logging.config\nimport six\nimport yaml\nimport os\nimport weakref\n\n# inspect.getargspec is deprecated in Python 3.\ntry:\n from inspect import getfullargspec as getargspec\nexcept ImportError:\n from inspect import getargspec\n\nfrom . import exceptions\nfrom .options_manager import OptionsManager\nfrom ..board.board import Board\nfrom ..utility.notification import Notifier\n\nLOG = logging.getLogger(__name__)\n\n## @brief Set of default config filenames to search for.\n_CONFIG_FILE_NAMES = [\n \"pyocd.yaml\",\n \"pyocd.yml\",\n \".pyocd.yaml\",\n \".pyocd.yml\",\n ]\n\n## @brief Set of default user script names to search for.\n_USER_SCRIPT_NAMES = [\n \"pyocd_user.py\",\n \".pyocd_user.py\",\n ]\n\nclass Session(Notifier):\n \"\"\"! @brief Top-level object for a debug session.\n \n This class represents a debug session with a single debug probe. It is the root of the object\n graph, where it owns the debug probe and the board objects.\n \n Another important function of this class is that it contains a dictionary of session-scope\n options. These would normally be passed in from the command line. Options can also be loaded\n from a config file.\n\n Precedence for session options:\n \n 1. Keyword arguments to constructor.\n 2. _options_ parameter to constructor.\n 3. Probe-specific options from a config file.\n 4. General options from a config file.\n 5. _option_defaults_ parameter to constructor.\n \n The session also tracks several other objects:\n - @ref pyocd.gdbserver.gdbserver.GDBServer \"GDBServer\" instances created for any cores.\n - @ref pyocd.probe.tcp_probe_server.DebugProbeServer \"DebugProbeServer\".\n - The user script proxy.\n \n See the @ref pyocd.core.helpers.ConnectHelper \"ConnectHelper\" class for several methods that\n make it easy to create new sessions, with or without user interaction in the case of multiple\n available debug probes. A common pattern is to combine @ref \n pyocd.core.helpers.ConnectHelper.session_with_chosen_probe()\n \"ConnectHelper.session_with_chosen_probe()\" and a **with** block.\n \n A Session instance can be used as a context manager. The session will, by default, be\n automatically opened when the context is entered. And, of course, it will be closed when the\n **with** block is exited (which is harmless if the session was never opened). If you wish to\n disable automatic opening, set the `auto_open` parameter to the constructor to False. If an\n exception is raised while opening a session inside a **with** statement, the session will be\n closed for you to undo any partial initialisation.\n \"\"\"\n \n ## @brief Weak reference to the most recently created session.\n _current_session = None\n \n @classmethod\n def get_current(cls):\n \"\"\"! @brief Return the most recently created Session instance or a default Session.\n \n By default this method will return the most recently created Session object that is\n still alive. If no live session exists, a new default session will be created and returned.\n That at least provides access to the user's config file(s).\n \n Used primarily so code that doesn't have a session reference can access session options. This\n method should only be used to access options that are unlikely to differ between sessions,\n or for debug or other purposes.\n \"\"\"\n if cls._current_session is not None:\n return cls._current_session()\n else:\n return Session(None)\n\n def __init__(self, probe, auto_open=True, options=None, option_defaults=None, **kwargs):\n \"\"\"! @brief Session constructor.\n \n Creates a new session using the provided debug probe. Session options are merged from the\n _options_ parameter and any keyword arguments. Normally a board instance is created that can\n either be a generic board or a board associated with the debug probe.\n \n Note that the 'project_dir' and 'config' options must be set in either keyword arguments or\n the _options_ parameter.\n \n Passing in a _probe_ that is None is allowed. This is useful to create a session that operates\n only as a container for session options. In this case, the board instance is not created, so the\n #board attribute will be None. Such a Session cannot be opened.\n \n @param self\n @param probe The @ref pyocd.probe.debug_probe. \"DebugProbe\" instance. May be None.\n @param auto_open Whether to automatically open the session when used as a context manager.\n @param options Optional session options dictionary.\n @param option_defaults Optional dictionary of session option values. This dictionary has the\n lowest priority in determining final session option values, and is intended to set new\n defaults for option if they are not set through any other method.\n @param kwargs Session options passed as keyword arguments.\n \"\"\"\n super(Session, self).__init__()\n \n Session._current_session = weakref.ref(self)\n \n self._probe = probe\n self._closed = True\n self._inited = False\n self._user_script_namespace = None\n self._user_script_proxy = None\n self._delegate = None\n self._auto_open = auto_open\n self._options = OptionsManager()\n self._gdbservers = {}\n self._probeserver = None\n \n # Set this session on the probe, if we were given a probe.\n if probe is not None:\n probe.session = self\n \n # Update options.\n self._options.add_front(kwargs)\n self._options.add_back(options)\n \n # Init project directory.\n if self.options.get('project_dir') is None:\n self._project_dir = os.getcwd()\n else:\n self._project_dir = os.path.abspath(os.path.expanduser(self.options.get('project_dir')))\n LOG.debug(\"Project directory: %s\", self.project_dir)\n \n # Apply common configuration settings from the config file.\n config = self._get_config()\n probesConfig = config.pop('probes', None)\n self._options.add_back(config)\n\n # Pick up any config file options for this board.\n if (probe is not None) and (probesConfig is not None):\n for uid, settings in probesConfig.items():\n if str(uid).lower() in probe.unique_id.lower():\n LOG.info(\"Using config settings for probe %s\" % (probe.unique_id))\n self._options.add_back(settings)\n \n # Merge in lowest priority options.\n self._options.add_back(option_defaults)\n \n # Logging config.\n self._configure_logging()\n \n # Bail early if we weren't provided a probe.\n if probe is None:\n self._board = None\n return\n \n # Load the user script.\n self._load_user_script()\n \n # Ask the probe if it has an associated board, and if not then we create a generic one.\n self._board = probe.create_associated_board() \\\n or Board(self, self.options.get('target_override'))\n \n def _get_config(self):\n # Load config file if one was provided via options, and no_config option was not set.\n if not self.options.get('no_config'):\n configPath = self.find_user_file('config_file', _CONFIG_FILE_NAMES)\n \n if configPath is not None:\n try:\n with open(configPath, 'r') as configFile:\n LOG.debug(\"Loading config from: %s\", configPath)\n config = yaml.safe_load(configFile)\n if not isinstance(config, dict):\n raise exceptions.Error(\"configuration file %s does not contain a top-level dictionary\"\n % configPath)\n return config\n except IOError as err:\n LOG.warning(\"Error attempting to access config file '%s': %s\", configPath, err)\n \n return {}\n \n def find_user_file(self, option_name, filename_list):\n \"\"\"! @brief Search the project directory for a file.\n \n @retval None No matching file was found.\n @retval string An absolute path to the requested file.\n \"\"\"\n if option_name is not None:\n filePath = self.options.get(option_name)\n else:\n filePath = None\n \n # Look for default filenames if a path wasn't provided.\n if filePath is None:\n for filename in filename_list:\n thisPath = os.path.join(self.project_dir, filename)\n if os.path.isfile(thisPath):\n filePath = thisPath\n break\n # Use the path passed in options, which may be absolute, relative to the\n # home directory, or relative to the project directory.\n else:\n filePath = os.path.expanduser(filePath)\n if not os.path.isabs(filePath):\n filePath = os.path.join(self.project_dir, filePath)\n \n return filePath\n \n def _configure_logging(self):\n \"\"\"! @brief Load a logging config dict or file.\"\"\"\n # Get logging config that could have been loaded from the config file.\n config = self.options.get('logging')\n \n # Allow logging setting to refer to another file.\n if isinstance(config, six.string_types):\n loggingConfigPath = self.find_user_file(None, [config])\n \n if loggingConfigPath is not None:\n try:\n with open(loggingConfigPath, 'r') as configFile:\n config = yaml.safe_load(configFile)\n LOG.debug(\"Using logging configuration from: %s\", config)\n except IOError as err:\n LOG.warning(\"Error attempting to load logging config file '%s': %s\", config, err)\n return\n\n if config is not None:\n # Stuff a version key if it's missing, to make it easier to use.\n if 'version' not in config:\n config['version'] = 1\n # Set a different default for disabling existing loggers.\n if 'disable_existing_loggers' not in config:\n config['disable_existing_loggers'] = False\n # Remove an empty 'loggers' key.\n if ('loggers' in config) and (config['loggers'] is None):\n del config['loggers']\n \n try:\n logging.config.dictConfig(config)\n except (ValueError, TypeError, AttributeError, ImportError) as err:\n LOG.warning(\"Error applying logging configuration: %s\", err)\n \n @property\n def is_open(self):\n \"\"\"! @brief Boolean of whether the session has been opened.\"\"\"\n return self._inited and not self._closed\n \n @property\n def probe(self):\n \"\"\"! @brief The @ref pyocd.probe.debug_probe.DebugProbe \"DebugProbe\" instance.\"\"\"\n return self._probe\n \n @property\n def board(self):\n \"\"\"! @brief The @ref pyocd.board.board.Board \"Board\" object.\"\"\"\n return self._board\n \n @property\n def target(self):\n \"\"\"! @brief The @ref pyocd.core.target.soc_target \"SoCTarget\" object representing the SoC.\n \n This is the @ref pyocd.core.target.soc_target \"SoCTarget\" instance owned by the board.\n \"\"\"\n return self.board.target\n \n @property\n def options(self):\n \"\"\"! @brief The @ref pyocd.core.options_manager.OptionsManager \"OptionsManager\" object.\"\"\"\n return self._options\n \n @property\n def project_dir(self):\n \"\"\"! @brief Path to the project directory.\"\"\"\n return self._project_dir\n \n @property\n def delegate(self):\n \"\"\"! @brief An optional delegate object for customizing behaviour.\"\"\"\n return self._delegate\n \n @delegate.setter\n def delegate(self, new_delegate):\n \"\"\"! @brief Setter for the `delegate` property.\"\"\"\n self._delegate = new_delegate\n \n @property\n def user_script_proxy(self):\n \"\"\"! @brief The UserScriptDelegateProxy object for a loaded user script.\"\"\"\n return self._user_script_proxy\n \n @property\n def gdbservers(self):\n \"\"\"! @brief Dictionary of core numbers to @ref pyocd.gdbserver.gdbserver.GDBServer \"GDBServer\" instances.\"\"\"\n return self._gdbservers\n \n @property\n def probeserver(self):\n \"\"\"! @brief A @ref pyocd.probe.tcp_probe_server.DebugProbeServer \"DebugProbeServer\" instance.\"\"\"\n return self._probeserver\n \n @probeserver.setter\n def probeserver(self, server):\n \"\"\"! @brief Setter for the `probeserver` property.\"\"\"\n self._probeserver = server\n \n @property\n def log_tracebacks(self):\n \"\"\"! @brief Quick access to debug.traceback option since it is widely used.\"\"\"\n return self.options.get('debug.traceback')\n\n def __enter__(self):\n assert self._probe is not None\n if self._auto_open:\n try:\n self.open()\n except Exception:\n self.close()\n raise\n return self\n\n def __exit__(self, type, value, traceback):\n self.close()\n return False\n \n def _init_user_script_namespace(self, user_script_path):\n \"\"\"! @brief Create the namespace dict used for user scripts.\n \n This initial namespace has only those objects that are available very early in the\n session init process. For instance, the Target instance isn't available yet. The\n _update_user_script_namespace() method is used to add such objects to the namespace\n later on.\n \"\"\"\n import pyocd\n import pyocd.flash.file_programmer\n self._user_script_namespace = {\n # Modules and classes\n 'pyocd': pyocd,\n 'exceptions': pyocd.core.exceptions,\n 'Error': pyocd.core.exceptions.Error,\n 'TransferError': pyocd.core.exceptions.TransferError,\n 'TransferFaultError': pyocd.core.exceptions.TransferFaultError,\n 'Target': pyocd.core.target.Target,\n 'State': pyocd.core.target.Target.State,\n 'SecurityState': pyocd.core.target.Target.SecurityState,\n 'BreakpointType': pyocd.core.target.Target.BreakpointType,\n 'WatchpointType': pyocd.core.target.Target.WatchpointType,\n 'VectorCatch': pyocd.core.target.Target.VectorCatch,\n 'Event': pyocd.core.target.Target.Event,\n 'RunType': pyocd.core.target.Target.RunType,\n 'HaltReason': pyocd.core.target.Target.HaltReason,\n 'ResetType': pyocd.core.target.Target.ResetType,\n 'MemoryType': pyocd.core.memory_map.MemoryType,\n 'MemoryMap': pyocd.core.memory_map.MemoryMap,\n 'RamRegion': pyocd.core.memory_map.RamRegion,\n 'RomRegion': pyocd.core.memory_map.RomRegion,\n 'FlashRegion': pyocd.core.memory_map.FlashRegion,\n 'DeviceRegion': pyocd.core.memory_map.DeviceRegion,\n 'FileProgrammer': pyocd.flash.file_programmer.FileProgrammer,\n 'FlashEraser': pyocd.flash.eraser.FlashEraser,\n 'FlashLoader': pyocd.flash.loader.FlashLoader,\n # User script info\n '__name__': os.path.splitext(os.path.basename(user_script_path))[0],\n '__file__': user_script_path,\n # Objects\n 'session': self,\n 'options': self.options,\n 'LOG': logging.getLogger('pyocd.user_script'),\n }\n \n def _update_user_script_namespace(self):\n \"\"\"! @brief Add objects available only after init to the user script namespace.\"\"\"\n if self._user_script_namespace is not None:\n self._user_script_namespace.update({\n 'probe': self.probe,\n 'board': self.board,\n 'target': self.target,\n 'dp': self.target.dp,\n 'aps': self.target.aps,\n })\n \n def _load_user_script(self):\n scriptPath = self.find_user_file('user_script', _USER_SCRIPT_NAMES)\n\n if scriptPath is not None:\n try:\n # Read the script source.\n with open(scriptPath, 'r') as scriptFile:\n LOG.debug(\"Loading user script: %s\", scriptPath)\n scriptSource = scriptFile.read()\n \n self._init_user_script_namespace(scriptPath)\n \n scriptCode = compile(scriptSource, scriptPath, 'exec')\n # Executing the code will create definitions in the namespace for any\n # functions or classes. A single namespace is shared for both globals and\n # locals so that script-level definitions are available within the\n # script functions.\n six.exec_(scriptCode, self._user_script_namespace, self._user_script_namespace)\n \n # Create the proxy for the user script. It becomes the delegate unless\n # another delegate was already set.\n self._user_script_proxy = UserScriptDelegateProxy(self._user_script_namespace)\n if self._delegate is None:\n self._delegate = self._user_script_proxy\n except IOError as err:\n LOG.warning(\"Error attempting to load user script '%s': %s\", scriptPath, err)\n\n def open(self, init_board=True):\n \"\"\"! @brief Open the session.\n \n This method does everything necessary to begin a debug session. It first loads the user\n script, if there is one. The user script will be available via the _user_script_proxy_\n property. Then it opens the debug probe and sets the clock rate from the `frequency` user\n option. Finally, it inits the board (which will init the target, which performs the\n full target init sequence).\n \n @param self\n @param init_board This parameter lets you prevent the board from being inited, which can\n be useful in board bringup situations. It's also used by pyocd commander's \"no init\"\n feature.\n \"\"\"\n if not self._inited:\n assert self._probe is not None, \"Cannot open a session without a probe.\"\n assert self._board is not None, \"Must have a board to open a session.\"\n \n # Add in the full set of objects for the user script.\n self._update_user_script_namespace()\n \n self._probe.open()\n self._closed = False\n self._probe.set_clock(self.options.get('frequency'))\n if init_board:\n self._board.init()\n self._inited = True\n\n def close(self):\n \"\"\"! @brief Close the session.\n \n Uninits the board and disconnects then closes the probe.\n \"\"\"\n if self._closed:\n return\n self._closed = True\n\n LOG.debug(\"uninit session %s\", self)\n if self._inited:\n try:\n self.board.uninit()\n self._inited = False\n except:\n LOG.error(\"exception during board uninit:\", exc_info=self.log_tracebacks)\n \n if self._probe.is_open:\n try:\n self._probe.disconnect()\n except:\n LOG.error(\"probe exception during disconnect:\", exc_info=self.log_tracebacks)\n try:\n self._probe.close()\n except:\n LOG.error(\"probe exception during close:\", exc_info=self.log_tracebacks)\n\nclass UserScriptFunctionProxy(object):\n \"\"\"! @brief Proxy for user script functions.\n \n This proxy makes arguments to user script functions optional. \n \"\"\"\n\n def __init__(self, fn):\n self._fn = fn\n self._spec = getargspec(fn)\n \n def __call__(self, **kwargs):\n args = {}\n for arg in self._spec.args:\n if arg in kwargs:\n args[arg] = kwargs[arg]\n self._fn(**args)\n\nclass UserScriptDelegateProxy(object):\n \"\"\"! @brief Delegate proxy for user scripts.\"\"\"\n\n def __init__(self, script_namespace):\n super(UserScriptDelegateProxy, self).__init__()\n self._script = script_namespace\n \n def __getattr__(self, name):\n if name in self._script:\n fn = self._script[name]\n return UserScriptFunctionProxy(fn)\n else:\n raise AttributeError(name)\n","sub_path":"pyocd/core/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":21469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"342690598","text":"import random, re, StringIO, csv, datetime\nfrom flask import Flask, render_template, request, redirect, url_for, make_response, send_file\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom flask.ext.login import login_user, current_user, logout_user\nfrom aioregister.sample_problems import get_sample_problems\nfrom aioregister.school_login import SchoolLogin\nfrom models import db, School, Deleted, Student\nfrom sqlalchemy.ext.automap import automap_base\n\nclass AioRegisterApplication(Flask):\n def __init__(self, *args, **kwargs):\n Flask.__init__(self, __name__, *args, **kwargs)\n with self.open_resource('wordlist.txt') as f:\n self.wordlist = f.read().split()\n with self.open_resource('countries.txt') as f:\n self.countries = f.read().split('\\n')\n\n @self.route('/')\n def index():\n return render_template('index.html', contestlive=self.contest_links_live())\n\n @self.route('/register/', methods=['GET', 'POST'])\n def register():\n if request.method == 'POST':\n \n school = SchoolLogin.get(request.form['username'])\n if school is not None and \\\n (school.school.password == request.form['password'] or \n (school.school.alt_password is not None and school.school.alt_password == request.form['password'])):\n login_user(school, remember=True)\n self.logger.info(\"[Auth] Sucessful login for '%s' with password '%s'\", request.form['username'], request.form['password'])\n else:\n self.logger.info(\"[Auth] Unucessful login for '%s' with password '%s'\", request.form.get('username','UNSPECIFIED'), request.form.get('password','UNSPECIFIED'))\n return render_template('register_login.html', badlogin=True)\n if (current_user.is_authenticated()):\n school = current_user.school\n students = Student.query.filter_by(school_id=school.id).order_by(Student.division, Student.id)\n return render_template('register.html',\n school=school,\n studentInfo=[\"First Name\", \"Last Name\", \"Username\", \"Password\", \"Year\", \"Gender\", \"Email\", \"Division\"],\n students=students,\n contestlive=self.contest_links_live())\n else:\n return render_template('register_login.html')\n\n @self.route('/sample/')\n def sample():\n return render_template('sample_problems.html', sample_problems=get_sample_problems())\n\n @self.route('/testenv/')\n def test_contest_environment():\n return render_template('test_contest_environment.html')\n\n @self.route('/logout/')\n def logout():\n if current_user.is_authenticated():\n self.logger.info('[AUTH] Logout for user %s', current_user.school.username)\n else:\n self.logger.info('[AUTH] Logout for unauthenticated user')\n logout_user()\n return redirect(url_for('index'))\n\n @self.route('/register/student//edit/', methods=['GET', 'POST'])\n def editstudent(studentid):\n if not current_user.is_authenticated():\n return notauthenticated()\n # ensure student exists and that user has permissions to view student\n student = Student.query.filter_by(id=studentid).first()\n if student is None or student.school_id != current_user.school.id:\n return \"Not your student, or student doesn't exist. Please go back.\"\n\n if request.method == 'POST':\n params = {}\n params['firstname'] = request.form.get('firstname', '').strip()\n params['lastname'] = request.form.get('lastname', '').strip()\n params['year'] = request.form.get('year', '')\n params['gender'] = request.form.get('gender', '')\n params['email'] = request.form.get('email', '').strip()\n params['division'] = request.form.get('division', '')\n if not (params['firstname']):\n return render_template('editstudent.html', message=\"First name must be defined\", **params)\n if not (params['lastname']):\n return render_template('editstudent.html', message=\"Last name must be defined\", **params)\n if not (params['year'] and params['year'].isdigit and int(params['year']) >= 1 and int(params['year']) <= 12):\n return render_template('editstudent.html', message=\"Year must be a number between 1 and 12\", **params)\n if not (params['gender'] and len(params['gender']) == 1 and params['gender'] in 'UFM'):\n return render_template('editstudent.html', message=\"Gender must be chosen from the drop down menu\", **params)\n if not (params['division'] and len(params['division']) == 1 and params['division'] in 'IS'):\n return render_template('editstudent.html', message=\"Division must be chosen from the drop down menu\", **params)\n if not (params['email'] and re.match(r\"^[A-Z'0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$\", params['email'], re.IGNORECASE)):\n return render_template('editstudent.html', message='Please enter a valid email address', **params)\n if int(params['year']) >= 11 and params['division']!='S':\n return render_template('editstudent.html', message='Students in year 11 and 12 can only compete in the senior division', **params)\n student.firstname = request.form['firstname']\n student.lastname = request.form['lastname']\n student.year = request.form['year']\n student.gender = request.form['gender']\n student.email = request.form['email']\n student.division = request.form['division']\n db.session.add(student)\n db.session.commit()\n return redirect(url_for('register'))\n\n params = {}\n params[\"firstname\"] = student.firstname\n params[\"lastname\"] = student.lastname\n params[\"year\"] = student.year\n params[\"gender\"] = student.gender\n params[\"email\"] = student.email\n params[\"division\"] = student.division\n for i in params:\n if params[i] == None:\n params[i] = \"\"\n return render_template('editstudent.html', **params)\n\n @self.route('/register/student/add/', methods=['GET', 'POST'])\n def addstudent():\n if not current_user.is_authenticated():\n return notauthenticated()\n\n if request.method == 'POST':\n params = {\"addingpage\":True}\n params['firstname'] = request.form.get('firstname', '').strip()\n params['lastname'] = request.form.get('lastname', '').strip()\n params['year'] = request.form.get('year', '') \n params['gender'] = request.form.get('gender', '') \n params['email'] = request.form.get('email', '').strip()\n params['division'] = request.form.get('division', '')\n if not (params['firstname']):\n return render_template('editstudent.html', message=\"First name must be defined\", **params)\n if not (params['lastname']):\n return render_template('editstudent.html', message=\"Last name must be defined\", **params)\n if not (params['year'] and params['year'].isdigit and int(params['year']) >= 1 and int(params['year']) <= 12):\n return render_template('editstudent.html', message=\"Year must be a number between 1 and 12\", **params)\n if not (params['gender'] and len(params['gender']) == 1 and params['gender'] in 'UFM'):\n return render_template('editstudent.html', message=\"Gender must be chosen from the drop down menu\", **params)\n if not (params['division'] and len(params['division']) == 1 and params['division'] in 'IS'):\n return render_template('editstudent.html', message=\"Division must be chosen from the drop down menu\", **params)\n if not (params['email'] and re.match(r\"^[A-Z'0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$\", params['email'], re.IGNORECASE)):\n return render_template('editstudent.html', message='Please enter a valid email address', **params)\n if int(params['year']) >= 11 and params['division']!='S':\n return render_template('editstudent.html', message='Students in year 11 and 12 can only compete in the senior division', **params)\n uname = self.generate_username(request.form['firstname'], request.form['lastname'])\n student = Student(uname, self.generate_password(),\n current_user.school,\n request.form['firstname'],\n request.form['lastname'],\n request.form['year'],\n request.form['gender'],\n request.form['email'],\n request.form['division'])\n db.session.add(student)\n db.session.commit()\n placetogo = 'register' if request.form.get('another',None) is None else 'addstudent'\n return redirect(url_for(placetogo))\n\n params = {\"addingpage\":True}\n params[\"firstname\"] = \"\"\n params[\"lastname\"] = \"\"\n params[\"year\"] = \"\"\n params[\"gender\"] = \"\"\n params[\"email\"] = \"\"\n params[\"division\"] = \"\"\n for i in params:\n if params[i] == None:\n params[i] = \"\"\n return render_template('editstudent.html', **params)\n\n @self.route('/register/student//delete/')\n def deletestudent(studentid):\n # ensure that user is logged in\n if not current_user.is_authenticated():\n return \"not authenticated\"\n # ensure student exists and that user has permissions to view student\n student = Student.query.filter_by(id=studentid).first()\n if student is None or student.school_id != current_user.school.id:\n return \"not your student, or student doesn't exist\"\n return render_template('deletestudent.html', student=student)\n\n @self.route('/register/student//finaldelete/')\n def deletestudentfinal(studentid):\n # ensure that user is logged in\n if not current_user.is_authenticated():\n return \"not authenticated\"\n # ensure student exists and that user has permissions to view student\n student = Student.query.filter_by(id=studentid).first()\n if student is None or student.school_id != current_user.school.id:\n return \"not your student, or student doesn't exist\"\n db.session.add(Deleted(student.username))\n db.session.delete(student)\n db.session.commit()\n return redirect(url_for('register'))\n\n @self.route('/register/school/edit/', methods=['GET', 'POST'])\n def editschool():\n if not current_user.is_authenticated():\n return notauthenticated()\n cschool = current_user.school\n if request.method == 'POST':\n params = {\"countries\":self.countries}\n params['schoolname'] = request.form.get('schoolname', '') \n params['teachername'] = request.form.get('teachername', '').strip()\n params['email'] = request.form.get('email', '').strip()\n params['phone'] = request.form.get('phone', '') \n if not (params['schoolname']):\n return render_template('editschool.html', message=\"School name must be defined\", **params)\n if not (params['teachername']):\n return render_template('editschool.html', message=\"Teacher name must be defined\", **params)\n if not (params['phone']):\n return render_template('editschool.html', message=\"Phone number must be entered\", **params)\n if not (params['email'] and re.match(r\"[A-Z'0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\", params['email'], re.IGNORECASE)):\n return render_template('editschool.html', message='Please enter a valid email address', **params)\n cschool.school_name = request.form['schoolname']\n cschool.teacher_name = request.form['teachername']\n cschool.email = request.form['email']\n cschool.phone = request.form['phone']\n db.session.add(cschool)\n db.session.commit()\n return redirect(url_for('register'))\n\n params = {\"countries\":self.countries}\n params[\"schoolname\"] = cschool.school_name \n params[\"teachername\"] = cschool.teacher_name \n params[\"email\"] = cschool.email\n params[\"phone\"] = cschool.phone \n for i in params:\n if params[i] == None:\n params[i] = \"\"\n return render_template(\"editschool.html\", school=cschool, **params)\n\n def notauthenticated():\n return \"not authenticated\"\n \n @self.route('/register/school/students.csv')\n def downloadStudents():\n if not current_user.is_authenticated():\n return notauthenticated()\n cschool = current_user.school\n si = StringIO.StringIO()\n cw = csv.writer(si)\n cw.writerow((\"First Name\", \"Last Name\", \"Year\", \"Division\", \"Email\", \"Username\", \"Password\"))\n students = Student.query.filter_by(school_id=cschool.id).order_by(Student.division, Student.id)\n studentData = [(s.firstname, s.lastname, s.year, (\"Intermediate\" if s.division==\"I\" else \"Senior\"), s.email, s.username, s.password) for s in students]\n cw.writerows(studentData)\n output = make_response(si.getvalue())\n output.headers[\"Content-Disposition\"] = \"attachment; filename=AIOstudents.csv\"\n output.headers[\"Content-type\"] = \"text/csv\"\n return output\n\n @self.route('/contest/')\n def contestlisting():\n return render_template(\"contests.html\", contestlive=self.contest_links_live())\n @self.route('/docs/rules.pdf')\n def rulebookpdf():\n return self.pdfresponse('docs/rules.pdf', 'rules')\n\n @self.route('/docs/aio18-int.pdf')\n def aio15intpdf():\n if not current_user.is_authenticated():\n return notauthenticated()\n if not self.contest_links_live():\n return \"Page not found\", 404\n return self.pdfresponse('docs/aio18-int.pdf', 'aio18-int')\n\n @self.route('/docs/aio18-sen.pdf')\n def aio15senpdf():\n if not current_user.is_authenticated():\n return notauthenticated()\n if not self.contest_links_live():\n return \"Page not found\", 404\n return self.pdfresponse('docs/aio18-sen.pdf', 'aio18-sen')\n\n @self.route('/docs/feedback')\n def feedback():\n argusername=request.args.get('username', None)\n argpassword=request.args.get('password', None)\n if argusername is None or argpassword is None:\n return \"invalid username or password\", 403\n student = Student.query.filter_by(username=argusername, password=argpassword).first()\n if student is None:\n return \"invalid username or password\", 403\n zippath = 'docs/feedback/%s.zip' % argusername\n zipname = '%s.zip' % argusername\n data = self.open_resource(zippath).read()\n response = make_response(data)\n response.headers['Content-Type'] = 'application/zip'\n response.headers['Content-Disposition'] = \\\n 'inline; filename=%s' % zipname\n return response\n \n\n def pdfresponse(self, fpath, fname):\n with self.open_resource(fpath) as f:\n data = f.read()\n response = make_response(data)\n response.headers['Content-Type'] = 'application/pdf'\n response.headers['Content-Disposition'] = \\\n 'inline; filename=%s.pdf' % fname\n return response\n\n\n def contest_links_live(self):\n tnow = datetime.datetime.utcnow()\n tlive = datetime.datetime(2018,8,22,22,0)\n islive = tnow >= tlive\n return islive\n\n def generate_password(self):\n return random.choice(self.wordlist)+random.choice(self.wordlist) \n\n def generate_username(self, firstname, lastname):\n firstname = filter(lambda x: x >= 'a' and x <= 'z', firstname.lower())\n lastname = filter(lambda x: x >= 'a' and x <= 'z', lastname.lower())\n candidate = firstname[:6] + lastname[:3]\n appendage = '' if len(candidate) != 0 else '1'\n if self.username_exists(candidate+str(appendage)):\n appendage = 1\n while self.username_exists(candidate+str(appendage)):\n appendage += 1\n return candidate + str(appendage)\n\n def username_exists(self, uname):\n return (Student.query.filter_by(username=uname).first() is not None or\n Deleted.query.filter_by(username=uname).first() is not None)\n\n def init_db(self):\n db.init_app(self)\n db.app = self # slight hack to work around flask's context \"feature\"\n db.create_all()\n db.session.commit()\n","sub_path":"aioregister/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":18035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"611715447","text":"#65. cosine series print and sumation of its:\n\n\ndef fact(n): # define the function of n used for factorial used .??\n fact = 1\n while n > 0:\n fact*=n\n n = n - 1\n return fact\nn=int(input(\"enter the number of term :\"))\nx=int(input(\"enter the value of x:\"))\nsum=1\nfor i in range (1,n+1):\n sum = sum + ((((-1)**i)) * (x**(2*i))) / fact(2*i) # cosine series formula in fact values.\nprint(sum)","sub_path":"PythonPrograms/python_program/cos_series_sumation.py","file_name":"cos_series_sumation.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"635195599","text":"#!/usr/bin/env python3\n\n\"\"\"The main function of the compiler, AKA the compiler driver\"\"\"\n\nimport lexer\nimport parser\nfrom support import *\nfrom datalayout import *\nfrom cfg import *\nfrom regalloc import *\nfrom codegen import *\n\n\ndef compile_program(text):\n lex = lexer.Lexer(text)\n pars = parser.Parser(lex)\n res = pars.program()\n print('\\n', res, '\\n')\n\n return\n res.navigate(print_stat_list)\n\n node_list = get_node_list(res)\n for n in node_list:\n print(type(n), id(n), '->', type(n.parent), id(n.parent))\n print('\\nTotal nodes in IR:', len(node_list), '\\n')\n\n res.navigate(lowering)\n\n node_list = get_node_list(res)\n print('\\n', res, '\\n')\n for n in node_list:\n print(type(n), id(n))\n try:\n n.flatten()\n except Exception:\n pass\n # res.navigate(flattening)\n print('\\n', res, '\\n')\n\n print_dotty(res, \"log.dot\")\n\n print(\"\\n\\nDATALAYOUT\\n\\n\")\n perform_data_layout(res)\n print('\\n', res, '\\n')\n\n cfg = CFG(res)\n cfg.liveness()\n cfg.print_liveness()\n cfg.print_cfg_to_dot(\"cfg.dot\")\n\n print(\"\\n\\nREGALLOC\\n\\n\")\n ra = LinearScanRegisterAllocator(cfg, 11)\n reg_alloc = ra()\n print(reg_alloc)\n\n print(\"\\n\\nCODEGEN\\n\\n\")\n code = generate_code(res, reg_alloc)\n print(code)\n\n return code\n\n\ndef driver_main():\n from lexer import __test_program\n test_program=__test_program\n import sys\n print(sys.argv)\n if len(sys.argv) >= 2:\n with open(sys.argv[1], 'r') as inf :\n test_program = inf.read()\n code = compile_program(test_program)\n\n if len(sys.argv) > 2:\n with open(sys.argv[-1], 'w') as outf :\n outf.write(code)\n\n\nif __name__ == '__main__':\n driver_main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"79533341","text":"from __future__ import annotations\nimport os\nfrom pathlib import Path\nimport shutil\nfrom urllib.request import urlretrieve\nimport tarfile\nfrom typing import Tuple\nfrom argparse import Namespace\nimport threading\nfrom abc import ABC\nimport re\nfrom constants import HasConstants\n\n\nclass HasComponentBaseDirectory:\n @property\n def component_base_dir(self) -> str:\n raise NotImplementedError(\"Base class not implement base_dir\")\n\n\nclass HasData:\n @property\n def data(self) -> dict:\n raise NotImplementedError(\"Base class not implement data\")\n\n\nclass FileDiscoverable:\n @staticmethod\n def discover(dir_path: str, regex_pattern: str) -> list[Path]:\n paths = []\n pattern = re.compile(regex_pattern)\n for file_or_dir in Path(dir_path).rglob(\"*\"):\n if file_or_dir.is_file() and pattern.match(str(file_or_dir.name)):\n paths.append(file_or_dir)\n return paths\n\n\nclass DestinationFigurable(HasConstants):\n def get_dest(self, src: str) -> Path:\n relative_path = src[len(self.BASE_PATH):]\n return Path(self.TARGET_BASE_PATH + relative_path)\n\n\nclass TemplateRequired(HasComponentBaseDirectory, FileDiscoverable, DestinationFigurable):\n\n @property\n def template_files(self) -> list[Path]:\n dir_to_traverse = os.path.join(self.BASE_PATH, Path(self.component_base_dir).name)\n pattern = \".*\\\\.{EXTENSION}$\".format(EXTENSION=self.TEMPLATE_EXTENSION)\n return self.discover(dir_to_traverse, pattern)\n\n def do_template(self, engine, data) -> None:\n for to_template in self.template_files:\n content = engine.render(to_template, data)\n dest = Path(os.path.splitext(self.get_dest(str(to_template)))[0])\n dest.parent.mkdir(parents=True, exist_ok=True)\n with open(str(dest), \"w\") as f:\n f.write(content)\n if str(dest.suffix) in [\".sh\", \".py\"]:\n os.chmod(dest, 0o755)\n\n\nclass FilesCopyRequired(ABC, HasComponentBaseDirectory, FileDiscoverable, DestinationFigurable):\n @property\n def files_to_copy(self) -> list[Path]:\n dir_to_traverse = os.path.join(self.BASE_PATH, Path(self.component_base_dir).name)\n pattern = \"(?!.*\\\\.{EXTENSION}$)\".format(EXTENSION=self.TEMPLATE_EXTENSION)\n return self.discover(dir_to_traverse, pattern)\n\n def copy(self) -> None:\n for to_copy in self.files_to_copy:\n dest = self.get_dest(str(to_copy))\n dest.parent.mkdir(parents=True, exist_ok=True)\n shutil.copy2(to_copy, dest)\n if str(dest.suffix) in [\".sh\", \".py\"]:\n os.chmod(dest, 0o755)\n\n\nclass DownloadRequired(HasComponentBaseDirectory, HasConstants):\n def __init__(self, force_download: bool):\n self.force_download = force_download\n\n def download_async(self) -> list[threading.Thread]:\n Path(self.component_base_dir).mkdir(parents=True, exist_ok=True)\n links = self.links_to_download\n awaitables = []\n for i in range(0, len(links)):\n link, output_file = links[i]\n download_func = self._download\n if not self.force_download and Path(output_file).exists():\n download_func = self._dummy_download\n\n awaitables.append(threading.Thread(target=download_func,\n args=(link, output_file)))\n return awaitables\n\n @staticmethod\n def _dummy_download(url: str, output_file: Path) -> None:\n print(\"Download from {URL} is ignored as {PATH} already exists\".format(URL=url, PATH=str(output_file)))\n return\n\n @staticmethod\n def _download(url: str, output_file: Path) -> None:\n print(\"Downloading from {SOURCE} to {DESTINATION}\".format(SOURCE=url, DESTINATION=output_file))\n urlretrieve(url, filename=output_file)\n\n @property\n def links_to_download(self) -> list[Tuple[str, Path]]:\n raise NotImplementedError(\"Base class not implement links_to_download\")\n\n\nclass DecompressRequired:\n def decompress_async(self) -> list[threading.Thread]:\n awaitables = []\n for compressed, dest in self.files_to_decompress:\n decompress_func = self._decompress\n if dest.exists():\n decompress_func = self._dummy_decompress\n\n awaitables.append(threading.Thread(target=decompress_func, args=(compressed, dest)))\n return awaitables\n\n @staticmethod\n def _dummy_decompress(compressed: Path, dest_path: Path) -> None:\n print(\"Decompressing {COMPRESSED} is ignored as {PATH} already exists\".format(\n COMPRESSED=str(compressed), PATH=str(dest_path)))\n return\n\n @staticmethod\n def _decompress(compressed: Path, dest_path: Path) -> None:\n dest_path.mkdir(parents=True, exist_ok=True)\n with tarfile.open(Path(compressed)) as f:\n f.extractall(dest_path)\n\n @property\n def files_to_decompress(self) -> list[Tuple[Path, Path]]:\n raise NotImplementedError(\"Base class not implement decompress\")\n\n\nclass Component(ABC):\n pass\n\n\nclass Scripts(Component, TemplateRequired):\n @property\n def component_base_dir(self) -> str:\n return os.path.join(self.TARGET_BASE_PATH, \"bin\")\n\n @property\n def data(self) -> dict:\n return {}\n\n\nclass ClusterStarter(Component, FilesCopyRequired, TemplateRequired, HasData, HasConstants):\n\n @property\n def component_base_dir(self) -> str:\n return os.path.join(self.TARGET_BASE_PATH, \"cluster-starter\")\n\n @property\n def data(self) -> dict:\n return {\n \"additional\": {\n \"image\": {\n \"cluster-starter\": self.CLUSTER_STARTER_IMAGE_NAME\n }\n }\n }\n\n\nclass Hue(Component, FilesCopyRequired, TemplateRequired, HasData):\n @property\n def component_base_dir(self) -> str:\n return os.path.join(self.TARGET_BASE_PATH, \"hue\")\n\n @property\n def data(self) -> dict:\n return {\n \"hue\": {\n \"db-user\": \"hue\", \"db-password\": \"hue\", \"db-name\": \"hue\", \"db-host\": \"cluster-db\", \"db-port\": \"5432\"\n }\n }\n\n\nclass Hadoop(Component, FilesCopyRequired, TemplateRequired, DownloadRequired, DecompressRequired, HasData, HasConstants):\n TAR_FILE_NAME = \"hadoop.tar.gz\"\n PREDEF_GROUPS = {\n \"admin\": 150, \"hadoop\": 151, \"hadoopsvc\": 152, \"usersvc\": 154, \"dataplatform_user\": 155, \"hadoopUser\":156,\n \"bi_user_group\": 157, \"ml_user_group\": 158, \"de_user_group\": 159\n }\n\n PREDEF_USERS = {\n \"hdfs\": {\"uid\": 180, \"groups\": [\"admin\"], \"isSvc\": True, \"proxyGroup\": \"*\"},\n \"webhdfs\": {\"uid\": 181, \"groups\": [\"admin\"], \"isSvc\": True, \"proxyGroup\": \"*\"},\n \"hive\": {\"uid\": 182, \"groups\": [\"hadoopsvc\", \"hadoopUser\"], \"isSvc\": True, \"proxyGroup\": \"hadoopUser\"},\n \"hue\": {\"uid\": 183, \"groups\": [\"hadoopsvc\", \"hadoopUser\"], \"isSvc\": True, \"proxyGroup\": \"hadoopUser\"},\n \"spark\": {\"uid\": 184, \"groups\": [\"hadoopsvc\", \"hadoopUser\"], \"isSvc\": True, \"proxyGroup\": \"hadoopUser\"},\n \"bi_user\": {\"uid\": 185, \"groups\": [\"dataplatform_user\", \"hadoopUser\", \"bi_user_group\"], \"isSvc\": False},\n \"bi_svc\": {\"uid\": 186, \"groups\": [\"usersvc\", \"hadoopUser\"], \"isSvc\": True, \"proxyGroup\": \"bi_user_group\"},\n \"ml_user\": {\"uid\": 187, \"groups\": [\"dataplatform_user\", \"hadoopUser\", \"ml_user_group\"], \"isSvc\": False},\n \"ml_svc\": {\"uid\": 188, \"groups\": [\"usersvc\", \"hadoopUser\"], \"isSvc\": True, \"proxyGroup\": \"ml_user_group\"},\n \"de_user\": {\"uid\": 189, \"groups\": [\"dataplatform_user\", \"hadoopUser\", \"de_user_group\"], \"isSvc\": False},\n \"de_svc\": {\"uid\": 190, \"groups\": [\"usersvc\", \"hadoopUser\"], \"isSvc\": True, \"proxyGroup\": \"de_user_group\"}\n }\n\n def __init__(self, args: Namespace):\n DownloadRequired.__init__(self, force_download=args.force_download_hadoop)\n self.hadoop_version = args.hadoop_version\n self.java_version = args.java_version\n self.num_datanode = args.num_datanode\n\n @property\n def component_base_dir(self) -> str:\n return os.path.join(self.TARGET_BASE_PATH, \"hadoop\")\n\n @property\n def links_to_download(self) -> list[Tuple[str, Path]]:\n return [\n (\"https://github.com/dev-moonduck/hadoop/releases/download/v{HADOOP_VERSION}/hadoop-{HADOOP_VERSION}.tar.gz\"\n .format(HADOOP_VERSION=self.hadoop_version),\n Path(os.path.join(self.component_base_dir, self.TAR_FILE_NAME)))\n ]\n\n @property\n def files_to_decompress(self) -> list[Tuple[Path, Path]]:\n return [\n (Path(os.path.join(self.component_base_dir, self.TAR_FILE_NAME)),\n Path(os.path.join(self.component_base_dir, \"hadoop-bin\")))\n ]\n\n @property\n def data(self) -> dict:\n return {\n \"primary_namenode\": {\n \"host\": \"primary-namenode\", \"rpc-port\": \"9000\", \"http-port\": \"9870\"\n },\n \"secondary_namenode\": {\n \"host\": \"secondary-namenode\", \"rpc-port\": \"9000\", \"http-port\": \"9870\"\n },\n \"journalnode\": {\"host\": [\"journalnode1\", \"journalnode2\", \"journalnode3\"], \"port\": \"8485\"},\n \"zookeeper\": {\"host\": [\"zookeeper1\", \"zookeeper2\", \"zookeeper3\"], \"port\": \"2181\"},\n \"yarn_history\": {\"host\": \"yarn-history\", \"port\": \"8188\"},\n \"resource_manager\": {\n \"host\": \"resource-manager\", \"port\": \"8032\", \"web-port\": \"8088\", \"resource-tracker-port\": \"8031\",\n \"scheduler-port\": \"8030\"\n },\n \"datanode\": {\n \"host\": list(map(lambda i: \"datanode\" + str(i), range(1, self.num_datanode + 1))),\n \"rpc-port\": \"9864\", \"nodemanager-port\": \"8042\"\n },\n \"additional\": {\n \"users\": self.PREDEF_USERS, \"groups\": self.PREDEF_GROUPS,\n \"dependency-versions\": {\n \"hadoop\": self.hadoop_version, \"java\": self.java_version\n },\n \"agent\": {\n \"port\": \"3333\"\n },\n \"image\": {\n \"hadoop\": self.HADOOP_IMAGE_NAME\n }\n }\n }\n\n\nclass Hive(Component, FilesCopyRequired, TemplateRequired, DownloadRequired, DecompressRequired, HasData):\n TAR_FILE_NAME = \"hive.tar.gz\"\n\n def __init__(self, args: Namespace):\n DownloadRequired.__init__(self, force_download=args.force_download_hive)\n self.hive_version = args.hive_version\n\n @property\n def component_base_dir(self) -> str:\n return os.path.join(self.TARGET_BASE_PATH, \"hive\")\n\n @property\n def links_to_download(self) -> list[Tuple[str, Path]]:\n return [\n ((\"https://github.com/dev-moonduck/hive/releases/download/v{HIVE_VERSION}\"\n + \"/apache-hive-{HIVE_VERSION}.tar.gz\").format(HIVE_VERSION=self.hive_version),\n Path(os.path.join(self.component_base_dir, self.TAR_FILE_NAME)))\n ]\n\n @property\n def files_to_decompress(self) -> list[Tuple[Path, Path]]:\n return [\n (Path(os.path.join(self.component_base_dir, self.TAR_FILE_NAME)),\n Path(os.path.join(self.component_base_dir, \"hive-bin\")))\n ]\n\n @property\n def data(self) -> dict:\n return {\n \"hive_server\": {\"host\": \"hive-server\", \"thrift-port\": \"10000\", \"http-port\": \"10001\"},\n \"hive_metastore\": {\"host\": \"hive-metastore\", \"thrift-port\": \"9083\", \"metastore-db-host\": \"cluster-db\",\n \"metastore-db-port\": \"5432\", \"metastore-db-name\": \"metastore\",\n \"metastore-db-user\": \"hive\", \"metastore-db-password\": \"hive\"},\n \"additional\": {\n \"dependency-versions\": {\n \"hive\": self.hive_version\n }\n }\n }\n\n\nclass Spark(Component, FilesCopyRequired, TemplateRequired, DownloadRequired, DecompressRequired, HasData):\n TAR_FILE_NAME = \"spark.tar.gz\"\n\n def __init__(self, args: Namespace):\n DownloadRequired.__init__(self, force_download=args.force_download_spark)\n self.spark_version = args.spark_version\n self.scala_version = args.scala_version\n self.hadoop_version = args.hadoop_version\n\n @property\n def component_base_dir(self) -> str:\n return os.path.join(self.TARGET_BASE_PATH, \"spark\")\n\n @property\n def links_to_download(self) -> list[Tuple[str, Path]]:\n return [(\n (\"https://github.com/dev-moonduck/spark/releases/download/v{SPARK_VERSION}-{SCALA_VERSION}-{HADOOP_VERSION}\"\n + \"/spark-{SPARK_VERSION}-{SCALA_VERSION}-{HADOOP_VERSION}.tar.gz\").format(\n SPARK_VERSION=self.spark_version, SCALA_VERSION=self.scala_version, HADOOP_VERSION=self.hadoop_version),\n Path(os.path.join(self.component_base_dir, self.TAR_FILE_NAME)))\n ]\n\n @property\n def files_to_decompress(self) -> list[Tuple[Path, Path]]:\n return [\n (Path(os.path.join(self.component_base_dir, self.TAR_FILE_NAME)),\n Path(os.path.join(self.component_base_dir, \"spark-bin\")))\n ]\n\n @property\n def data(self) -> dict:\n return {}\n\n\nclass SparkHistory(Component, TemplateRequired, FilesCopyRequired, HasData):\n @property\n def component_base_dir(self) -> str:\n return os.path.join(self.TARGET_BASE_PATH, \"spark-history\")\n\n @property\n def data(self) -> dict:\n return {\n \"spark_history\": {\"host\": \"spark-history\", \"port\": \"18080\"}\n }\n\n\nclass SparkThrift(Component, TemplateRequired, FilesCopyRequired, HasData):\n @property\n def component_base_dir(self) -> str:\n return os.path.join(self.TARGET_BASE_PATH, \"spark-thrift\")\n\n @property\n def data(self) -> dict:\n return {\n \"spark_thrift\": {\"host\": \"spark-thrift\", \"thrift-port\": \"10010\", \"http-port\": \"10011\"}\n }\n\n\nclass Presto(Component, FilesCopyRequired, TemplateRequired, DownloadRequired, DecompressRequired, HasData):\n TAR_FILE_NAME = \"presto.tar.gz\"\n\n def __init__(self, args: Namespace):\n DownloadRequired.__init__(self, force_download=args.force_download_presto)\n self.presto_version = args.presto_version\n self.num_worker = args.num_presto_worker\n\n @property\n def component_base_dir(self) -> str:\n return os.path.join(self.TARGET_BASE_PATH, \"presto\")\n\n @property\n def links_to_download(self) -> list[Tuple[str, Path]]:\n return [\n ((\"https://github.com/dev-moonduck/presto/releases/download/v{PRESTO_VERSION}\"\n + \"/presto-server-{PRESTO_VERSION}.tar.gz\").format(PRESTO_VERSION=self.presto_version),\n Path(os.path.join(self.component_base_dir, self.TAR_FILE_NAME)))\n ]\n\n @property\n def files_to_decompress(self) -> list[Tuple[Path, Path]]:\n return [\n (Path(os.path.join(self.component_base_dir, self.TAR_FILE_NAME)),\n Path(os.path.join(self.component_base_dir, \"presto-bin\")))\n ]\n\n @property\n def data(self) -> dict:\n return {\n \"presto_server\": {\"host\": \"presto-server\", \"port\": \"8081\"}\n }\n\n\nclass ComponentFactory:\n @staticmethod\n def get_components(args: Namespace) -> list[Component]:\n components = [Scripts(), ClusterStarter(), Hadoop(args)]\n if args.hive or args.all:\n components.append(Hive(args))\n if args.spark_thrift or args.spark_history or args.all:\n components.append(Spark(args))\n if args.spark_history or args.all:\n components.append(SparkHistory())\n if args.spark_thrift or args.all:\n components.append(SparkThrift())\n if args.presto or args.all:\n components.append(Presto(args))\n if args.hue or args.all:\n components.append(Hue())\n return components\n","sub_path":"component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":15890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"183753282","text":"#! /usr/bin/env python3\n\nimport sys\n\nresistor_colours = [\"black\" ,\"brown\", \"red\", \"orange\", \"yellow\", \"green\", \"blue\" ,\"violet\", \"grey\", \"gold\", \"silver\"]\n\nfirst_band = sys.argv[1]\nsecond_band = sys.argv[2]\nthird_band = sys.argv[3]\ntolerance = sys.argv[4]\nif len(sys.argv) == 1:\n for colour in range(0, 11):\n print(resistor_colours[colour])\nelif len(sys.argv) == 6:\n print (\"yo!\")\nelse:\n print(\"enter entire value\")\n","sub_path":"exercises/04-resistor-value-calculator.py","file_name":"04-resistor-value-calculator.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"544148228","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n#\n# Copyright 2013 Mellanox Technologies, Ltd\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.\n\n\n# VSA Constants\n\nERR_TWISTED = 3\nERR_HA_SLAVE = 11\nERR_HA_TRANSITION = 12\nERR_COMPUTE_NODE = 13\nERR_LOADPVD = 15\nERR_LOADPVD_LO = 17\n\n# Data refresh period in seconds, 0 means no periodic refresh\nREFRESH_PERIOD = 60\n\n# Communication ports\nSANSRV_XMLRPC_PORT = 7080\nVSAD_XMLRPC_PORT = 7081\nMANHOLE_PORT = 7082\n\n# Timeout for vsad rpc connections\nVSAD_RPC_TIMEOUT = 30\n\nMANHOLE_CREDENTIALS = { 'admin': '123456' }\nWEBPORTAL_CREDENTIALS = { 'admin': '123456' }\n\nparamopts=['vendor_id','product_id','product_rev','scsi_id','scsi_sn','removable','mode_page','sense_format','online','path','direct']\niSCSIOpts=['MaxRecvDataSegmentLength','MaxXmitDataSegmentLength','DataDigest','HeaderDigest'\n,'InitialR2T','MaxOutstandingR2T','ImmediateData','FirstBurstLength','MaxBurstLength',\n'DataPDUInOrder','DataSequenceInOrder','ErrorRecoveryLevel','IFMarker','OFMarker','DefaultTime2Wait',\n'DefaultTime2Retain','OFMarkInt','IFMarkInt','MaxConnections','RDMAExtensions','TargetRecvDataSegmentLength'\n,'InitiatorRecvDataSegmentLength','MaxOutstandingUnexpectedPDUs']\n\nshowlist=['system','config','log','version','cache','fctree']\n\n# Enums\nfrom enum import Enum\nTransport = Enum('iser', 'iscsi')\nOsType = Enum('unknown', 'linux', 'windows', 'vmware', 'other')\nObjState = Enum('unknown', 'created', 'running', 'blocked', 'error', 'absent', 'down',\n 'offline', 'degraded', 'delete', 'slaved', 'other')\n\ndef IsRunning(obj):\n \"\"\"\n The description of IsRunning comes here.\n @param obj\n @return\n \"\"\"\n return (obj.state==ObjState.running or obj.state==ObjState.degraded)\n\nReqState=Enum('enabled','disabled','error')\nClusterState=Enum('master','standby','slave','none','disabled','local','transition','standalone','compute')\nRaidLevel=Enum('none','0','1','5','6','10','dr','linear')\nCachePolicy=Enum('fifo','lru')\nIoSchedType=Enum('default','noop','cfq','deadline','anticipatory')\nQualityType=Enum('unknown','slow','average','fast','fastest')\nAlarmType=Enum('add', 'delete', 'state_change', 'error')\n\n\n# Flash Cache\nCACHEVGN = 'cache.vg' # name of the cache volume group\nCACHESEP = '._.' # replace the ':' char\nCACHEPFX = 'vcache.' # VSA flashcache prefix\nCACHECMDS = 'zero_stats','do_sync','stop_sync','reclaim_policy','write_merge','dirty_thresh_pct','fast_remove','fallow_delay'\n\n# constants for disk stats\nRDIO=0\nRDSEC=1\nRDWAIT=2\nRDMRG=3\nWRIO=4\nWRSEC=5\nWRWAIT=6\nWRMRG=7\n\n# log menu options\nlogopt=['agent','audit','event','tgt','webportal']\n\n# error return codes\nILLEGAL_EXT_NAME = 2\nEXT_IS_LOCKED = 3\nEXT_NOT_FOUND = 4\nEXT_NOT_RUNNING = 5\nEXT_IS_PRIVATE = 6\nEXT_NOT_ENABLED = 7\n\n# SNMP\nSNMP_TRAP_PORT = 162\nSNMP_TRAP_COMMUNITY = 'public'\n","sub_path":"src/vsa/infra/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"334223867","text":"\"\"\"A module for keyboard presses emulation.\n\nAs MAME does not always register single presses with pyautogui certain functions perform multiple presses to\ncircumvent that.\n\nWARNING: MAME does not accept keyboard emulators on Windows as of more recent versions (MacOS works,\nLinux not tested). To fix that, a custom version of MAME with DIRECT_INPUT enabled must be used.\n\"\"\"\n\nimport pyautogui\n\n\ndef move_car_in_direction(direction):\n for key in possible_keys_for_move:\n if keys_for_direction[direction] and key in keys_for_direction[direction]:\n pyautogui.keyDown(key)\n else:\n pyautogui.keyUp(key)\n\n\ndef exit_game():\n pyautogui.press(\"esc\", interval=0.1)\n pyautogui.press(\"esc\", interval=0.1)\n\n\ndef restart_game():\n pyautogui.press(\"f3\", interval=0.1)\n pyautogui.press(\"f3\", interval=0.1)\n\n\ndef insert_coin():\n pyautogui.press(\"5\", interval=0.1)\n pyautogui.press(\"5\", interval=0.1)\n pyautogui.press(\"5\", interval=0.1)\n\n\nkeys_for_direction = {\n 'L': ['left'],\n 'R': ['right'],\n 'F': ['up'],\n 'FR': ['up', 'right'],\n 'FL': ['up', 'left'],\n 'S': None\n}\n\npossible_keys_for_move = ['up', 'left', 'right']\n","sub_path":"src/gamecontrols.py","file_name":"gamecontrols.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"98082588","text":"def fields_template():\n\n alldefs = dict()\n dblink = 'integer'\n\n #alldefs[\"TblAdmins\"] = dict(\n #IIDD='string',\n #Name='string',\n #Password='string',\n #)\n\n alldefs[\"TblDefaults\"] = dict(\n IIDD='integer',\n AdminMaxResultsInPage='integer',\n UserMaxResultsInPage='integer',\n PhotosInMember='integer',\n PhotosInEvent='integer',\n NormalPhotoWidth='integer',\n ThumbnailPhotoWidth='integer',\n AdminThumbnailPhotoHeight='integer',\n UserMaxRandomEventsInMainPage='integer',\n PageHitsCountingStatus='integer',\n CommentsEmailName='string',\n CommentsEmailAddress='string',\n IdentifyEmailName='string',\n IdentifyEmailAddress='string',\n MailHost='string',\n MailPort='integer',\n MailFromAddress='string',\n MailFromName='string',\n UserMaxPhotosInUnidentifiedPage='integer',\n AdminHrefInitialAddress='string',\n )\n\n #alldefs[\"TblDocuments\"] = dict(\n #IIDD='string',\n #ArchiveNum='string',\n #DocumentDate='string',\n #Description='string',\n #LocationInDisk='string',\n #StatusID='string',\n #)\n\n #alldefs[\"TblEventDocuments\"] = dict(\n #EventID='string',\n #DocumentID='string',\n #EventDocumentRank='string',\n #)\n\n alldefs[\"TblEventMembers\"] = dict(\n EventID=dblink,\n MemberID=dblink,\n EventMemberRank='integer',\n )\n\n alldefs[\"TblEventPhotos\"] = dict(\n EventID=dblink,\n PhotoID=dblink,\n EventPhotoRank='integer',\n )\n\n alldefs[\"TblEventTypes\"] = dict(\n IIDD=dblink,\n Name='string',\n Description='string',\n ImageName='string',\n )\n\n alldefs[\"TblEvents\"] = dict(\n IIDD=dblink,\n Name='string',\n SSource='string',\n EventDate='string', #may be missing, just year, years range or true date\n Place='string',\n Description='string',\n KeyWords='string',\n EventRank='integer',\n TypeID=dblink, #db.TblEventTypes\n ObjectID=dblink, #db.TblObjects\n StatusID=dblink, #db.TblStatuses\n PageHits='integer',\n DescriptionNoHtml='string',\n )\n\n alldefs[\"TblFamilyConnectionTypes\"] = dict(\n IIDD=dblink,\n Description='string',\n )\n\n #alldefs[\"TblHrefCategories\"] = dict(\n #IIDD='string',\n #Name='string',\n #CategoryRank='string',\n #)\n\n #alldefs[\"TblHrefCategoryCategories\"] = dict(\n #ChildCategoryID='string',\n #ParentCategoryID='string',\n #ChildHierarchyLevel='string',\n #)\n\n alldefs[\"TblHrefCategoryHrefs\"] = dict(\n HrefID=dblink, #db.Tbl???\n CategoryID='string',\n )\n\n alldefs[\"TblHrefTypes\"] = dict(\n IIDD=dblink,\n Name='string',\n )\n\n #alldefs[\"TblHrefs\"] = dict(\n #IIDD='string',\n #Name='string',\n #Description='string',\n #Href='string',\n #HrefTypeID='string',\n #HrefRank='string',\n #DescriptionNoHtml='string',\n #)\n\n #alldefs[\"TblJokes\"] = dict(\n #IIDD='string',\n #Description='string',\n #)\n\n alldefs[\"TblMemberConnections\"] = dict(\n IIDD=dblink,\n MemberID=dblink, #db.TblMdembers\n ConnectToMemberID=dblink, #db.TblMdembers\n ConnectionTypeID=dblink, #db.TblFamilyConnectionTypes\n Name='string',\n DateOfBirth='string', #redundant\n PlaceOfBirth='string',\n Professions='string',\n )\n\n #alldefs[\"TblMemberDocuments\"] = dict(\n #MemberID='string',\n #DocumentID='string',\n #MemberDocumentRank='string',\n #)\n\n alldefs[\"TblMemberPhotos\"] = dict(\n MemberID=dblink, #db.TblMembers\n PhotoID=dblink, #db.TblMembers\n MemberPhotoRank='integer',\n )\n\n alldefs[\"TblMembers\"] = dict(\n IIDD=dblink,\n Name='string',\n FormerName='string',\n DateOfBirth='string', #may be missing, year or range...\n PlaceOfBirth='string',\n DateOfAlia='string', #missing or year\n DateOfMember='string', #missing or year\n Education='string', #drop it\n Institute='string', #drop it\n Professions='string', #drop it\n LifeStory='text',\n KeyWords='string',\n ObjectID=dblink, #db.TblObjects. probably reduntdant\n NickName='string',\n StatusID=dblink, #db.TblStatuses\n PageHits='integer',\n LifeStoryNoHtml='text',\n )\n\n alldefs[\"TblObjects\"] = dict(\n IIDD=dblink,\n Description='string',\n Priority='integer',\n HebrewDescription='string',\n )\n\n alldefs[\"TblPhotos\"] = dict(\n IIDD=dblink,\n ArchiveNum='string',\n PhotoDate='string', #range, year, etc.\n Name='string',\n Description='string',\n Photographer='string',\n KeyWords='string',\n LocationInDisk='string',\n PhotoRank='integer',\n ObjectID=dblink, #db.TblObjects\n Recognized='boolean',\n StatusID=dblink, #db.TblStatuses\n PageHits='integer',\n DescriptionNoHtml='string',\n )\n\n alldefs[\"TblStatuses\"] = dict(\n IIDD=dblink,\n Name='string',\n )\n\n alldefs[\"TblSuperAdmins\"] = dict(\n IIDD=dblink,\n Name='string',\n Password='string',\n )\n\n #alldefs[\"TblSuperAdminsNickNames\"] = dict(\n #IIDD='string',\n #NickName='string',\n #)\n\n alldefs[\"TblTerms\"] = dict(\n IIDD=dblink,\n Name='string',\n TermTranslation='string',\n Background='string',\n InventedBy='string',\n InventedByMemberID=dblink, #db.TblMembers\n ObjectID=dblink, #db.TblObjects\n StatusID=dblink, #db.TblStatuses\n PageHits='integer',\n BackgroundNoHtml='string',\n )\n\n #alldefs[\"vw_displayableMembers\"] = dict(\n #IIDD='string',\n #Name='string',\n #)\n\n #alldefs[\"vw_displayablePhotoIDs\"] = dict(\n #PhotoID='string',\n #)\n\n #alldefs[\"vw_siteEventPhotosGroupedAndOrd\"] = dict(\n #EventID='string',\n #FixedRandomValue='string',\n #)\n\n #alldefs[\"vw_siteEventPhotosHighestRanke1\"] = dict(\n #EventID='string',\n #PhotoPath='string',\n #)\n\n #alldefs[\"vw_siteEventPhotosHighestRanked\"] = dict(\n #EventID='string',\n #PhotoID='string',\n #)\n\n #alldefs[\"vw_siteEventPhotosOrderedByRan1\"] = dict(\n #EventID='string',\n #FixedRandomValue='string',\n #EventPhotoRank='string',\n #)\n\n #alldefs[\"vw_siteEventPhotosOrderedByRank\"] = dict(\n #EventID='string',\n #PhotoID='string',\n #EventPhotoRank='string',\n #RandomValue='string',\n #)\n\n #alldefs[\"vw_siteMemberPhotosGroupedAndOr\"] = dict(\n #MemberID='string',\n #FixedRandomValue='string',\n #)\n\n #alldefs[\"vw_siteMemberPhotosHighestRank1\"] = dict(\n #MemberID='string',\n #PhotoPath='string',\n #)\n\n #alldefs[\"vw_siteMemberPhotosHighestRanke\"] = dict(\n #MemberID='string',\n #PhotoID='string',\n #)\n\n #alldefs[\"vw_siteMemberPhotosOrderedByRa1\"] = dict(\n #MemberID='string',\n #FixedRandomValue='string',\n #MemberPhotoRank='string',\n #)\n\n #alldefs[\"vw_siteMemberPhotosOrderedByRan\"] = dict(\n #MemberID='string',\n #PhotoID='string',\n #MemberPhotoRank='string',\n #RandomValue='string',\n #)\n\n return alldefs\n\ndef create_db_defs():\n out_name = '/home/haim/fossil_projects/gbs/private/db_defs.py'\n alldefs = fields_template()\n with open(out_name, 'w') as out:\n for tbl in sorted(alldefs):\n out.write(\"db.define_table('{}',\\n\".format(tbl))\n fields = alldefs[tbl]\n for field in sorted(fields):\n out.write(\" Field('{}', type='{}'),\\n\".format(field, fields[field]))\n out.write(')\\n\\n')\n \nif __name__ == '__main__':\n create_db_defs() \n","sub_path":"modules/porting/old_db_mappings.py","file_name":"old_db_mappings.py","file_ext":"py","file_size_in_byte":7962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"417708666","text":"def Rabin_Karp(p,c):\n\t'''\n\tRabin-Karp Algorithm -- 滚动哈希算法:\n\t选取两个合适的互素常数b和h(l plen:\n\t\treturn False\n\tres = []\n\t# hash radix\n\tb = 2 # 100000000007\n\tt = b**clen\n\n\t# 计算p和c长度为clen的前缀对应的哈希值\n\tphash=0\n\tchash=0\n\tfor i in range(clen):\n\t\tphash = phash * b + ord(p[i])\n\t\tchash = chash * b + ord(c[i])\n\n\t# 对p不断右移一位,更新哈希值并判断\n\tfor x in range(0, plen-clen+1):\n\t\tif phash == chash:\n\t\t\tres.append(x)\n\t\tif x + clen < plen:\n\t\t\tphash = phash*b - ord(p[x])*t + ord(p[x+clen])\n\n\tif res:\n\t\treturn res\n\telse:\n\t\treturn False\n\n\nprint(Rabin_Karp('abcbc','ebc')) ","sub_path":"String Problem/Rabin_Karp.py","file_name":"Rabin_Karp.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"230549123","text":"import os\nimport abacusSoftware.constants as constants\nimport pyAbacus as abacus\nfrom PyQt5 import QtGui\n\ndef timeInUnitsToMs(time):\n value = 0\n if 'ms' in time:\n value = int(time.replace(' ms', ''))\n elif 's' in time:\n value = float(time.replace(' s', ''))\n value = int(1000 * value)\n return value\n\ndef setSamplingComboBox(comboBox, values = abacus.constants.SAMPLING_VALUES, default_value = abacus.constants.SAMPLING_DEFAULT_VALUE):\n comboBox.clear()\n\n model = comboBox.model()\n for row in values:\n if row < 1000:\n item = QtGui.QStandardItem(\"%d ms\" % row)\n elif row < 10000:\n item = QtGui.QStandardItem(\"%.1f s\" % (row / 1000))\n else:\n item = QtGui.QStandardItem(\"%d s\" % (row / 1000))\n # if row < abacus.SAMP_CUTOFF:\n # item.setBackground(QtGui.QColor('red'))\n # item.setForeground(QtGui.QColor('white'))\n model.appendRow(item)\n if default_value < 1000: unit = \"ms\"\n else: unit = \"s\"; value = default_value // 1000\n comboBox.setCurrentIndex(comboBox.findText(\"%d %s\"%(value, unit)))\n\ndef setCoincidenceSpinBox(spinBox, value = abacus.constants.COINCIDENCE_WINDOW_DEFAULT_VALUE):\n spinBox.setMinimum(abacus.constants.COINCIDENCE_WINDOW_MINIMUM_VALUE)\n spinBox.setMaximum(abacus.constants.COINCIDENCE_WINDOW_MAXIMUM_VALUE)\n spinBox.setSingleStep(abacus.constants.COINCIDENCE_WINDOW_STEP_VALUE)\n spinBox.setValue(value)\n \ndef setDelaySpinBox(spinBox, value = abacus.constants.DELAY_DEFAULT_VALUE):\n spinBox.setMinimum(abacus.constants.DELAY_MINIMUM_VALUE)\n spinBox.setMaximum(abacus.constants.DELAY_MAXIMUM_VALUE)\n spinBox.setSingleStep(abacus.constants.DELAY_STEP_VALUE)\n spinBox.setValue(value) \n\ndef setSleepSpinBox(spinBox, value = abacus.constants.SLEEP_DEFAULT_VALUE):\n spinBox.setMinimum(abacus.constants.SLEEP_MINIMUM_VALUE)\n spinBox.setMaximum(abacus.constants.SLEEP_MAXIMUM_VALUE)\n spinBox.setSingleStep(abacus.constants.SLEEP_STEP_VALUE)\n spinBox.setValue(value)\n\ndef findWidgets(class_, widget):\n return [att for att in dir(class_) if widget in att]\n\ndef unicodePath(path):\n return path.replace(\"\\\\\", \"/\")\n\ndef readConstantsFile():\n if os.path.exists(constants.SETTINGS_PATH):\n with open(constants.SETTINGS_PATH) as file:\n for line in file:\n try:\n exec(\"constants.%s\" % line)\n except SyntaxError as e:\n pass\n constants.SETTING_FILE_EXISTS = True\n else:\n print(\"Settings file not found at: %s\"%constants.SETTINGS_PATH)\n\ndef updateConstants(class_):\n for (name, action) in zip(constants.WIDGETS_NAMES, constants.WIDGETS_SET_ACTIONS):\n attributes = findWidgets(class_, name)\n for att in attributes:\n if att in dir(constants):\n val = eval(\"constants.%s\"%att)\n if name != \"comboBox\":\n try: #if the element does not exist, skip. Example: sleep_C in a 2ch device\n exec(action%(att, val)) \n except:\n pass\n \n else:\n try: #if the element does not exist, skip. Example: sleep_C in a 2ch device\n exec(action%(att, att, val))\n except:\n pass\n\ndef findDocuments():\n if constants.CURRENT_OS == \"win32\":\n import ctypes.wintypes\n buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)\n ctypes.windll.shell32.SHGetFolderPathW(None, 5, None, 0, buf)\n buf = buf.value\n else:\n buf = os.path.expanduser(\"~\")\n return buf\n","sub_path":"AbacusSoftware/abacusSoftware/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"163734257","text":"\"\"\"Tests for acme.jose.jwk.\"\"\"\nimport os\nimport pkg_resources\nimport unittest\n\nfrom Crypto.PublicKey import RSA\n\nfrom acme.jose import errors\nfrom acme.jose import util\n\n\nRSA256_KEY = util.HashableRSAKey(RSA.importKey(pkg_resources.resource_string(\n __name__, os.path.join('testdata', 'rsa256_key.pem'))))\nRSA512_KEY = util.HashableRSAKey(RSA.importKey(pkg_resources.resource_string(\n __name__, os.path.join('testdata', 'rsa512_key.pem'))))\n\n\nclass JWKOctTest(unittest.TestCase):\n \"\"\"Tests for acme.jose.jwk.JWKOct.\"\"\"\n\n def setUp(self):\n from acme.jose.jwk import JWKOct\n self.jwk = JWKOct(key='foo')\n self.jobj = {'kty': 'oct', 'k': 'foo'}\n\n def test_to_partial_json(self):\n self.assertEqual(self.jwk.to_partial_json(), self.jobj)\n\n def test_from_json(self):\n from acme.jose.jwk import JWKOct\n self.assertEqual(self.jwk, JWKOct.from_json(self.jobj))\n\n def test_from_json_hashable(self):\n from acme.jose.jwk import JWKOct\n hash(JWKOct.from_json(self.jobj))\n\n def test_load(self):\n from acme.jose.jwk import JWKOct\n self.assertEqual(self.jwk, JWKOct.load('foo'))\n\n def test_public(self):\n self.assertTrue(self.jwk.public() is self.jwk)\n\n\nclass JWKRSATest(unittest.TestCase):\n \"\"\"Tests for acme.jose.jwk.JWKRSA.\"\"\"\n\n def setUp(self):\n from acme.jose.jwk import JWKRSA\n self.jwk256 = JWKRSA(key=RSA256_KEY.publickey())\n self.jwk256_private = JWKRSA(key=RSA256_KEY)\n self.jwk256json = {\n 'kty': 'RSA',\n 'e': 'AQAB',\n 'n': 'm2Fylv-Uz7trgTW8EBHP3FQSMeZs2GNQ6VRo1sIVJEk',\n }\n self.jwk512 = JWKRSA(key=RSA512_KEY.publickey())\n self.jwk512json = {\n 'kty': 'RSA',\n 'e': 'AQAB',\n 'n': 'rHVztFHtH92ucFJD_N_HW9AsdRsUuHUBBBDlHwNlRd3fp5'\n '80rv2-6QWE30cWgdmJS86ObRz6lUTor4R0T-3C5Q',\n }\n\n def test_equals(self):\n self.assertEqual(self.jwk256, self.jwk256)\n self.assertEqual(self.jwk512, self.jwk512)\n\n def test_not_equals(self):\n self.assertNotEqual(self.jwk256, self.jwk512)\n self.assertNotEqual(self.jwk512, self.jwk256)\n\n def test_load(self):\n from acme.jose.jwk import JWKRSA\n self.assertEqual(\n JWKRSA(key=util.HashableRSAKey(RSA256_KEY)), JWKRSA.load(\n pkg_resources.resource_string(\n __name__, os.path.join('testdata', 'rsa256_key.pem'))))\n\n def test_public(self):\n self.assertEqual(self.jwk256, self.jwk256_private.public())\n\n def test_to_partial_json(self):\n self.assertEqual(self.jwk256.to_partial_json(), self.jwk256json)\n self.assertEqual(self.jwk512.to_partial_json(), self.jwk512json)\n\n def test_from_json(self):\n from acme.jose.jwk import JWK\n self.assertEqual(self.jwk256, JWK.from_json(self.jwk256json))\n # TODO: fix schemata to allow RSA512\n #self.assertEqual(self.jwk512, JWK.from_json(self.jwk512json))\n\n def test_from_json_hashable(self):\n from acme.jose.jwk import JWK\n hash(JWK.from_json(self.jwk256json))\n\n def test_from_json_non_schema_errors(self):\n # valid against schema, but still failing\n from acme.jose.jwk import JWK\n self.assertRaises(errors.DeserializationError, JWK.from_json,\n {'kty': 'RSA', 'e': 'AQAB', 'n': ''})\n self.assertRaises(errors.DeserializationError, JWK.from_json,\n {'kty': 'RSA', 'e': 'AQAB', 'n': '1'})\n\n\nif __name__ == '__main__':\n unittest.main() # pragma: no cover\n","sub_path":"acme/jose/jwk_test.py","file_name":"jwk_test.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"55490487","text":"'''\r\nCreated on 2018/09/19\r\n\r\n@author: Taichi\r\n'''\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.colors import ListedColormap\r\n\r\ndef plot_decision_regions(x,y,classifier,test_idx=None,resolution=0.02):\r\n markers=('s','x','o','^','v')\r\n colors=('red','blue','lightgreen','gray','cyan')\r\n cmap=ListedColormap(colors[:len(np.unique(y))])\r\n\r\n x1_min,x1_max=x[:,0].min()-1,x[:,0].max+1\r\n x2_min,x2_max=x[:,1].min()-1,x[:,1].max+1\r\n\r\n xx1,xx2=np.meshgrid(np.arange(x1_min,x1_max,resolution),\r\n np.arange(x2_min,x2_max,resolution))\r\n Z=classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T)\r\n Z=Z.reshape(xx1.shape)\r\n plt.contourf(xx1,xx2,Z,alpha=0.4,cmap=cmap)\r\n plt.xlim(xx1.min(),xx1.max())\r\n plt.ylim(xx2.min(),xx2.max())\r\n\r\n for idx, cl in enumerate(np.unique(y)):\r\n plt.scatter(x=x[y==cl,0],y=x[y==cl,1],\r\n alpha=0.8,c=cmap(idx),\r\n marker=markers[idx],label=cl)\r\n if test_idx:\r\n x_test,y_test=x[test_idx,:],y[test_idx]\r\n plt.scatter(x_test[:,0],x_test[:,1],c='',alpha=1.0,linewidth=1,marker='o',s=55,lable='test_set')\r\n\r\nlink=''\r\nlink2=''\r\ndf=pd.read_csv(link,encoding='cp932')\r\ndf=pd.read_table(link,encoding='cp932')\r\ndf=pd.read_excel(link,sheetname='',encoding='cp932')\r\ndf2=pd.read_csv(link2,encoding='cp932')\r\ndf2=pd.read_table(link2,encoding='cp932')\r\ndf2=pd.read_excel(link2,sheetname='',encoding='cp932')\r\n\r\n#二つのデータを分割したが、k分割などで分けてもok\r\nx_train=df[''].values\r\ny_train=df[''].values\r\nx_test=df2[''].values\r\ny_test=df2[''].values\r\nx_combined=np.vstack([x_train,x_test])\r\ny_combined=np.hstack([y_train,y_test])\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n#エントロピーを指標とするランダムフォレストのインスタンスの生成\r\nforest=RandomForestClassifier(criterion='entropy',n_estimators=10,random_state=1,n_jobs=2)\r\n#ランダムフォレストのモデルにトレーニングデータを適合させる\r\nforest.fit(x_train,y_train)\r\nplot_decision_regions(x_combined,y_combined,classifier=forest,test_idx=range(105,150))\r\nplt.xlabel('')\r\nplt.ylabel('')\r\nplt.legend(loc='upper left')\r\nplt.show()","sub_path":"RandomForest.py","file_name":"RandomForest.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"66516401","text":"from __future__ import division, print_function, absolute_import\n\nimport tflearn\nfrom tflearn.data_utils import shuffle, to_categorical\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.normalization import local_response_normalization\nfrom tflearn.data_preprocessing import ImagePreprocessing\nfrom tflearn.layers.estimator import regression\n\n\ndef get_data():\n # Data loading and preprocessing\n from tflearn.datasets import cifar10\n (X, Y), (X_test, Y_test) = cifar10.load_data()\n X, Y = shuffle(X, Y)\n Y = to_categorical(Y, 10)\n Y_test = to_categorical(Y_test, 10)\n return (X, Y), (X_test, Y_test)\n\n\ndef get_network():\n # Building convolutional network\n network = input_data(shape=[None, 32, 32, 3], name='input')\n network = conv_2d(network, 32, 3, activation='relu', regularizer=\"L2\")\n network = max_pool_2d(network, 2)\n network = conv_2d(network, 64, 3, activation='relu', regularizer=\"L2\")\n network = max_pool_2d(network, 2)\n\n network = conv_2d(network, 128, 3, activation='relu', regularizer=\"L2\")\n network = max_pool_2d(network, 2)\n\n network = fully_connected(network, 256, activation='relu')\n network = dropout(network, 0.8)\n network = fully_connected(network, 10, activation='softmax')\n network = regression(network, optimizer='adam', learning_rate=0.01,\n loss='categorical_crossentropy', name='target')\n return network\n\n\ndef main():\n name = 'model6'\n (X, Y), (X_test, Y_test) = get_data()\n network = get_network()\n\n # Training\n model = tflearn.DNN(network, tensorboard_verbose=0, checkpoint_path='checkpoints/' + name + '.tfl.ckpt')\n\n model.load('checkpoints/' + name + '.tfl')\n model.fit({'input': X}, {'target': Y}, n_epoch=12,\n validation_set=({'input': X_test}, {'target': Y_test}),\n snapshot_step=100, show_metric=True, batch_size=96, run_id='cifar10_cnn6')\n\n # Manually save model\n model.save('checkpoints/' + name + '.tfl')\n\n\nmain()\n","sub_path":"tensor6.py","file_name":"tensor6.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"459062061","text":"import os\nimport sys\nimport warnings\n\nimport pycrfsuite\n\nfrom nalaf.structures.data import Label\nfrom nalaf.learning.taggers import Tagger\n\n\nclass PyCRFSuite:\n\n def __init__(self, model_file=None):\n self.model_file = model_file\n\n if self.model_file is None:\n self.tagger = None\n else:\n self.tagger = pycrfsuite.Tagger()\n self.tagger.open(self.model_file)\n\n\n def annotate(self, corpus, class_id):\n \"\"\"\n :type corpus: nalaf.structures.data.Dataset\n :type class_id: str ~ to annotate with\n \"\"\"\n\n for sentence in corpus.sentences():\n labels = self.tagger.tag(pycrfsuite.ItemSequence(token.features for token in sentence))\n\n for token_index in range(len(sentence)):\n label = labels[token_index]\n sentence[token_index].predicted_labels = [Label(label, self.tagger.marginal(label, token_index))]\n\n corpus.form_predicted_annotations(class_id)\n\n\n @staticmethod\n def train(data, model_file, params=None):\n \"\"\"\n :type data: nalaf.structures.data.Dataset\n :type model_file: str ~ filename (from local file system) to save trained model to. If None, no model is saved.\n \"\"\"\n\n trainer = pycrfsuite.Trainer()\n if params is not None:\n trainer.set_params(params)\n\n for sentence in data.sentences():\n trainer.append(pycrfsuite.ItemSequence([token.features for token in sentence]),\n [token.original_labels[0].value for token in sentence])\n\n # The CRFSuite library handles the \"pickling\" of the file; saves the model here\n trainer.train(model_file)\n\n\n @staticmethod\n def tag(data, model_file, class_id):\n warnings.warn('Use non-static `annotate` instead', DeprecationWarning)\n\n \"\"\"\n :type data: nalaf.structures.data.Dataset\n :type model_file: str\n \"\"\"\n\n tagger = pycrfsuite.Tagger()\n tagger.open(model_file)\n\n for sentence in data.sentences():\n labels = tagger.tag(pycrfsuite.ItemSequence(token.features for token in sentence))\n\n for token_index in range(len(sentence)):\n label = labels[token_index]\n sentence[token_index].predicted_labels = [Label(label, tagger.marginal(label, token_index))]\n\n data.form_predicted_annotations(class_id)\n\n\nclass CRFSuite:\n \"\"\"\n Basic class for interaction with CRFSuite\n \"\"\"\n\n def __init__(self, directory, minify=False):\n warnings.warn('Deprecated. Please use PyCRFSuite instead', DeprecationWarning)\n\n self.directory = os.path.abspath(directory)\n \"\"\"the directory where the CRFSuite executable is located\"\"\"\n self.model_filename = 'example_entity_model'\n \"\"\"name to be used for saving the model\"\"\"\n if sys.platform.startswith('linux'):\n self.crf_suite_call = './crfsuite'\n else:\n self.crf_suite_call = 'crfsuite'\n self.minify = minify\n \"\"\"controls whether to replace feature names with an index in order to minimize input file length\"\"\"\n\n\n def create_input_file(self, dataset, mode):\n \"\"\"\n Creates the input files for training, testing or prediction in the appropriate format required by CRFSuite.\n Saves the files in the same directory where the executable is located.\n\n :type dataset: nalaf.structures.data.Dataset\n :param mode: one of the following 'train' or 'test' or 'predict'\n :type mode: str\n \"\"\"\n if self.minify:\n key_map = {key: index for index, key in\n enumerate(set(key for token in dataset.tokens() for key in token.features.keys()))}\n key_string = lambda key: key_map[key]\n else:\n key_string = lambda key: key\n\n with open(os.path.join(self.directory, mode), 'w', encoding='utf-8') as file:\n for sentence in dataset.sentences():\n for token in sentence:\n features = '\\t'.join(['{}:{}'.format(key_string(key), value)\n if type(value) is float\n else '{}={}'.format(key_string(key), str(value).replace(':', '_COLON_'))\n for key, value in token.features.items()])\n\n if mode in ('train', 'test'):\n label = token.original_labels[0].value\n else:\n label = '?'\n file.write('{}\\t{}\\n'.format(label, features))\n file.write('\\n')\n\n\n def learn(self, options=''):\n \"\"\"\n Train and save a CRF model with the latest train file.\n \"\"\"\n os.chdir(self.directory)\n if options:\n os.system('{} learn {}'.format(self.crf_suite_call, options))\n else:\n os.system('{} learn -m {} train'.format(self.crf_suite_call, self.model_filename))\n\n\n def tag(self, options=''):\n \"\"\"\n Test a CRF model with the latest model and test file.\n \"\"\"\n os.chdir(self.directory)\n if options:\n os.system('{} tag {}'.format(self.crf_suite_call, options))\n else:\n os.system('{} tag -qt -m {} test'.format(self.crf_suite_call, self.model_filename))\n\n\n def read_predictions(self, dataset, class_id, prediction_file='output.txt'):\n \"\"\"\n :type dataset: nalaf.structures.data.Dataset\n\n Reads in the predictions made by our model for each token and stores them into token.predicted_label[]\n\n Requires a dataset object and the output prediction file.\n\n The default output prediction file is 'output.txt'. The format is:\n * [predicted label]:[marginal probability]\n * in new line for each token\n * followed by a blank line for the end of the sentence\n\n IMPORTANT NOTE:\n Assumes a call to the test() function was made previously with the 'i' option included.\n Furthermore, it assumes we are calling it with the same dataset object used to create the test file.\n\n For example first we would call:\n * crf.create_input_file(dataset=test, mode='test')\n * crf.test(options='-m example_entity_model -i test > output.txt')\n Then we would call:\n * crf.read_predictions(dataset=test)\n \"\"\"\n\n os.chdir(self.directory)\n with open(prediction_file) as file:\n for sentence in dataset.sentences():\n for token in sentence:\n label, probability = file.readline().split(':')\n token.predicted_labels = [Label(label, float(probability))]\n\n file.readline() # skip the empty line signifying new sentence\n\n # call form_predicted_annotations() to populate the mention level predictions\n dataset.form_predicted_annotations(class_id)\n\n\nclass CRFSuiteTagger(Tagger):\n \"\"\"\n Performs tagging with a binary model using CRFSuite\n\n :type crf_suite: nalaf.learning.crfsuite.CRFSuite\n \"\"\"\n\n def __init__(self, predicts_classes, crf_suite, model_file='example_entity_model'):\n warnings.warn('Use PyCRFSuite', DeprecationWarning)\n\n super().__init__(predicts_classes)\n self.crf_suite = crf_suite\n \"\"\"an instance of CRFSuite used to actually generate predictions\"\"\"\n self.model_file = model_file\n \"\"\"path to the binary model used for generating predictions\"\"\"\n\n def tag(self, dataset):\n \"\"\"\n :type dataset: nalaf.structures.data.Dataset\n \"\"\"\n self.crf_suite.create_input_file(dataset, 'predict')\n self.crf_suite.tag('-m {} -i predict > output.txt'.format(self.model_file))\n self.crf_suite.read_predictions(dataset)\n","sub_path":"nalaf/learning/crfsuite.py","file_name":"crfsuite.py","file_ext":"py","file_size_in_byte":7835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"87071015","text":"from lib.base_action import BaseAction\n\n\nclass CreateIP(BaseAction):\n def run(self, subnet_network_mask=None, subnet_name=None,\n vrf_group_id=None, vrf_group=None,\n ipaddress=None, macaddress=None, ip_type=None, tags=None,\n device_name=None, available=None, clear_all=None,\n debug=False):\n\n payload = {\n \"ipaddress\": ipaddress, \"subnet\": subnet_name,\n \"macaddress\": macaddress, \"ip_type\": ip_type,\n \"tags\": tags, \"device\": device_name\n }\n\n print(\"payload: %s\" % payload)\n d42_headers = {'Accept': 'application/json'}\n response = self.post(\n endpoint=\"ips/\",\n payload=payload,\n headers=d42_headers\n )\n # d42 api agent returns response.json(0) if response.ok...:\n if type(response) is dict:\n return response\n else:\n return response.text\n","sub_path":"actions/create_or_edit_ip.py","file_name":"create_or_edit_ip.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"485970988","text":"import os\nimport threading\nfrom queue import Queue\nimport logging\nimport requests\nfrom requests.exceptions import ConnectionError\nfrom bs4 import BeautifulSoup\nfrom page_urls import get_page_links,get_number_of_pages\nfrom constants import all_movies_by_year,header\nimport re\nimport json\nparams = {'year_selected':2018, 'sort':'desc'}\nimport time\nimport random\nfrom threading import Lock,Thread\n\nlogging.basicConfig(format='%(asctime)s -%(funcName)s - %(levelname)s - %(message)s',\n datefmt='%d-%b-%y %H:%M:%S',\n level=logging.INFO, filename=\"log_file.log\")\n\nextract_year_from_url = re.compile('year_selected=(\\d{4})')\n\ndef get_year(url):\n return extract_year_from_url.findall(url)[0]\n\ndef get_links_for_all_movies_by_year(year):\n '''gets the links to all movies in a given year'''\n\n params = {'year_selected':year, 'sort':'desc'}\n\n num_pages = get_number_of_pages(f'{all_movies_by_year}/filtered?year_selected={year}')\n\n if num_pages == '0':\n return [f'{all_movies_by_year}/filtered?year_selected={year}&sort=desc&page={0}']\n else:\n links = [f'{all_movies_by_year}/filtered?year_selected={year}&sort=desc&page={i}' for i in range(0,int(num_pages))]\n\n return links\n\ndef get_links_to_all_movies_on_page(page_url):\n '''takes the url of a to a page with movies as input, returns a list of with urls to all the movies that appear in the page'''\n try:\n page = requests.get(page_url,headers=header)\n except ConnectionError:\n print('Connection error, trying again in 10')\n time.sleep(10)\n return get_links_to_all_movies_on_page(page_url)\n\n except Exception as e:\n logging.error(e)\n\n\n soup = BeautifulSoup(page.content,features=\"html.parser\")\n\n movie_tags = soup.select('span.title.numbered + a.title')\n movie_links = [link.attrs['href'] for link in movie_tags]\n movie_links = [f'https://www.metacritic.com/movie{link}' for link in movie_links]\n\n return movie_links\n\n\n\ndef get_link_for_all_movies_in_single_year(task_queue, write_queue):\n '''takes a list of urls as input, find all the movies in those urls and puts that result (a dict) on queue'''\n tmp_dict = {}\n\n while not task_queue.empty():\n url = task_queue.get()\n year = get_year(url[0])\n\n for link in url:\n\n\n print(f' ({year}) Getting url {link}')\n time.sleep(random.uniform(0.5,1))\n\n completed = False\n\n while not completed:\n try:\n page = requests.get(link,headers=header)\n soup = BeautifulSoup(page.content, features=\"html.parser\")\n movie_titles = [title.text for title in soup.select('span.title.numbered + a h3')]\n movie_tags = soup.select('span.title.numbered + a.title')\n movie_links = [link.attrs['href'] for link in movie_tags]\n movie_name_and_link = {name: f'https://www.metacritic.com{link}' for name, link in\n zip(movie_titles, movie_links)}\n tmp_dict.update({year:movie_name_and_link})\n time.sleep(random.uniform(1, 2))\n completed = True\n\n except ConnectionError:\n print('Connection error, retrying in 10 seconds')\n time.sleep(10)\n\n except Exception as e:\n logging.error(f'Was unable to download {link}, ({e})')\n break\n task_queue.task_done()\n\n write_queue.put(tmp_dict)\n tmp_dict = {}\n\n print(f'{threading.currentThread().name}: Stopping due to empty queue')\n\ndef make_dict_of_links_to_all_movies_by_year(num_workers):\n '''Use workers to get all the movies and save it to a dict that links the movie name to the url to that movie'''\n task_queue = Queue()\n write_queue = Queue()\n write_queue.downloads_complete = False\n\n # get all the links to all the movies\n with open('links_for_all_movies_by_year.txt', 'r') as file:\n content = file.read()\n content = content.split('\\n')\n\n # put urls for all the different pages in all years into the task queue\n unique_years = list(set([get_year(link) for link in content]))\n for year in unique_years:\n task_queue.put([item for item in content if get_year(item) == year])\n\n\n # make a writer queue thread\n writer_thread = Thread(target=write_dict_of_links_to_file,args=[write_queue])\n writer_thread.start()\n # iterate over each link\n for i in range(num_workers):\n workers = [threading.Thread(name=str(i),target=get_link_for_all_movies_in_single_year,args=[task_queue,write_queue]) for i in range(num_workers)]\n for w in workers:\n w.start()\n for w in workers:\n w.join()\n\n write_queue.downloads_complete = True\n\ndef write_dict_of_links_to_file(queue):\n '''Takes a queue as input and continuelesly updates the .json files'''\n FILENAME = 'all_movies_with_titles_and_links_by_year.json'\n\n\n if not os.path.isfile(FILENAME):\n with open(FILENAME,'w+') as file:\n pass\n\n while True and not queue.downloads_complete:\n if queue.empty():\n time.sleep(0.5)\n else:\n output = queue.get()\n with open(FILENAME, 'r+') as file:\n content = file.read()\n if content == '':\n json_dict = output\n file.write(json.dumps(json_dict))\n else:\n try:\n json_dict = json.loads(content)\n json_dict.update(output)\n with open(FILENAME, 'w+') as file2:\n print(f'Updated dict with {output}')\n file2.write(json.dumps(json_dict))\n\n except json.JSONDecodeError as e:\n print(e)\n\n print('Stopping writer queue thread')\n\n\n\n\ndef get_link_of_failed_download(task_queue,write_queue):\n\n while not task_queue.empty():\n time.sleep(random.uniform(0.5,1))\n failed_url = task_queue.get()\n print(f'Trying to fix {failed_url}')\n try:\n page = requests.get(failed_url, headers=header, allow_redirects=True)\n print(f'{failed_url} :: {page.status_code}')\n\n # check if the page was moved\n if 301 in [item.status_code for item in page.history]:\n print(f'{failed_url} has moved')\n real_url = page.url.split('movie_title=')[-1]\n real_url = f'https://www.metacritic.com/movie/{real_url}'\n time.sleep(random.uniform(0.5, 1))\n real_page = requests.get(real_url, headers=header, allow_redirects=True)\n if real_page.status_code == 200:\n soup = BeautifulSoup(real_page.content, features=\"html.parser\")\n product_title = soup.select('.product_page_title h1')[0].text.strip()\n year = soup.select('h1 + .release_year')[0].text.strip()\n\n # send the answer to the write queue\n write_queue.put( (year,product_title,real_page.url) )\n print(f'Fix {product_title}s url to {real_page.url}')\n\n else:\n print(f'Failed to get {real_url} ({real_page.status_code})')\n\n else:\n print(f'{failed_url} has not moved {page.status_code}')\n\n\n except Exception as e:\n print(f'Could not access {failed_url}: {e}')\n\n print('Stopping due to empty task queue')\n\ndef write_fixed_links(task_queue,write_queue):\n\n\n while task_queue.done is False:\n\n while not write_queue.empty():\n year,product_title,fixed_link = write_queue.get()\n\n # open up the json links file and read into memory\n with open('all_movies_with_titles_and_links_by_year.json', 'r') as jsonfile:\n all_movies_dict = json.loads(jsonfile.read())\n all_movies_dict[year][product_title] = fixed_link\n\n # overwrite the file\n with open('all_movies_with_titles_and_links_by_year.json', 'w') as jsonfile:\n jsonfile.write(json.dumps(all_movies_dict))\n\n print('No fixed urls to write, sleeping for 5 secs')\n time.sleep(5)\n\n print('All tasks done, shutting down write queue')\n\n\ndef get_real_links_of_failed_downloads(num_workers):\n\n write_queue = Queue()\n task_queue = Queue()\n task_queue.done = False\n\n # all the tasks to the task queue\n with open('failed_raw_downloads.txt','r') as file:\n for line in file:\n link,error = line.split(',')\n task_queue.put(link)\n\n # start the workers\n workers = []\n for i in range(num_workers):\n workers.append(threading.Thread(target=get_link_of_failed_download,args=[task_queue,write_queue]))\n\n for w in workers:\n w.start()\n for w in workers:\n w.join()\n\n\n print('All workers finished their jobs')\n task_queue.done = True\n\n\nif __name__ == '__main__':\n\n get_real_links_of_failed_downloads(5)\n\n #make_dict_of_links_to_all_movies_by_year(num_workers=20)\n","sub_path":"get_links_for_all_movies.py","file_name":"get_links_for_all_movies.py","file_ext":"py","file_size_in_byte":9253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"323549739","text":"import unittest\n\nfrom utils.deployutils import compile_contracts, attempt_deploy, mine_tx, MASTER, DUMMY\nfrom utils.deployutils import take_snapshot, restore_snapshot\nfrom utils.testutils import assertReverts, ZERO_ADDRESS\nfrom utils.testutils import generate_topic_event_map, get_event_data_from_log\n\nOWNED_SOURCE = \"contracts/Owned.sol\"\n\n\ndef setUpModule():\n print(\"Testing Owned...\")\n\n\ndef tearDownModule():\n print()\n\n\nclass TestOwned(unittest.TestCase):\n def setUp(self):\n self.snapshot = take_snapshot()\n\n def tearDown(self):\n restore_snapshot(self.snapshot)\n\n @classmethod\n def setUpClass(cls):\n cls.assertReverts = assertReverts\n\n compiled = compile_contracts([OWNED_SOURCE])\n cls.owned, txr = attempt_deploy(compiled, 'Owned', MASTER, [MASTER])\n\n cls.owner = lambda self: cls.owned.functions.owner().call()\n cls.nominatedOwner = lambda self: cls.owned.functions.nominatedOwner().call()\n cls.nominateOwner = lambda self, sender, newOwner: mine_tx(\n cls.owned.functions.nominateOwner(newOwner).transact({'from': sender}))\n cls.acceptOwnership = lambda self, sender: mine_tx(\n cls.owned.functions.acceptOwnership().transact({'from': sender}))\n\n cls.owned_event_map = generate_topic_event_map(compiled['Owned']['abi'])\n\n def test_owner_is_master(self):\n self.assertEqual(self.owner(), MASTER)\n\n def test_change_owner(self):\n old_owner = self.owner()\n new_owner = DUMMY\n\n self.assertReverts(self.nominateOwner, new_owner, old_owner)\n nominated_tx = self.nominateOwner(old_owner, new_owner)\n event_data = get_event_data_from_log(self.owned_event_map, nominated_tx.logs[0])\n self.assertEqual(event_data['event'], \"OwnerNominated\")\n self.assertEqual(event_data['args']['newOwner'], new_owner)\n\n self.assertEqual(self.owner(), old_owner)\n self.assertEqual(self.nominatedOwner(), new_owner)\n self.assertReverts(self.nominateOwner, new_owner, old_owner)\n accepted_tx = self.acceptOwnership(new_owner)\n event_data = get_event_data_from_log(self.owned_event_map, accepted_tx.logs[0])\n self.assertEqual(event_data['event'], \"OwnerChanged\")\n self.assertEqual(event_data['args']['oldOwner'], old_owner)\n self.assertEqual(event_data['args']['newOwner'], new_owner)\n\n self.assertEqual(self.nominatedOwner(), ZERO_ADDRESS)\n self.assertEqual(self.owner(), new_owner)\n self.assertReverts(self.nominateOwner, old_owner, new_owner)\n\n self.nominateOwner(new_owner, old_owner)\n self.acceptOwnership(old_owner)\n self.assertEqual(self.owner(), old_owner)\n\n def test_change_invalid_owner(self):\n invalid_account = DUMMY\n self.assertReverts(self.nominateOwner, invalid_account, invalid_account)\n\n def test_undo_change_owner(self):\n old_owner = self.owner()\n new_owner = DUMMY\n\n self.assertReverts(self.nominateOwner, new_owner, old_owner)\n self.nominateOwner(old_owner, new_owner)\n self.nominateOwner(old_owner, ZERO_ADDRESS)\n self.assertReverts(self.acceptOwnership, new_owner)\n","sub_path":"tests/test_Owned.py","file_name":"test_Owned.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"433359679","text":"#encoding: utf-8\nimport xlrd\nimport xlwt\nimport xlutils.copy\n\ndef _getOutCell(outSheet, colIndex, rowIndex):\n \"\"\" HACK: Extract the internal xlwt cell representation. \"\"\"\n row = outSheet._Worksheet__rows.get(rowIndex)\n if not row: return None\n\n cell = row._Row__cells.get(colIndex)\n return cell\n\ndef setOutCell(outSheet, col, row, value):\n \"\"\" Change cell value without changing formatting. \"\"\"\n # HACK to retain cell style.\n previousCell = _getOutCell(outSheet, col, row)\n # END HACK, PART I\n\n outSheet.write(row, col, value)\n\n # HACK, PART II\n if previousCell:\n newCell = _getOutCell(outSheet, col, row)\n if newCell:\n newCell.xf_idx = previousCell.xf_idx\n # END HACK\n\ndef simple_excel(data, infile, outfile):\n\n data = [ [unicode(val, 'utf-8') if isinstance(val, basestring) else val for val in row] for row in data]\n\n inbook = xlrd.open_workbook(infile, formatting_info=True)\n outbook = xlutils.copy.copy(inbook)\n\n outSheet = outbook.get_sheet(0)\n for row, sub_data in enumerate(data):\n for col, value in enumerate(sub_data):\n setOutCell(outSheet, col, row, value)\n\n outbook.save(outfile)\n\ndef multi_sheet(infos, infile, outfile):\n\n inbook = xlrd.open_workbook(infile, formatting_info=True)\n outbook = xlutils.copy.copy(inbook)\n\n\n for id, info in enumerate(infos):\n info['data'] = [ [unicode(val, 'utf-8') if isinstance(val, basestring) else val for val in row] for row in info['data']]\n outSheet = outbook.get_sheet(id)\n for row, sub_data in enumerate(info['data']):\n for col, value in enumerate(sub_data):\n setOutCell(outSheet, col, row, value)\n\n outbook.save(outfile)\n'''\ndef multi_sheet(infos, filename):\n book = xlwt.Workbook()\n\n for info in infos:\n sheet = book.add_sheet(info['sheetname'])\n\n info['data'] = [ [unicode(val, 'utf-8') if isinstance(val, basestring) else val for val in row] for row in info['data']]\n\n for row, sub_data in enumerate(info['data']):\n for col, value in enumerate(sub_data):\n sheet.write(row, col, value)\n\n book.save(filename)\n'''\n\n","sub_path":"python/116_cronscript/lib/mkexcel2.py","file_name":"mkexcel2.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"55539931","text":"import pandas as pd\nimport pymc3 as pm\nfrom theano import scan, shared\nimport theano.tensor as tt\n\n\ndef build_model(X, treatment_start, treatment_observations):\n time_seen = pd.to_datetime(treatment_start) + pd.DateOffset(treatment_observations - 1)\n y = shared(X[:time_seen].values)\n y_switch = shared(X[:time_seen].index < treatment_start)\n with pm.Model() as i1ma1:\n σ = pm.HalfCauchy('σ', beta=2.)\n θ = pm.Normal('θ', 0., sd=2.)\n β = pm.Normal('β', 0., sd=2.)\n\n y_adj = tt.switch(y_switch, y, y - tt.dot(y, β))\n\n # ARIMA (0, 1, 1)\n # ---------------\n # (1 - B) y[t] = (1 - θB) ε[t]\n # y[t] - y[t-1] = ε[t] - θ * ε[t-1]\n # ε[t] = y[t] - y[t-1] - θ * ε[t-1]\n def calc_next(y_lag1, y_lag0, ε, θ):\n return y_lag0 - y_lag1 - θ * ε\n\n # Initial noise guess -- let's just seed with 0\n ε0 = tt.zeros_like(y_adj)\n\n ε, _ = scan(fn=calc_next,\n sequences=dict(input=y_adj, taps=[-1, 0]),\n outputs_info=[ε0],\n non_sequences=[θ])\n\n pm.Potential('like', pm.Normal.dist(0, sd=σ).logp(ε))\n return i1ma1\n","sub_path":"utils/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"522401192","text":"# -*- coding: utf-8 -*-\r\n\r\nimport scrapy\r\nimport sys\r\nimport re\r\nsys.path.append('..')\r\nfrom items import Player\r\nfrom soccerspider import SoccerSpider\r\nfrom CurrentRosterYear import get_current_roster_year\r\nfrom LeagueDictionary import get_college_from_url, check_league\r\nfrom TableSpider import TableSpider\r\n\r\nclass NewRosterDataTableDukeSpider(scrapy.Spider):\r\n\r\n \"\"\"\r\n Spider for websites formatted like Duke's and Holy Cross's page. Only for current roster year\r\n \"\"\"\r\n name = 'newRosterDataTableDukeSpider'\r\n\r\n current_roster_year = get_current_roster_year() #i.e 2018-2019\r\n\r\n custom_settings = {\r\n\r\n 'ITEM_PIPELINES':{\r\n 'SoccerScrape.pipelines.IncomingPlayerPipeline': 300,\r\n }\r\n }\r\n\r\n start_urls = [\r\n 'http://www.goduke.com/SportSelect.dbml?SPID=1833&SPSID=22446&DB_OEM_ID=4200',\r\n 'https://goholycross.com/SportSelect.dbml?DB_OEM_ID=33100&SPID=174208&SPSID=1020214'\r\n ]\r\n\r\n allowed_domains = [\r\n 'www.goduke.com',\r\n 'goholycross.com'\r\n ]\r\n\r\n INDEX = { #maps the school to where the attributes are in the HTMl
tags\r\n 'www.goduke' :{'NUMBER': 1 ,'PLAYER_POSITION': 3, 'ACADEMIC_YEAR': 6, 'HEIGHT': 4, 'WEIGHT': 5 ,'LOCATION': 7},\r\n 'goholycross' :{'NUMBER': 1 ,'PLAYER_POSITION': 3, 'ACADEMIC_YEAR': 6, 'HEIGHT': 4, 'WEIGHT': 5 , 'LOCATION': 7}\r\n }\r\n\r\n def start_requests(self):\r\n \"\"\"\r\n Starts the http request\r\n \"\"\"\r\n for u in self.start_urls:\r\n try:\r\n yield scrapy.Request(u, callback=self.parse_list,\r\n errback=SoccerSpider.errback_httpbin, dont_filter=True)\r\n except ValueError:\r\n print(\"ValueError\")\r\n continue\r\n\r\n\r\n def parse_list(self, response):\r\n \"\"\"\r\n parses data in a table format similar to American University's\r\n \"\"\"\r\n self.logger.debug('Got successful response from {}'.format(response.url))\r\n players_table_view = '//*[@id=\"roster-list-table\"]/tbody/tr'\r\n players = response.xpath(players_table_view)\r\n school_url = response.url[response.url.index('/')+2:response.url.index('.com')] #domain for school\r\n\r\n roster_year = (response.xpath('//*[@id=\"roster-page\"]/h1/text()')\r\n .extract_first()\r\n .split(' ')[-2]\r\n .split('-')[1]\r\n .strip())\r\n\r\n for player in players:\r\n #extracting data from table\r\n playerItem = Player()\r\n player_name = player.xpath(\".//td[2]/a/text()\").extract_first().strip().split() #array [fn, ln]\r\n\r\n if(len(player_name) == 0):\r\n continue #skipping header row\r\n\r\n player_first_name = player_name[0].strip()\r\n player_last_name = \" \".join(player_name[1:]).strip()\r\n\r\n player_position = player.xpath('.//td['+ self.reference_index(school_url, 'PLAYER_POSITION') + ']/text()').extract_first().strip() #'position'\r\n\r\n player_class_year = player.xpath('.//td['+ self.reference_index(school_url, 'ACADEMIC_YEAR') + ']/text()').extract()[1].strip()\r\n\r\n player_height = player.xpath('.//td['+ self.reference_index(school_url, 'HEIGHT') + ']/text()').extract() #array['feet-inches']\r\n\r\n number = player.xpath('.//td[' + self.reference_index(school_url, 'NUMBER') + ']/text()').extract_first().strip()\r\n\r\n weight = player.xpath('.//td[' + self.reference_index(school_url, 'WEIGHT') + ']/text()').extract_first().strip()\r\n\r\n if(len(player_height) == 0):\r\n player_height = 'NA'\r\n else:\r\n player_height = player_height[0].strip()\r\n\r\n player_location = player.xpath('.//td['+ self.reference_index(school_url, 'LOCATION') + ']/text()').extract_first().strip()\r\n\r\n #Item Processing\r\n playerItem['previousSchool'] = 'NA'\r\n self.process_player_location(playerItem, player_location)\r\n playerItem['rosterYear'] = roster_year\r\n playerItem['college'] = get_college_from_url(urlDomain=response.url[response.url.index('/')\r\n + 2:response.url.index('.com')+4])\r\n\r\n playerItem['collegeLeague'] = check_league(urlDomain=response.url[response.url.index('/')\r\n + 2:response.url.index('.com')+4])\r\n\r\n SoccerSpider.process_other_attribute(playerItem, player_first_name, 'firstName')\r\n SoccerSpider.process_other_attribute(playerItem, player_last_name, 'lastName')\r\n SoccerSpider.process_other_attribute(playerItem, player_position, 'position')\r\n SoccerSpider.process_other_attribute(playerItem, player_class_year, 'classYear')\r\n TableSpider.process_other_attribute(playerItem, player_height, 'height')\r\n SoccerSpider.process_other_attribute(playerItem, number, 'number')\r\n SoccerSpider.process_other_attribute(playerItem, weight, 'weight')\r\n\r\n href = player.xpath('.//td[2]/a/@href').extract_first()\r\n link = response.url[0:response.url.index('.com')+4] + href\r\n\r\n playerItem['profileLink'] = link\r\n\r\n yield playerItem\r\n\r\n\r\n def process_player_location(self, playerItem, player_location):\r\n \"\"\"\r\n method process_player_location processes attributes regarding high school, hometown, and home state\r\n type player_location: string formatted\r\n \"\"\"\r\n if not player_location:\r\n playerItem['homeTown'] = 'NA'\r\n playerItem['state_or_country'] = 'NA'\r\n playerItem['highSchool'] = 'NA'\r\n return\r\n\r\n split_location = player_location.split('(')\r\n homeTown = split_location[0].strip().split(',') #['hometown', 'state']\r\n playerItem['homeTown'] = re.sub(' +', ' ', homeTown[0].strip())\r\n playerItem['state_or_country'] = re.sub(' +', ' ', homeTown[1].strip())\r\n playerItem['highSchool'] = 'NA'\r\n\r\n if len(split_location) > 1:\r\n highSchool = split_location[1].strip()\r\n playerItem['highSchool'] = re.sub('[)]', '', highSchool)\r\n\r\n @classmethod\r\n def reference_index(self, school_url, attribute):\r\n \"\"\" Method reference_index looks up the proper index value in
tages for the data needed\"\"\"\r\n return str(NewRosterDataTableDukeSpider.INDEX[school_url][attribute])\r\n\r\n\r\n","sub_path":"scripts/SoccerScrape/spiders/NewRosterDataTableViewDukeSpider.py","file_name":"NewRosterDataTableViewDukeSpider.py","file_ext":"py","file_size_in_byte":6755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"617989488","text":"\r\nfrom enemy import*\r\nfrom info import*\r\nfrom images import images\r\nfrom keybinding import keybinding\r\nfrom maps import*\r\nfrom intro import*\r\nfrom item import*\r\nimport turtle\r\nimport math\r\nimport random\r\nimport time\r\nimport winsound\r\n\r\nfor image in images:\r\n turtle.register_shape(image)\r\n\r\n#intro screen\r\n#------------------------------\r\nintro()\r\n\r\n#main screen \r\n#------------------------------\r\n\r\nwn = turtle.Screen()\r\nwn.bgcolor(\"black\")\r\nwn.title(\"7 Dungeons Deep (7DD)\")\r\nwn.setup(1900,930)\r\nwn.bgpic(\".\\\\art\\\\background.gif\")\r\nwn.tracer(0)\r\n\r\nclass Player(turtle.Turtle):\r\n def __init__(self):\r\n turtle.Turtle.__init__(self)\r\n self.shape(\".\\\\art\\\\heroright.gif\")\r\n self.penup()\r\n self.speed()\r\n self.fd(0)\r\n self.right=1\r\n self.left=0\r\n self.up=0\r\n self.down=0\r\n\r\n def headright(self):\r\n\r\n if self.right==1:\r\n pass\r\n\r\n if self.down==1:\r\n self.rt(270)\r\n self.down=0\r\n self.right=1 \r\n \r\n if self.left==1:\r\n self.rt(180)\r\n self.left=0\r\n self.right=1\r\n\r\n if self.up==1:\r\n self.rt(90)\r\n self.up=0\r\n self.right=1\r\n\r\n self.shape(\".\\\\art\\\\heroright.gif\")\r\n missile.shape(\".\\\\art\\\\arrowright.gif\")\r\n missile.fire()\r\n\r\n\r\n def headdown(self):\r\n\r\n if self.down==1:\r\n pass\r\n\r\n if self.left==1:\r\n \r\n self.rt(270)\r\n self.left=0\r\n self.down=1\r\n\r\n\r\n if self.up==1:\r\n \r\n self.rt(180)\r\n self.up=0\r\n self.down=1\r\n \r\n if self.right==1:\r\n \r\n self.rt(90)\r\n self.right=0\r\n self.down=1\r\n\r\n self.shape(\".\\\\art\\\\herodown.gif\")\r\n missile.shape(\".\\\\art\\\\arrowdown.gif\")\r\n missile.fire()\r\n\r\n def headleft(self):\r\n\r\n if self.left==1:\r\n pass\r\n\r\n if self.up==1:\r\n \r\n self.rt(270)\r\n self.up=0\r\n self.left=1\r\n\r\n if self.right==1:\r\n \r\n self.rt(180)\r\n self.right=0\r\n self.left=1\r\n\r\n if self.down==1:\r\n \r\n self.rt(90)\r\n self.down=0\r\n self.left=1\r\n\r\n self.shape(\".\\\\art\\\\heroleft.gif\")\r\n missile.shape(\".\\\\art\\\\arrowleft.gif\")\r\n missile.fire()\r\n \r\n def headup(self):\r\n \r\n if self.up==1:\r\n pass\r\n\r\n if self.right==1:\r\n \r\n self.rt(270)\r\n self.right=0\r\n self.up=1\r\n\r\n if self.down==1:\r\n \r\n self.rt(180)\r\n self.down=0\r\n self.up=1\r\n\r\n if self.left==1:\r\n \r\n self.rt(90)\r\n self.left=0\r\n self.up=1\r\n \r\n self.shape(\".\\\\art\\\\heroup.gif\")\r\n missile.shape(\".\\\\art\\\\arrowup.gif\")\r\n missile.fire()\r\n \r\n\r\n def go_up(self):\r\n\r\n if self.up==1:\r\n pass\r\n\r\n if self.right==1:\r\n \r\n self.rt(270)\r\n self.right=0\r\n self.up=1\r\n\r\n if self.down==1:\r\n \r\n self.rt(180)\r\n self.down=0\r\n self.up=1\r\n\r\n if self.left==1:\r\n \r\n self.rt(90)\r\n self.left=0\r\n self.up=1\r\n\r\n move_to_x = self.xcor()\r\n move_to_y = self.ycor()+24\r\n\r\n self.shape(\".\\\\art\\\\heroup.gif\")\r\n\r\n \r\n if (move_to_x, move_to_y) not in walls:\r\n self.goto(move_to_x, move_to_y)\r\n \r\n\r\n def go_down(self):\r\n\r\n if self.down==1:\r\n pass\r\n\r\n if self.left==1:\r\n \r\n self.rt(270)\r\n self.left=0\r\n self.down=1\r\n\r\n\r\n if self.up==1:\r\n \r\n self.rt(180)\r\n self.up=0\r\n self.down=1\r\n \r\n if self.right==1:\r\n \r\n self.rt(90)\r\n self.right=0\r\n self.down=1\r\n \r\n move_to_x = self.xcor()\r\n move_to_y = self.ycor()-24\r\n self.shape(\".\\\\art\\\\herodown.gif\")\r\n \r\n if (move_to_x, move_to_y) not in walls and npcs:\r\n self.goto(move_to_x, move_to_y)\r\n \r\n \r\n def go_left(self):\r\n\r\n if self.left==1:\r\n pass\r\n\r\n if self.up==1:\r\n \r\n self.rt(270)\r\n self.up=0\r\n self.left=1\r\n\r\n if self.right==1:\r\n \r\n self.rt(180)\r\n self.right=0\r\n self.left=1\r\n\r\n if self.down==1:\r\n \r\n self.rt(90)\r\n self.down=0\r\n self.left=1\r\n \r\n move_to_x = self.xcor()-24\r\n move_to_y = self.ycor()\r\n self.shape(\".\\\\art\\\\heroleft.gif\")\r\n \r\n if (move_to_x, move_to_y) not in walls :\r\n self.goto(move_to_x, move_to_y)\r\n \r\n def go_right(self):\r\n\r\n if self.right==1:\r\n pass\r\n\r\n if self.down==1:\r\n self.rt(270)\r\n self.down=0\r\n self.right=1 \r\n \r\n if self.left==1:\r\n self.rt(180)\r\n self.left=0\r\n self.right=1\r\n\r\n if self.up==1:\r\n self.rt(90)\r\n self.up=0\r\n self.right=1\r\n \r\n move_to_x = player.xcor()+24\r\n move_to_y = player.ycor()\r\n\r\n\r\n if (move_to_x, move_to_y) not in walls:\r\n self.goto(move_to_x, move_to_y)\r\n \r\n self.shape(\".\\\\art\\\\heroright.gif\")\r\n\r\n \r\n def drink(self):\r\n \r\n if info.potion>0 and info.hp is not info.fullhp : \r\n info.potion-=1\r\n info.show_healthpotion()\r\n\r\n if info.hp < info.fullhp-300:\r\n info.hp+=300\r\n info.show_health()\r\n else:\r\n info.hp=info.fullhp\r\n info.show_health()\r\n else:\r\n pass\r\n \r\n def fireball(self):\r\n if info.fire_scroll>0:\r\n info.fire_scroll-=1\r\n info.show_fire_scroll()\r\n missile2.fire()\r\n \r\n else:\r\n pass\r\n \r\n\r\n def is_collision(self,other):\r\n a = self.xcor()- other.xcor()\r\n b = self.ycor()- other.ycor()\r\n distance = math.sqrt ((a ** 2)+(b ** 2) )\r\n\r\n if distance < 10:\r\n return True\r\n else:\r\n return False\r\n\r\n def is_collision2(self,other):\r\n a = self.xcor()- other.xcor()\r\n b = self.ycor()- other.ycor()\r\n distance = math.sqrt ((a ** 2)+(b ** 2) )\r\n\r\n if distance < 50:\r\n return True\r\n else:\r\n return False\r\n\r\n def destroy(self):\r\n self.goto(500,500)\r\n self.hideturtle()\r\n\r\n\r\nclass Missile(turtle.Turtle):\r\n def __init__(self,startx, starty):\r\n turtle.Turtle.__init__(self)\r\n self.speed = 3\r\n self.fd(10)\r\n self.penup()\r\n self.color(\"yellow\")\r\n self.status = \"ready\"\r\n self.goto(-1000, 1000)\r\n\r\n def is_collision(self,other):\r\n a = self.xcor()- other.xcor()\r\n b = self.ycor()- other.ycor()\r\n distance = math.sqrt ((a ** 2)+(b ** 2) )\r\n\r\n if distance < 22: # LESS THAN 25 OR YOU ATTACK DIAGANAL \r\n return True\r\n else:\r\n return False\r\n\r\n def is_far(self,other):\r\n a = self.xcor()- other.xcor()\r\n b = self.ycor()- other.ycor()\r\n distance = math.sqrt ((a ** 2)+(b ** 2) )\r\n\r\n if distance >25:\r\n return True\r\n else:\r\n return False\r\n \r\n\r\n def fire(self):\r\n if self.status == \"ready\":\r\n self.goto(player.xcor(), player.ycor())\r\n self.setheading(player.heading())\r\n self.status = \"firing\"\r\n if lives != 3:\r\n winsound.PlaySound(\".\\\\sound\\\\swing.wav\", winsound.SND_ASYNC) \r\n \r\n def move(self):\r\n \r\n if self.status == \"ready\":\r\n self.goto(-2456, 3422)\r\n \r\n \r\n if self.status == \"firing\":\r\n self.fd(self.speed) \r\n \r\n #Border check\r\n\r\n\r\n if missile.is_far(player):\r\n self.setheading(player.heading())\r\n self.status = \"ready\" \r\n \r\n \r\n if self.xcor() < -400 or self.xcor() > 400 or \\\r\n self.ycor()< -400 or self.ycor()> 400:\r\n self.setheading(player.heading())\r\n self.status = \"ready\"\r\n\r\n if (self.xcor(), self.ycor()) in walls: \r\n self.setheading(player.heading())\r\n self.status = \"ready\"\r\n \r\nclass Missile2(turtle.Turtle):\r\n def __init__(self,startx, starty):\r\n turtle.Turtle.__init__(self)\r\n self.shape(\".\\\\art\\\\fire.gif\")\r\n self.speed = 3\r\n self.fd(10)\r\n self.damage=400\r\n self.penup()\r\n self.color(\"yellow\")\r\n self.status = \"ready\"\r\n self.goto(-1000, 1000)\r\n\r\n def is_collision(self,other):\r\n a = self.xcor()- other.xcor()\r\n b = self.ycor()- other.ycor()\r\n distance = math.sqrt ((a ** 2)+(b ** 2) )\r\n\r\n if distance < 30:\r\n return True\r\n else:\r\n return False\r\n\r\n def is_far(self,other):\r\n a = self.xcor()- other.xcor()\r\n b = self.ycor()- other.ycor()\r\n distance = math.sqrt ((a ** 2)+(b ** 2) )\r\n\r\n if distance >125:\r\n return True\r\n else:\r\n return False\r\n \r\n\r\n def fire(self):\r\n if self.status == \"ready\":\r\n self.goto(player.xcor(), player.ycor())\r\n self.setheading(player.heading())\r\n self.status = \"firing\"\r\n if lives != 3:\r\n winsound.PlaySound(\".\\\\sound\\\\fireball.wav\", winsound.SND_ASYNC)\r\n\r\n \r\n def move(self):\r\n \r\n if self.status == \"ready\":\r\n self.goto(-2456, 3422)\r\n \r\n \r\n if self.status == \"firing\":\r\n self.fd(self.speed) \r\n \r\n #Border check\r\n\r\n\r\n if missile2.is_far(player):\r\n self.setheading(player.heading())\r\n self.status = \"ready\" \r\n \r\n \r\n if self.xcor() < -400 or self.xcor() > 400 or \\\r\n self.ycor()< -400 or self.ycor()> 400:\r\n self.setheading(player.heading())\r\n self.status = \"ready\"\r\n\r\n if (self.xcor(), self.ycor()) in walls: \r\n self.setheading(player.heading())\r\n self.status = \"ready\"\r\n\r\n\r\nparticles = []\r\n\r\nfor i in range(15):\r\n particles.append(Particle(\"circle\", \"red\", 0, 0))\r\n \r\nmission=0\r\nlives=0\r\nquests2=[]\r\nquests=[]\r\nquest_items=[]\r\narmourupgrade=0\r\nweaponupgrade=0\r\ncrowns=[]\r\nenemies2 =[]\r\nenemies =[] \r\ncoins =[]\r\ndoors =[]\r\nhealings=[]\r\nfake_walls=[]\r\nnpcs=[]\r\nfirescrolls=[]\r\nswords=[]\r\narmours=[]\r\nwalls=[]\r\n\r\nlevels = [\"\"]\r\n\r\nlevels.append(level_1)\r\nlevels.append(level_2)\r\nlevels.append(level_3)\r\nlevels.append(level_4)\r\nlevels.append(level_5)\r\nlevels.append(level_6)\r\nlevels.append(level_7)\r\nlevels.append(level_8)\r\n\r\n#row are y ( up/down) column are x (left and right )\r\n# \r\n\r\ndef setup_maze(level):\r\n for y in range (len(level)): #tell how many rows there is \r\n for x in range(len(level[y])): # acquire every x of the y row\r\n #Get the character at each x,y coordinate\r\n #NOTE the order of Y AND X in the next line\r\n character = level [y][x]\r\n #Calculate the screen x,y coordinates. Furtherest left upper corner is (0,0)\r\n screen_x = -350 + (x*24)\r\n screen_y = 288 - (y*24)\r\n\r\n #check if it is an x represent a wall\r\n if character == \"X\": \r\n pen.goto(screen_x, screen_y)\r\n pen.shape(\".\\\\art\\\\wall.gif\")\r\n pen.stamp()\r\n walls.append((screen_x,screen_y))\r\n\r\n if character == \"T\": \r\n pen.goto(screen_x, screen_y)\r\n pen.shape(\".\\\\art\\\\torch.gif\")\r\n pen.stamp()\r\n walls.append((screen_x,screen_y))\r\n\r\n if character == \"Y\": \r\n pen.goto(screen_x, screen_y)\r\n pen.shape(\".\\\\art\\\\skeleton.gif\")\r\n pen.stamp()\r\n walls.append((screen_x,screen_y))\r\n\r\n if character == \"G\": \r\n pen.goto(screen_x, screen_y)\r\n pen.shape(\".\\\\art\\\\tree.gif\")\r\n pen.stamp()\r\n walls.append((screen_x,screen_y))\r\n\r\n if character == \"R\": \r\n pen.goto(screen_x, screen_y)\r\n pen.shape(\".\\\\art\\\\rock.gif\")\r\n pen.stamp()\r\n walls.append((screen_x,screen_y))\r\n\r\n if character == \"V\": \r\n pen.goto(screen_x, screen_y)\r\n pen.shape(\".\\\\art\\\\cage.gif\")\r\n pen.stamp()\r\n walls.append((screen_x,screen_y))\r\n\r\n\r\n\r\n\r\n \r\n if character == \"P\": # p= player \r\n player.goto(screen_x, screen_y)\r\n\r\n if character == \"C\":\r\n coins.append(Coin(screen_x, screen_y))\r\n \r\n if character ==\"E\":\r\n enemies.append(Enemy(screen_x, screen_y,player,walls))\r\n\r\n if character ==\"D\":\r\n doors.append(Door(screen_x, screen_y))\r\n\r\n if character ==\"M\":\r\n crowns.append(Crown(screen_x, screen_y))\r\n\r\n if character ==\"H\":\r\n healings.append(Healing(screen_x, screen_y))\r\n\r\n if character ==\"F\":\r\n firescrolls.append(Firescroll(screen_x, screen_y))\r\n\r\n if character ==\"A\":\r\n armours.append(Armour(screen_x, screen_y))\r\n\r\n if character ==\"S\":\r\n swords.append(Sword(screen_x, screen_y))\r\n\r\n if character ==\"Z\":\r\n enemies.append(Enemy2(screen_x, screen_y,player,walls))\r\n\r\n\r\n if character ==\"N\":\r\n npcs.append(Npc(screen_x, screen_y))\r\n\r\n if character ==\"Q\":\r\n quests.append(Quest(screen_x, screen_y))\r\n\r\n if character ==\"B\":\r\n quest_items.append(Quest_item(screen_x, screen_y))\r\n\r\n if character ==\"I\":\r\n fake_walls.append(Fake_wall(screen_x, screen_y))\r\n\r\n if character ==\"J\":\r\n enemies.append(Enemy3(screen_x, screen_y,player,walls))\r\n\r\n if character ==\"L\":\r\n enemies.append(Enemy4(screen_x, screen_y,player,walls))\r\n\r\n if character ==\"K\":\r\n quests2.append(Quest2(screen_x, screen_y))\r\n \r\n \r\npen=Pen()\r\nplayer= Player()\r\nmissile = Missile(0, 0)\r\nmissile2 = Missile2(0, 0)\r\n\r\n\r\nsetup_maze(levels[1])\r\nmaze=(\"level1\")\r\n\r\ninfo=Info()\r\ngame=Info()\r\ngame.draw_border()\r\ngame.draw_border2()\r\ngame.draw_border3()\r\ngame.draw_border4()\r\ngame.show_rules()\r\ngame.show_gold()\r\ngame.show_armour()\r\ngame.show_weapon()\r\ninfo.show_health()\r\ninfo.show_strength()\r\ninfo.show_level()\r\ninfo.show_healthpotion()\r\ninfo.show_fire_scroll()\r\ninfo.show_exp()\r\ninfo.show_defense()\r\n\r\n\r\n#keyboard binding\r\n\r\nkeybinding(player)\r\n\r\nfor enemy in enemies:\r\n turtle.ontimer(enemy.move(walls,player),t=250)\r\n\r\n \r\n\r\n#bob=0\r\n\r\nwhile True:\r\n \r\n # bob+=1\r\n # while bob ==300:\r\n\r\n # for enemy in enemies:\r\n # turtle.ontimer(enemy.move(walls,player),t=100)\r\n # bob=0\r\n \r\n \r\n missile.move()\r\n missile2.move()\r\n\r\n for particle in particles:\r\n particle.move()\r\n \r\n for armour in armours:\r\n\r\n if player.is_collision(armour):\r\n\r\n armour.destroy()\r\n\r\n if armourupgrade==1:\r\n info.armourstats+=4\r\n game.armour=(\"Mythril Plate\")\r\n game.show_armour()\r\n info.show_defense()\r\n armourupgrade+=1\r\n winsound.PlaySound(\".\\\\sound\\\\armour.wav\", winsound.SND_ASYNC)\r\n\r\n if armourupgrade==0:\r\n info.armourstats+=6\r\n game.armour=(\"Steel Plate\")\r\n game.show_armour()\r\n info.show_defense()\r\n armourupgrade+=1\r\n winsound.PlaySound(\".\\\\sound\\\\armour.wav\", winsound.SND_ASYNC)\r\n\r\n for npc in npcs:\r\n\r\n if player.is_collision(npc): \r\n game.intro() \r\n Npc.destroy(npc)\r\n \r\n for quest in quests:\r\n\r\n if player.is_collision2(quest):\r\n if mission ==0:\r\n game.start()\r\n \r\n if mission ==1:\r\n game.end()\r\n info.exp+=quest.exp\r\n info.show_exp()\r\n Quest.destroy(quest)\r\n\r\n\r\n for quest2 in quests2:\r\n\r\n if player.is_collision2(quest2):\r\n if info.boss ==0:\r\n game.start2()\r\n \r\n if info.boss ==1:\r\n game.end2()\r\n info.exp+=200\r\n info.show_exp()\r\n Quest.destroy(quest2)\r\n\r\n for quest_item in quest_items:\r\n if player.is_collision(quest_item):\r\n mission=1\r\n Quest_item.destroy(quest_item)\r\n winsound.PlaySound(\".\\\\sound\\\\key.wav\", winsound.SND_ASYNC)\r\n \r\n\r\n for sword in swords:\r\n\r\n if player.is_collision(sword):\r\n\r\n sword.destroy()\r\n\r\n if weaponupgrade==1:\r\n info.weaponstats+=4\r\n game.weapon=(\"Mythril Sword\")\r\n game.show_weapon()\r\n info.show_strength()\r\n weaponupgrade+=1\r\n winsound.PlaySound(\".\\\\sound\\\\sword.wav\", winsound.SND_ASYNC)\r\n\r\n if weaponupgrade==0:\r\n info.weaponstats+=6\r\n game.weapon=(\"Steel Sword\")\r\n game.show_weapon()\r\n info.show_strength()\r\n weaponupgrade+=1\r\n winsound.PlaySound(\".\\\\sound\\\\sword.wav\", winsound.SND_ASYNC)\r\n\r\n for firescroll in firescrolls:\r\n\r\n if player.is_collision(firescroll):\r\n\r\n firescroll.destroy()\r\n info.fire_scroll+=1\r\n info.show_fire_scroll()\r\n winsound.PlaySound(\".\\\\sound\\\\scroll.wav\", winsound.SND_ASYNC)\r\n\r\n\r\n for healing in healings:\r\n\r\n if player.is_collision(healing):\r\n\r\n healing.destroy()\r\n info.potion+=1\r\n info.show_healthpotion()\r\n winsound.PlaySound(\".\\\\sound\\\\potion.wav\", winsound.SND_ASYNC)\r\n \r\n\r\n for crown in crowns:\r\n \r\n if player.is_collision(crown):\r\n \r\n #winsound.PlaySound(\".\\\\sound\\\\victory.wav\",0)\r\n player.destroy()\r\n crown.destroy()\r\n crowns.remove(crown)\r\n lives=3\r\n game.win()\r\n \r\n \r\n for enemy in enemies:\r\n if missile.is_collision(enemy):\r\n enemy.hp -= (info.strength+info.weaponstats)\r\n missile.status = \"ready\"\r\n winsound.PlaySound(\".\\\\sound\\\\orkdeath.wav\", winsound.SND_ASYNC)\r\n\r\n if missile2.is_collision(enemy):\r\n enemy.hp -= missile2.damage\r\n missile2.status = \"ready\"\r\n winsound.PlaySound(\".\\\\sound\\\\orkdeath.wav\", winsound.SND_ASYNC)\r\n\r\n\r\n if enemy.hp<=0 and enemy.alive==True:\r\n enemy.alive=False \r\n Enemy.destroy(enemy)\r\n missile.status = \"ready\"\r\n info.exp += enemy.exp\r\n info.boss+=enemy.boss\r\n info.kill+=1\r\n info.show_exp()\r\n winsound.PlaySound(\".\\\\sound\\\\orkdeath.wav\", winsound.SND_ASYNC)\r\n\r\n if info.exp>70 and info.level2_claimed:\r\n info.hp=1100\r\n info.fullhp=1100\r\n info.strength=20\r\n info.defense=4\r\n info.level=2\r\n info.level2_claimed = False\r\n info.show_defense()\r\n info.show_health()\r\n info.show_strength()\r\n info.show_level()\r\n winsound.PlaySound(\".\\\\sound\\\\levelup.wav\", winsound.SND_ASYNC)\r\n time.sleep(1)\r\n \r\n\r\n if info.exp>150 and info.level3_claimed:\r\n info.hp=1200\r\n info.fullhp=1200\r\n info.strength=25\r\n info.defense=8\r\n info.level=3\r\n info.level3_claimed = False\r\n info.show_defense()\r\n info.show_health()\r\n info.show_strength()\r\n info.show_level()\r\n winsound.PlaySound(\".\\\\sound\\\\levelup.wav\", winsound.SND_ASYNC)\r\n time.sleep(1)\r\n \r\n if info.exp>300 and info.level4_claimed:\r\n info.hp=1300\r\n info.fullhp=1300\r\n info.strength=30\r\n info.defense=12\r\n info.level=4\r\n info.level4_claimed = False\r\n info.show_defense()\r\n info.show_health()\r\n info.show_strength()\r\n info.show_level()\r\n winsound.PlaySound(\".\\\\sound\\\\levelup.wav\", winsound.SND_ASYNC)\r\n time.sleep(1)\r\n \r\n\r\n if info.exp>450 and info.level5_claimed:\r\n info.hp=1500\r\n info.fullhp=1500\r\n info.strength=40\r\n info.defense=20\r\n info.level=5\r\n info.level5_claimed = False\r\n info.show_defense()\r\n info.show_health()\r\n info.show_strength()\r\n info.show_level()\r\n winsound.PlaySound(\".\\\\sound\\\\levelup.wav\", winsound.SND_ASYNC)\r\n time.sleep(1)\r\n\r\n if info.exp>700 and info.level6_claimed:\r\n info.hp=1700\r\n info.fullhp=1700\r\n info.strength=60\r\n info.defense=25\r\n info.level=6\r\n info.level6_claimed = False\r\n info.show_defense()\r\n info.show_health()\r\n info.show_strength()\r\n info.show_level()\r\n winsound.PlaySound(\".\\\\sound\\\\levelup.wav\", winsound.SND_ASYNC)\r\n time.sleep(1)\r\n\r\n if info.exp>950 and info.level7_claimed:\r\n info.hp=2000\r\n info.fullhp=2000\r\n info.strength=80\r\n info.defense=30\r\n info.level=7\r\n info.level7_claimed = False\r\n info.show_defense()\r\n info.show_health()\r\n info.show_strength()\r\n info.show_level()\r\n winsound.PlaySound(\".\\\\sound\\\\levelup.wav\", winsound.SND_ASYNC) \r\n time.sleep(1)\r\n\r\n if info.exp>1400 and info.level8_claimed:\r\n info.hp=2200\r\n info.fullhp=2200\r\n info.strength=100\r\n info.defense=50\r\n info.level=8\r\n info.level8_claimed = False\r\n info.show_defense()\r\n info.show_health()\r\n info.show_strength()\r\n info.show_level()\r\n winsound.PlaySound(\".\\\\sound\\\\levelup.wav\", winsound.SND_ASYNC) \r\n time.sleep(1)\r\n \r\n for coin in coins:\r\n if player.is_collision(coin):\r\n game.gold += coin.gold\r\n game.show_gold()\r\n #print(\"Player Gold: {}\".format (game.gold))\r\n coin.destroy()\r\n coins.remove(coin)\r\n winsound.PlaySound(\".\\\\sound\\\\coin.wav\", winsound.SND_ASYNC)\r\n\r\n for enemy in enemies:\r\n if player.is_collision(enemy):\r\n attack=enemy.damage\r\n reduce_damage=attack-(info.defense+game.armourstats)\r\n if reduce_damage <0 :\r\n reduce_damage=0\r\n\r\n info.hp-=reduce_damage\r\n info.show_health()\r\n\r\n for particle in particles:\r\n particle.explode(player.xcor(), player.ycor())\r\n\r\n for door in doors:\r\n if player.is_collision(door):\r\n walls.clear()\r\n pen.clear()\r\n wn.bgpic(\".\\\\art\\\\black.gif\")\r\n for enemy in enemies:\r\n Enemy.destroy(enemy)\r\n for coin in coins:\r\n Coin.destroy(coin)\r\n for door in doors:\r\n Door.destroy(door)\r\n for armour in armours:\r\n Armour.destroy(armour)\r\n for sword in swords:\r\n Sword.destroy(sword)\r\n for healing in healings:\r\n Healing.destroy(healing)\r\n for firescroll in firescrolls:\r\n Firescroll.destroy(firescroll)\r\n for npc in npcs:\r\n Npc.destroy(npc)\r\n for quest in quests:\r\n Quest.destroy(quest)\r\n for quest_item in quest_items:\r\n Quest_item.destroy(quest_item)\r\n for fake_wall in fake_walls:\r\n Fake_wall.destroy(fake_wall)\r\n for quest2 in quests2:\r\n Quest2.destroy(quest2)\r\n \r\n winsound.PlaySound(\".\\\\sound\\\\unlock.wav\", winsound.SND_ASYNC)\r\n \r\n if maze==(\"level1\"):\r\n \r\n setup_maze(levels[2])\r\n maze=(\"level2\")\r\n \r\n \r\n elif maze ==(\"level2\"):\r\n setup_maze(levels[3])\r\n maze=(\"level3\")\r\n \r\n \r\n elif maze==(\"level3\"):\r\n setup_maze(levels[4])\r\n maze=(\"level4\")\r\n \r\n\r\n elif maze==(\"level4\"):\r\n setup_maze(levels[5])\r\n maze=(\"level5\")\r\n\r\n elif maze==(\"level5\"):\r\n setup_maze(levels[6])\r\n maze=(\"level6\")\r\n\r\n elif maze==(\"level6\"):\r\n setup_maze(levels[7])\r\n maze=(\"level7\")\r\n\r\n elif maze==(\"level7\"):\r\n setup_maze(levels[8])\r\n maze=(\"level8\") \r\n \r\n else:\r\n pass\r\n \r\n for enemy in enemies:\r\n turtle.ontimer(enemy.move(walls,player),t=250)\r\n \r\n if info.hp<=0:\r\n game.dead()\r\n player.destroy()\r\n winsound.PlaySound(\".\\\\sound\\\\death.wav\", winsound.SND_ASYNC)\r\n time.sleep(2)\r\n info.show_health()\r\n break\r\n \r\n wn.update()\r\n","sub_path":"misc/enemy game.py","file_name":"enemy game.py","file_ext":"py","file_size_in_byte":26797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"65714848","text":"from xml.dom import minidom\nfrom google.appengine.api import memcache, urlfetch\n\nclass api(object):\n '''\n classdocs\n '''\n\n def readType(self, data):\n buyOrderPrice = data.getElementsByTagName('buy')[0].getElementsByTagName('max')[0].firstChild.data\n sellOrderPrice = data.getElementsByTagName('sell')[0].getElementsByTagName('min')[0].firstChild.data\n memcache.Client().set('Price/%s' % (data.getAttribute('id')),[float(buyOrderPrice), float(sellOrderPrice)],time=3600)\n #print data.getAttribute('id') + \": \" + buyOrderPrice, sellOrderPrice\n \n def httpGetPricesXML(self,itemIDs):\n params = ''\n cache = memcache.Client()\n for item in itemIDs:\n if cache.get('Price/%s' % item) is None:\n params += 'typeid=%s&' % (item)\n if params != '':\n params += 'usesystem=30000142' #Jita system\n response = urlfetch.fetch(url='http://api.eve-central.com/api/marketstat?%s' % (params),method=urlfetch.GET,deadline=60)\n if response.status_code == 200:\n result = response.content\n else:\n raise ValueError('HTTP Request failed with status code %s' % response.status_code)\n else:\n result = None\n return result\n \n def getPrice(self, itemIDs):\n if type(itemIDs) is str:\n items = [int(itemIDs)]\n elif type(itemIDs) is long:\n items = [int(itemIDs)]\n elif type(itemIDs) is int:\n items = [itemIDs]\n elif type(itemIDs) is list:\n items = itemIDs\n \n items = self.unique(items)\n xmlresponse = self.httpGetPricesXML(items)\n if xmlresponse is not None: \n doc = minidom.parseString(xmlresponse)\n if doc.documentElement.tagName == 'evec_api':\n for each in doc.getElementsByTagName(\"type\"):\n self.readType(each)\n \n def unique(self, seq):\n seen = set()\n seen_add = seen.add\n return [ x for x in seq if x not in seen and not seen_add(x)]","sub_path":"evecentralapi.py","file_name":"evecentralapi.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"6559203","text":"\nfrom flask import render_template,flash,redirect\nfrom app import app\nfrom forms import LoginForm\n\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\n\t#fake user object\n\tuser = {'nickname':'ming'}\n\n\tposts = [\n\t\t\t{\n\t\t\t\t'author':{'nickname':'John'},\n\t\t\t\t'body':'Beautiful day in AnHui'\n\t\t\t},\t\n\t\t\t{\n\t\t\t\t'author':{'nickname':'Bing'},\n\t\t\t\t'body':'The Avengers movie was so cool!'\n\t\t\t}\n\t\t]\n\treturn render_template('index.html',title='Home',user=user,posts = posts)\n\n@app.route('/login',methods=['GET','POST'])\ndef login():\n\tform = LoginForm()\n\tif form.validate_on_submit():\n\t\t#flash('Login requested for OpenID=%s,remember_me=%s '\\\n\t\t#\t\t%(form.openid.data,str(form.remember_me.data)))\n\t\t\n\t\tflash('Login requested for OpenID=%s,remember_me=%s '\\\n\t\t\t\t%(form.openid.data,str(form.remember_me.data)))\n\t\treturn redirect('/index')\n\treturn render_template('login.html',title='Sigin In',\\\n\t\t\tform = form,providers=app.config['OPENID_PROVIDERS'])\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"195720855","text":"from __future__ import unicode_literals\n\nfrom django.db import models\n\nclass Collection(models.Model):\n id = models.AutoField(db_column='Id', primary_key=True)\n name = models.CharField(db_column='Name', null=True)\n\n class Meta:\n managed = False\n db_table = 'Collection'\n\nclass WeaponModel(models.Model):\n id = models.AutoField(db_column='Id', primary_key=True)\n name = models.CharField(db_column='Name', null=True)\n\n class Meta:\n managed = False\n db_table = 'WeaponModel'\n\nclass WeaponGrade(models.Model):\n id = models.AutoField(db_column='Id', primary_key=True)\n rank = models.IntegerField(db_column='Rank', null=True)\n name = models.CharField(db_column='Name', null=True)\n\n class Meta:\n managed = False\n db_table = 'WeaponGrade'\n\nclass CollectionItem(models.Model):\n id = models.AutoField(db_column='Id', primary_key=True)\n name = models.CharField(db_column='Name', null=True)\n float_min = models.DecimalField(db_column='FloatMin', max_digits=5, decimal_places=3)\n float_max = models.DecimalField(db_column='FloatMax', max_digits=5, decimal_places=3)\n stat_trak = models.BooleanField(db_column='StatTrak')\n souvenir = models.BooleanField(db_column='Souvenir')\n factory_new = models.BooleanField(db_column='FactoryNew')\n minimal_wear = models.BooleanField(db_column='MinimalWear')\n field_tested = models.BooleanField(db_column='FieldTested')\n well_worn = models.BooleanField(db_column='WellWorn')\n battle_scarred = models.BooleanField(db_column='BattleScarred')\n collection = models.ForeignKey(Collection, db_column='Collection')\n weapon_grade = models.ForeignKey(WeaponGrade, db_column='WeaponGrade')\n weapon_model = models.ForeignKey(WeaponModel, db_column='WeaponModel')\n\n class Meta:\n managed = False\n db_table = 'CollectionItem'\n\nclass SteamMarketUrl(models.Model):\n id = models.AutoField(db_column='Id', primary_key=True)\n url = models.CharField(db_column='Url', null=True)\n market_hash_name = models.CharField(db_column='market_hash_name', null=True)\n stat_trak = models.BooleanField(db_column='StatTrak')\n souvenir = models.BooleanField(db_column='Souvenir')\n factory_new = models.BooleanField(db_column='FactoryNew')\n minimal_wear = models.BooleanField(db_column='MinimalWear')\n field_tested = models.BooleanField(db_column='FieldTested')\n well_worn = models.BooleanField(db_column='WellWorn')\n battle_scarred = models.BooleanField(db_column='BattleScarred')\n collection_item = models.ForeignKey(CollectionItem, db_column='CollectionItem')\n\n class Meta:\n managed = False\n db_table = 'SteamMarketUrl'\n\nclass MarketData(models.Model):\n id = models.AutoField(db_column='Id', primary_key=True)\n price = models.DecimalField(db_column='Price', max_digits=8, decimal_places=3)\n currency_id = models.IntegerField(db_column='CurrencyId', null=True)\n time_seen = models.DateTimeField(db_column='TimeSeen')\n market_url = models.ForeignKey(SteamMarketUrl, db_column='MarketUrl')\n\n class Meta:\n managed = False\n db_table = 'MarketData'\n\nclass Currency(models.Model):\n id = models.AutoField(db_column='Id', primary_key=True)\n name = models.CharField(db_column='Name', null=True)\n exchange_rate = models.DecimalField(db_column='ExchangeRate', max_digits=16, decimal_places=8)\n\n class Meta:\n managed = False\n db_table = 'Currency'\n\nclass LatestPrice(models.Model):\n id = models.AutoField(db_column='Id', primary_key=True)\n steam_market_url = models.ForeignKey(SteamMarketUrl, db_column='SteamMarketUrl')\n average_price = models.DecimalField(db_column='AveragePrice', max_digits=8, decimal_places=3)\n time_seen = models.DateTimeField(db_column='TimeSeen')\n\n class Meta:\n managed = False\n db_table = 'LatestPrice'\n","sub_path":"www/bin/csgoskin/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"148803966","text":"\"\"\"DataConvert \n\nThe DataConvert class just a service that class convert data in different format.\nIn this class we are reading DAT, STM and ecodedXmlFile\n\n\"\"\"\n\n# importing for libraries\nimport numpy\nimport pandas as pd\nfrom datetime import datetime, timedelta\nfrom xml.etree import ElementTree\nimport base64\nimport urllib2\nimport xmltodict\nfrom core.services.DatabaseConnection import *\nfrom core.persistence.CostData import *\n\nclass DataConvert: \n \"\"\"Reading DAT, STM and ecodedXmlFile file.\n\n This class convert data and reading DAT, STM and ecodedXmlFile from specific folder location\n\n \"\"\"\n\n @staticmethod\n def readSTM(lane, user_folder, n): \n \"\"\"Reading STM value from CSV and return detail of particular lane.\n Note:\n This is static method so call this function by statically\n like DataConvert.readSTM.\n Args:\n lane(str): the name of the lane.\n user_folder(str): the user_folder is folder location (location of the files)\n n(int): n is number of days\n Returns:\n context (this is combination of two values tableData and recent_cost_table_data)\n \"\"\" \n try:\n origin = lane[:4] # Origin_PR\n dest = lane[-4:] # Dest_PR\n\n #make connection with database\n con = DatabaseConnection.connectWithDB()\n\n #get query result \n input_df = CostData.queryToGetCostData(origin, dest, n, con)\n #close database connection\n con.close()\n\n input_df['PR_Lane'] = input_df['Origin_PR'] + input_df['Dest_PR']\n\n if input_df.empty:\n context = {'tableData': '', 'recent_cost_table_data': ''}\n else:\n slice2 = input_df[[\"CreateDate_EST\", 'PR_Lane', 'Carrier_Name', 'Customer_LHL']]\n sorted_array = slice2.sort([\"CreateDate_EST\"], ascending=False)\n g = sorted_array.groupby(['PR_Lane', 'Carrier_Name'])\n recent = (g['Customer_LHL'].first()).astype(float)\n # get second last record\n nth = (g.nth(1).fillna(value=0).reset_index())\n # get sum of accepted data\n countAccepted = (g['Carrier_Name'].count())\n # get top 10 records\n final = pd.DataFrame({'countAccepted': countAccepted, 'LH_COST_RECENT': recent}).fillna(\n value=0).reset_index()\n fData = []\n # sort according to the recent cost\n fData = final.sort([\"LH_COST_RECENT\"], ascending=True).head(10)\n # convert data frame to array\n nparray = numpy.array(fData)\n tableData = nparray.tolist()\n # second recent record from data frame to an array\n recent_cost = nth\n recent_cost_array = numpy.array(recent_cost)\n recent_cost_table_data = recent_cost_array.tolist()\n\n context = {'tableData': tableData, 'recent_cost_table_data': recent_cost_table_data}\n return context\n except:\n context = {'tableData': '', 'recent_cost_table_data': ''}\n return context\n\n","sub_path":"core/services/DataConvert.py","file_name":"DataConvert.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"622480001","text":"#! /usr/bin/env python\n\nfrom scipy.io import wavfile\nfrom scipy.interpolate import interp1d\nimport damage, recognize, utils, evaluate\n\nsample_rate, samples = wavfile.read('songs/hakuna_matata.wav')\n\nnewsamples = samples.copy()\ndamage.zerofill(newsamples, 0.5)\nwavfile.write('songs/zerofill_hakuna_matata.wav', sample_rate, newsamples)\n\nmatches = recognize.cheat(samples, newsamples, false_negatives=0.01)\nvalidx, validy = utils.tovalidxy(newsamples, matches)\nf = interp1d(validx, validy, fill_value='extrapolate')\n\ninvalidx = utils.invalidx(matches)\nfixedy = f(invalidx)\n\nutils.replace(newsamples, invalidx, fixedy)\nwavfile.write('songs/zerofill_cheat_linear_hakuna_matata.wav', sample_rate, newsamples)\n\nevaluate.study(samples, newsamples, matches=matches)\n","sub_path":"investigation/wav/linear.output.example.py","file_name":"linear.output.example.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"208803918","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nfrom utils import FileManager\nfrom os import path as os_path\nimport os, io\nimport sys\nimport shutil\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nrootDir = \"../我的对对对源文件innerclass\"\ndestDir = \"../app/src/main/java/\"\nmapping = {}\n\n\nclass item:\n def __init__(self):\n self.value = ''\n self.isSubclass = False\n\ndef traversal(basicDir):\n getMapping()\n fileList = FileManager.lsAllFile(basicDir)\n for f in fileList:\n alter(f)\n\n\ndef getMapping():\n for line in open(\"replacemap.txt\", \"r\"): # 设置文件对象并读取每一行文件\n array = line.strip().split(',', 1)\n mapping[array[0]] = array[1]\n print(\"mapping: \" + str(mapping))\n\n\ndef alter(file):\n if os_path.basename(file).startswith(\".\") :\n return\n\n new_file = file.replace(rootDir, destDir)\n b, new_file = replaceString(new_file)\n if not os.path.exists(os_path.dirname(new_file)):\n os.makedirs(os_path.dirname(new_file))\n\n if os.path.exists(new_file):\n os.remove(new_file)\n\n with io.open(file, \"r\", encoding=\"utf-8\") as f1, io.open(new_file, \"w\", encoding=\"utf-8\") as f2:\n for line in f1:\n has_replace, newline = replaceString(line)\n if has_replace:\n print(\"alterfile: \" + line + \" - > \" + newline)\n f2.write(newline)\n\n f1.close()\n f2.close()\n\n\ndef replaceString(line):\n needNotice = line.startswith(\"import \")\n has_replace = False\n old_line = line\n for old, new in mapping.items():\n if old in line:\n has_replace = True\n if needNotice and len(new.split('.')) > 1:\n new = new.rsplit('.', 1)[0]\n line = line.replace(old, new)\n\n # if has_replace:\n # print(\"replaceString: \" + old_line + \" - > \" + line)\n return has_replace, line\n\n\nif __name__ == '__main__':\n print(\"start replacement\")\n if os.path.exists(destDir):\n shutil.rmtree(destDir) # 递归删除文件夹\n else:\n os.makedirs(destDir)\n traversal(rootDir)\n","sub_path":"py/replacejava.py","file_name":"replacejava.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"489704070","text":"\"\"\"\nSQLAlchemy attribute annotations\n--------------------------------\n\nAnnotations are strings attached to attributes that serve as a programmer\nreference on how those attributes are meant to be used. They can be used to\nindicate that a column's value should be :attr:`immutable` and should never\nchange, or that it's a :attr:`cached` copy of a value from another source\nthat can be safely discarded in case of a conflict.\n\nThis module's exports may be imported via :mod:`coaster.sqlalchemy`.\n\nSample usage::\n\n from coaster.db import db\n from coaster.sqlalchemy import annotation_wrapper, immutable\n\n natural_key = annotation_wrapper('natural_key', \"Natural key for this model\")\n\n class MyModel(db.Model):\n __tablename__ = 'my_model'\n id = immutable(db.Column(db.Integer, primary_key=True))\n name = natural_key(db.Column(db.Unicode(250), unique=True))\n\n @classmethod\n def get(cls, **kwargs):\n for key in kwargs:\n if key in cls.__column_annotations__[natural_key.name]:\n return cls.query.filter_by(**{key: kwargs[key]}).one_or_none()\n\nAnnotations are saved to the model's class as a ``__column_annotations__``\ndictionary, mapping annotation names to a list of attribute names, and to a\nreverse lookup ``__column_annotations_by_attr__`` of attribute names to annotations.\n\"\"\"\n\nfrom collections.abc import Hashable\nfrom typing import Any, Dict\n\nfrom sqlalchemy import event\nfrom sqlalchemy.orm import ColumnProperty, RelationshipProperty, SynonymProperty, mapper\nfrom sqlalchemy.orm.attributes import QueryableAttribute\nfrom sqlalchemy.schema import SchemaItem\n\nfrom ..signals import coaster_signals\n\ntry: # SQLAlchemy >= 1.4\n from sqlalchemy.orm import MapperProperty # type: ignore[attr-defined]\nexcept ImportError: # SQLAlchemy < 1.4\n from sqlalchemy.orm.interfaces import MapperProperty\n\n__all__ = ['annotations_configured', 'annotation_wrapper']\n\n# Global dictionary for temporary storage of annotations until the\n# mapper_configured events\n__cache__: Dict[Any, list] = {}\n\n# --- Signals -----------------------------------------------------------------\n\nannotations_configured = coaster_signals.signal(\n 'annotations-configured',\n doc=\"Signal raised after all annotations on a class are configured\",\n)\n\n\n# --- SQLAlchemy signals for base class ---------------------------------------\n\n\n@event.listens_for(mapper, 'mapper_configured')\ndef _configure_annotations(mapper_, cls):\n \"\"\"\n Extract annotations from attributes.\n\n Run through attributes of the class looking for annotations from\n :func:`annotation_wrapper` and add them to :attr:`cls.__column_annotations__`\n and :attr:`cls.__column_annotations_by_attr__`\n \"\"\"\n annotations = {}\n annotations_by_attr = {}\n\n # An attribute may be defined more than once in base classes. Only handle the first\n processed = set()\n\n # Loop through all attributes in the class and its base classes,\n # looking for annotations\n for base in cls.__mro__:\n for name, attr in base.__dict__.items():\n if name in processed or name.startswith('__'):\n continue\n\n if isinstance(attr, QueryableAttribute) and isinstance(\n getattr(attr, 'original_property', None), SynonymProperty\n ):\n # Skip synonyms\n data = None\n # 'data' is a list of string annotations\n elif isinstance(attr, Hashable) and attr in __cache__:\n data = __cache__[attr]\n elif hasattr(attr, '_coaster_annotations'):\n data = attr._coaster_annotations\n elif isinstance(\n attr, (QueryableAttribute, RelationshipProperty, MapperProperty)\n ):\n if attr.property in __cache__:\n data = __cache__[attr.property]\n elif '_coaster_annotations' in attr.info:\n data = attr.info['_coaster_annotations']\n elif hasattr(attr.property, '_coaster_annotations'):\n data = getattr(attr.property, '_coaster_annotations')\n else:\n data = None\n else:\n data = None\n if data is not None:\n annotations_by_attr.setdefault(name, []).extend(data)\n for a in data:\n annotations.setdefault(a, []).append(name)\n processed.add(name)\n\n # Classes specifying ``__column_annotations__`` directly isn't supported,\n # so we don't bother preserving existing content, if any.\n if annotations:\n cls.__column_annotations__ = annotations\n if annotations_by_attr:\n cls.__column_annotations_by_attr__ = annotations_by_attr\n annotations_configured.send(cls)\n\n\n# --- Helpers -----------------------------------------------------------------\n\n\ndef annotation_wrapper(annotation, doc=None):\n \"\"\"Define an annotation, which can be applied to attributes in a database model.\"\"\"\n\n def decorator(attr):\n __cache__.setdefault(attr, []).append(annotation)\n # Also mark the annotation on the object itself. This will\n # fail if the object has a restrictive __slots__, but it's\n # required for some objects like Column because SQLAlchemy copies\n # them in subclasses, changing their hash and making them\n # undiscoverable via the cache.\n if isinstance(attr, SynonymProperty):\n raise TypeError(\n \"Synonyms cannot have annotations; set it on the referred attribute\"\n )\n if isinstance(attr, (SchemaItem, ColumnProperty, MapperProperty)):\n attr.info.setdefault('_coaster_annotations', []).append(annotation)\n else:\n try:\n if not hasattr(attr, '_coaster_annotations'):\n setattr(attr, '_coaster_annotations', [])\n attr._coaster_annotations.append(annotation)\n except AttributeError:\n pass\n return attr\n\n decorator.__name__ = decorator.name = annotation\n decorator.__doc__ = doc\n return decorator\n","sub_path":"coaster/sqlalchemy/annotations.py","file_name":"annotations.py","file_ext":"py","file_size_in_byte":6150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"552681403","text":"# # # # # # # # # # # # # # # # # # # # # # # #\r\n# # \r\n# Module to run condition module #\r\n# By: David Alvarez #\r\n# 08-11-2020 #\r\n# Version Aplha-0. 1 # \r\n# #\r\n# # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\nfrom PywerAPM_Case_Setting import*\r\n\r\nfrom APM_Module import APM \r\nfrom Processing_tools import Report_APM_df, Report_APM_Meta_data, Report_ACM_Meta_data\r\nimport pandas as pd\r\nfrom datetime import datetime\r\n\r\n#results_path ='RESULTS/'\r\n\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n# Run criticality #\r\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\r\n\r\ndef run_criticality():\r\n import PywerACM_Main\r\n df = PywerACM_Main.run_ACM(N)\r\n store = pd.HDFStore(results_path+'Results_ACM.h5')\r\n store.put('df', df)\r\n store.get_storer('df').attrs['TITLE'] = 'ACM_Report'\r\n date = datetime.date(datetime.now())\r\n print(date)\r\n store.get_storer('df').attrs['Date'] = date\r\n store.close()\r\n\r\n\r\ndef load_criticality(cr_type='Monte_Carlo',assets=None): \r\n if cr_type == 'Monte_Carlo': # Load Montecarlo simulations\r\n store = pd.HDFStore(results_path+'Results_ACM.h5')\r\n df = store['df']\r\n store.close()\r\n else: # Fixed conditios\r\n df = assets.copy()\r\n df_type = {}\r\n df_group = assets.groupby(['Disc_Type'])\r\n for group in df_group: # Read criticality by type of asset \r\n name = group[0]\r\n df_type = pd.read_excel(cr_type, sheet_name=name,usecols = \"A:H\")\r\n for index, row in df_type.iterrows(): \r\n df.loc[(df.Disc_Type==name) & (df.Asset_To_Disconet==row.Asset),['Cr_Env','Cr_Sec','Cr_Leg']] = [row.ENVIRONMENTAL,row.SECURITY,row.LEGAL]\r\n # Total criticality\r\n df['T_Cr'] = df['Cr_Env']+df['Cr_Sec']+df['Cr_Leg']+df['Cr_Fin'] \r\n return df\r\n\r\n# Generate condition report\r\ndef Generate_Report_Risk(DF_ACP,DF_sum):\r\n from R1_Reports import Test_Report_AC\r\n Test_Report_AC(report_data,DF_ACP,DF_sum,years,N)\r\n","sub_path":"APM/BIN/ARM_Run.py","file_name":"ARM_Run.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"620215529","text":"# -*- coding: utf8 -*-\n# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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 tencentcloud.common.abstract_model import AbstractModel\n\n\nclass DataPoint(AbstractModel):\n \"\"\"监控数据点\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n :param Dimensions: 实例对象维度组合\n :type Dimensions: list of Dimension\n :param Timestamps: 时间戳数组,表示那些时间点有数据,缺失的时间戳,没有数据点,可以理解为掉点了\n :type Timestamps: list of float\n :param Values: 监控值数组,该数组和Timestamps一一对应\n :type Values: list of float\n \"\"\"\n self.Dimensions = None\n self.Timestamps = None\n self.Values = None\n\n\n def _deserialize(self, params):\n if params.get(\"Dimensions\") is not None:\n self.Dimensions = []\n for item in params.get(\"Dimensions\"):\n obj = Dimension()\n obj._deserialize(item)\n self.Dimensions.append(obj)\n self.Timestamps = params.get(\"Timestamps\")\n self.Values = params.get(\"Values\")\n\n\nclass DescribeBaseMetricsRequest(AbstractModel):\n \"\"\"DescribeBaseMetrics请求参数结构体\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n :param Namespace: 业务命名空间\n :type Namespace: str\n :param MetricName: 指标名\n :type MetricName: str\n \"\"\"\n self.Namespace = None\n self.MetricName = None\n\n\n def _deserialize(self, params):\n self.Namespace = params.get(\"Namespace\")\n self.MetricName = params.get(\"MetricName\")\n\n\nclass DescribeBaseMetricsResponse(AbstractModel):\n \"\"\"DescribeBaseMetrics返回参数结构体\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n :param MetricSet: 查询得到的指标描述列表\n :type MetricSet: list of MetricSet\n :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n :type RequestId: str\n \"\"\"\n self.MetricSet = None\n self.RequestId = None\n\n\n def _deserialize(self, params):\n if params.get(\"MetricSet\") is not None:\n self.MetricSet = []\n for item in params.get(\"MetricSet\"):\n obj = MetricSet()\n obj._deserialize(item)\n self.MetricSet.append(obj)\n self.RequestId = params.get(\"RequestId\")\n\n\nclass Dimension(AbstractModel):\n \"\"\"实例对象的维度组合\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n :param Name: 实例维度名称\n :type Name: str\n :param Value: 实例维度值\n :type Value: str\n \"\"\"\n self.Name = None\n self.Value = None\n\n\n def _deserialize(self, params):\n self.Name = params.get(\"Name\")\n self.Value = params.get(\"Value\")\n\n\nclass DimensionsDesc(AbstractModel):\n \"\"\"维度信息\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n :param Dimensions: 维度名数组\n :type Dimensions: list of str\n \"\"\"\n self.Dimensions = None\n\n\n def _deserialize(self, params):\n self.Dimensions = params.get(\"Dimensions\")\n\n\nclass GetMonitorDataRequest(AbstractModel):\n \"\"\"GetMonitorData请求参数结构体\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n :param Namespace: 命名空间,每个云产品会有一个命名空间\n :type Namespace: str\n :param MetricName: 指标名称,各个云产品的详细指标说明请参阅各个产品[监控接口](https://cloud.tencent.com/document/product/248/30384)文档\n :type MetricName: str\n :param Instances: 实例对象的维度组合\n :type Instances: list of Instance\n :param Period: 监控统计周期。默认为取值为300,单位为s\n :type Period: int\n :param StartTime: 起始时间,如2018-09-22T19:51:23+08:00\n :type StartTime: str\n :param EndTime: 结束时间,默认为当前时间。 EndTime不能小于EtartTime\n :type EndTime: str\n \"\"\"\n self.Namespace = None\n self.MetricName = None\n self.Instances = None\n self.Period = None\n self.StartTime = None\n self.EndTime = None\n\n\n def _deserialize(self, params):\n self.Namespace = params.get(\"Namespace\")\n self.MetricName = params.get(\"MetricName\")\n if params.get(\"Instances\") is not None:\n self.Instances = []\n for item in params.get(\"Instances\"):\n obj = Instance()\n obj._deserialize(item)\n self.Instances.append(obj)\n self.Period = params.get(\"Period\")\n self.StartTime = params.get(\"StartTime\")\n self.EndTime = params.get(\"EndTime\")\n\n\nclass GetMonitorDataResponse(AbstractModel):\n \"\"\"GetMonitorData返回参数结构体\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n :param Period: 统计周期\n :type Period: int\n :param MetricName: 指标名\n :type MetricName: str\n :param DataPoints: 数据点数组\n :type DataPoints: list of DataPoint\n :param StartTime: 开始时间\n :type StartTime: str\n :param EndTime: 结束时间\n :type EndTime: str\n :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。\n :type RequestId: str\n \"\"\"\n self.Period = None\n self.MetricName = None\n self.DataPoints = None\n self.StartTime = None\n self.EndTime = None\n self.RequestId = None\n\n\n def _deserialize(self, params):\n self.Period = params.get(\"Period\")\n self.MetricName = params.get(\"MetricName\")\n if params.get(\"DataPoints\") is not None:\n self.DataPoints = []\n for item in params.get(\"DataPoints\"):\n obj = DataPoint()\n obj._deserialize(item)\n self.DataPoints.append(obj)\n self.StartTime = params.get(\"StartTime\")\n self.EndTime = params.get(\"EndTime\")\n self.RequestId = params.get(\"RequestId\")\n\n\nclass Instance(AbstractModel):\n \"\"\"实例维度组合数组\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n :param Dimensions: 实例的维度组合\n :type Dimensions: list of Dimension\n \"\"\"\n self.Dimensions = None\n\n\n def _deserialize(self, params):\n if params.get(\"Dimensions\") is not None:\n self.Dimensions = []\n for item in params.get(\"Dimensions\"):\n obj = Dimension()\n obj._deserialize(item)\n self.Dimensions.append(obj)\n\n\nclass MetricObjectMeaning(AbstractModel):\n \"\"\"指标数据的解释\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n :param En: 指标英文解释\n :type En: str\n :param Zh: 指标中文解释\n :type Zh: str\n \"\"\"\n self.En = None\n self.Zh = None\n\n\n def _deserialize(self, params):\n self.En = params.get(\"En\")\n self.Zh = params.get(\"Zh\")\n\n\nclass MetricSet(AbstractModel):\n \"\"\"对业务指标的单位及支持统计周期的描述\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n :param Namespace: 命名空间,每个云产品会有一个命名空间\n :type Namespace: str\n :param MetricName: 指标名称\n :type MetricName: str\n :param Unit: 指标使用的单位\n :type Unit: str\n :param UnitCname: 指标使用的单位\n :type UnitCname: str\n :param Period: 指标支持的统计周期,单位是秒,如60、300\n :type Period: list of int\n :param Periods: 统计周期内指标方式\n :type Periods: list of PeriodsSt\n :param Meaning: 统计指标含义解释\n :type Meaning: :class:`tencentcloud.monitor.v20180724.models.MetricObjectMeaning`\n :param Dimensions: 维度描述信息\n :type Dimensions: list of DimensionsDesc\n \"\"\"\n self.Namespace = None\n self.MetricName = None\n self.Unit = None\n self.UnitCname = None\n self.Period = None\n self.Periods = None\n self.Meaning = None\n self.Dimensions = None\n\n\n def _deserialize(self, params):\n self.Namespace = params.get(\"Namespace\")\n self.MetricName = params.get(\"MetricName\")\n self.Unit = params.get(\"Unit\")\n self.UnitCname = params.get(\"UnitCname\")\n self.Period = params.get(\"Period\")\n if params.get(\"Periods\") is not None:\n self.Periods = []\n for item in params.get(\"Periods\"):\n obj = PeriodsSt()\n obj._deserialize(item)\n self.Periods.append(obj)\n if params.get(\"Meaning\") is not None:\n self.Meaning = MetricObjectMeaning()\n self.Meaning._deserialize(params.get(\"Meaning\"))\n if params.get(\"Dimensions\") is not None:\n self.Dimensions = []\n for item in params.get(\"Dimensions\"):\n obj = DimensionsDesc()\n obj._deserialize(item)\n self.Dimensions.append(obj)\n\n\nclass PeriodsSt(AbstractModel):\n \"\"\"周期内的统计方式\n\n \"\"\"\n\n def __init__(self):\n \"\"\"\n :param Period: 周期\n :type Period: str\n :param StatType: 统计方式\n :type StatType: list of str\n \"\"\"\n self.Period = None\n self.StatType = None\n\n\n def _deserialize(self, params):\n self.Period = params.get(\"Period\")\n self.StatType = params.get(\"StatType\")","sub_path":"tencentcloud/monitor/v20180724/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"342197793","text":"\"\"\"\nCreate a new dashboard with manage_status widget\n\"\"\"\n\nfrom datadog_api_client import ApiClient, Configuration\nfrom datadog_api_client.v1.api.dashboards_api import DashboardsApi\nfrom datadog_api_client.v1.model.dashboard import Dashboard\nfrom datadog_api_client.v1.model.dashboard_layout_type import DashboardLayoutType\nfrom datadog_api_client.v1.model.monitor_summary_widget_definition import MonitorSummaryWidgetDefinition\nfrom datadog_api_client.v1.model.monitor_summary_widget_definition_type import MonitorSummaryWidgetDefinitionType\nfrom datadog_api_client.v1.model.widget import Widget\nfrom datadog_api_client.v1.model.widget_color_preference import WidgetColorPreference\nfrom datadog_api_client.v1.model.widget_layout import WidgetLayout\nfrom datadog_api_client.v1.model.widget_monitor_summary_display_format import WidgetMonitorSummaryDisplayFormat\nfrom datadog_api_client.v1.model.widget_monitor_summary_sort import WidgetMonitorSummarySort\nfrom datadog_api_client.v1.model.widget_summary_type import WidgetSummaryType\n\nbody = Dashboard(\n title=\"Example-Dashboard\",\n description=\"\",\n widgets=[\n Widget(\n layout=WidgetLayout(\n x=0,\n y=0,\n width=50,\n height=25,\n ),\n definition=MonitorSummaryWidgetDefinition(\n type=MonitorSummaryWidgetDefinitionType.MANAGE_STATUS,\n summary_type=WidgetSummaryType.MONITORS,\n display_format=WidgetMonitorSummaryDisplayFormat.COUNTS_AND_LIST,\n color_preference=WidgetColorPreference.TEXT,\n hide_zero_counts=True,\n show_last_triggered=False,\n query=\"\",\n sort=WidgetMonitorSummarySort.STATUS_ASCENDING,\n count=50,\n start=0,\n ),\n ),\n ],\n template_variables=[],\n layout_type=DashboardLayoutType.FREE,\n is_read_only=False,\n notify_list=[],\n)\n\nconfiguration = Configuration()\nwith ApiClient(configuration) as api_client:\n api_instance = DashboardsApi(api_client)\n response = api_instance.create_dashboard(body=body)\n\n print(response)\n","sub_path":"examples/v1/dashboards/CreateDashboard_2917274132.py","file_name":"CreateDashboard_2917274132.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"155804561","text":"from typing import List\n\nclass Solution:\n #时间复杂度 O(N) : 其中 N 为列表 pushed 的长度;每个元素最多入栈与出栈一次,即最多共 2N 次出入栈操作。\n #空间复杂度 O(N) : 辅助栈 stack 最多同时存储 NN 个元素。\n\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack, i = [], 0 #stack辅助栈\n for num in pushed:\n stack.append(num) # num 入栈\n while stack and stack[-1] == popped[i]: # 如果栈顶一样 循环判断与出栈\n stack.pop()\n i += 1 #把i +1,指向下一个popped的值\n return not stack\n\n","sub_path":"Offer/Offer31-validateStackSequences.py","file_name":"Offer31-validateStackSequences.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"407812493","text":"import rospy\nimport numpy as np\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Twist\n\n\nclass KalmanFilter():\n def __init__(self, position, velocity):\n self.step_time = 0.1\n self.X0 = self.get_numpy_state(position, velocity)\n self.P0 = 0.001 * np.eye(4) # Ne znam kako izgleda pocetna matrica\n self.Q = 0.1 * np.eye(4)\n self.R = 0.001 * np.eye(2)\n\n T = self.step_time\n self.A = np.array([[1, 0, T, 0], [0, 1, 0, T], [0, 0, 1, 0], [0, 0, 0, 1]])\n self.B = np.array([[]])\n self.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]])\n\n self.X_old = self.X0\n self.P_old = self.P0\n\n def get_numpy_state(self, position, velocity=Twist()):\n \"\"\"Convert from some type (here: ROS msg) to numpy array.\"\"\"\n x = position.position.x\n y = position.position.y\n vx = velocity.linear.x\n vy = velocity.linear.y\n state = np.array([[x, y, vx, vy]])\n return state.T\n\n def get_used_state(self, np_state):\n \"\"\"Convert from numpy array to type used elswhere (here: ROS msg).\"\"\"\n time = rospy.Time.now()\n msg = Odometry()\n msg.header.stamp = time\n msg.pose.pose.position.x = np_state[0][0]\n msg.pose.pose.position.y = np_state[1][0]\n msg.twist.twist.linear.x = np_state[2][0]\n msg.twist.twist.linear.y = np_state[3][0]\n return msg\n\n def predict(self, u):\n \"\"\"\n Args:\n u: input vector\n \"\"\"\n X_est = np.dot(self.A, self.X_old)\n P_est = np.dot(np.dot(self.A, self.P_old), self.A.T) + self.Q\n\n self.X_old = X_est\n self.P_old = P_est\n\n return X_est, P_est\n\n def update(self, X_est, P_est, Xm):\n \"\"\"\n Args:\n Xm: measured state\n X_est: estimated state from prediction step\n P_est: estimated covariance matrix from prediction step\n \"\"\"\n Xm = self.get_numpy_state(Xm)\n K = np.dot(np.dot(P_est, self.H.T), np.linalg.inv(np.dot(np.dot(self.H, P_est), self.H.T) + self.R))\n Y = np.dot(self.H, Xm)\n X_new = X_est + np.dot(K, (Y - np.dot(self.H, X_est)))\n P_new = np.eye(4) - np.dot(np.dot(K, self.H), P_est)\n\n self.X_old = X_new\n self.P_old = P_new\n\n return self.get_used_state(X_new)\n","sub_path":"scripts/kalman.py","file_name":"kalman.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"394679148","text":"import socket\nimport sys\n\n\n# Create a TCP/IP socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Connect the socket to the port where the server is listening\nserver_address = ('localhost', 10000)\nprint(sys.stderr, 'connecting to %s port %s' % server_address)\nsock.connect(server_address)\n\n# After the connection is established, data can be sent through the socket with sendall() and received with recv(), just as in the server.\n\ntry:\n # Send data\n # message = input()\n line = \"\"\"a = input('a=')\nprint(a)\"\"\"\n message = exec(line)\n\n # message = 'This is the message. It will be repeated.'\n print(sys.stderr, 'sending {}'.format(message))\n sock.sendall(message.encode('utf-8'))\n\n # Look for the response\n amount_received = 0\n amount_expected = len(message)\n\n while amount_received < amount_expected:\n data = sock.recv(1024)\n amount_received += len(data)\n print(sys.stderr, 'received {}'.format(data))\nfinally:\n print(sys.stderr, 'closing socket')\n sock.close()\n","sub_path":"Socket Programming/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"407828869","text":"import numpy as np\nimport matplotlib.pyplot as plt\n# State 0 is facing towards the lava, State 1 is facing away from the lava.\n# Control actions are moving forward, moving backward (which are absorbing states) and turning around\n\ncontrol_action_rewards = np.array(\n [[-100,100,-1],\n [100,-50,-1]]).T\n\nmeasurement_probabilities = np.array(\n [[0.7, 0.3],\n [0.3, 0.7]]\n)\npx1_u_x2 = np.array(\n [[[0, 0], [0, 0]],\n [[0, 0], [0, 0]],\n [[0.8, 0.2],[0.2, 0.8]]]\n)\n\n# Line set for each control action\ndef calculate_policy(T, gamma):\n # Initial line set\n line_set = [[0,0]]\n for tau in range(T):\n print(tau)\n all_new_lines = []\n policy = {}\n v_kuzj = np.zeros((len(line_set),3,2,2))\n # Cycle through each line\n for k, line in enumerate(line_set):\n # Cycle through each control action\n for u in range(3):\n # Cycle through each measurement\n for z in range(2):\n # Cycle through each state\n for j in range(2):\n for i in range(2):\n vik = line[i]\n pz_xi = measurement_probabilities[z][i]\n pxi_u_xj = px1_u_x2[u][j][i]\n v_kuzj[k][u][z][j] += vik*pz_xi*pxi_u_xj\n for u in range(3):\n for k1, line1 in enumerate(line_set):\n for k2, line2 in enumerate(line_set):\n v = [0,0]\n for i in range(2):\n v[i] = gamma*(control_action_rewards[u][i] + v_kuzj[k1][u][0][i] + v_kuzj[k2][u][1][i])\n if abs(v[0]) == 100*gamma:\n policy[(v[0], v[1])] = u\n else:\n policy[(v[1], v[0])] = u\n all_new_lines.append(v)\n line_set = np.copy(all_new_lines)\n if tau==0:\n pruned_lines = line_set\n else:\n not_initial = np.argwhere(abs(line_set[:,0]) != gamma*100)\n line_set[not_initial] = np.flip(np.squeeze(line_set[not_initial]), axis=1)[:,None,:]\n # Prune the lines\n # Check for duplicates\n line_dict = {}\n next_lines = []\n for line_first in line_set:\n skip_line = False\n for check_line in next_lines:\n if np.allclose(line_first, check_line):\n skip_line = True\n break\n if skip_line:\n continue\n next_lines.append(line_first) \n # Keep dominant lines\n to_examine = next_lines[np.argmax(np.array(next_lines)[:,0])]\n pruned_lines = np.array([to_examine])\n start_x = 0\n finished = False\n remaining_linear_constraints = np.delete(next_lines, 1, axis=0)\n while not finished:\n # Check minimum intersecting lines\n m1 = np.repeat(to_examine[1]-to_examine[0], len(remaining_linear_constraints))\n b1 = np.repeat(to_examine[0], len(remaining_linear_constraints))\n m2 = remaining_linear_constraints[:,1] - remaining_linear_constraints[:,0]\n b2 = remaining_linear_constraints[:,0]\n delete_indices = np.where(np.isclose(m2-m1, 0))\n m1 = np.delete(m1, delete_indices, axis=0)\n b1 = np.delete(b1, delete_indices, axis=0)\n m2 = np.delete(m2, delete_indices, axis=0)\n b2 = np.delete(b2, delete_indices, axis=0)\n remaining_linear_constraints = np.delete(remaining_linear_constraints, delete_indices, axis=0)\n if len(remaining_linear_constraints) == 0:\n break\n x = (b1-b2)/(m2-m1)\n delete_indices_2 = np.where(x < start_x)\n x = np.delete(x, delete_indices_2)\n remaining_linear_constraints = np.delete(remaining_linear_constraints, delete_indices_2, axis=0)\n if len(remaining_linear_constraints) == 0:\n break\n\n mins = np.argmin(x)\n candidates = remaining_linear_constraints[mins].reshape(-1,2)\n pruned_lines = np.concatenate((pruned_lines, candidates), axis=0)\n remaining_linear_constraints = np.delete(remaining_linear_constraints, mins, axis=0)\n to_examine = np.copy(candidates)[0]\n start_x = x[mins] \n line_set = np.copy(pruned_lines)\n for constraint in line_set:\n plt.plot([0,1], constraint)\n print(line_set)\n return policy, line_set\n\n\n\ndef take_measurement(actual_state):\n prob = np.random.random()\n if prob > 0.7:\n return int(not actual_state)\n else:\n return actual_state\n\ndef update_belief_after_measurement(p1, measured):\n if measured == 1:\n return (p1*0.7)/(0.4*p1+0.3)\n else: \n return (p1*0.3)/(-0.4*p1+0.7)\n\ndef update_belief_after_state_change(p1):\n return (-0.6*p1 + 0.8)\n\ndef take_step_u3(actual_state):\n prob = np.random.random()\n if prob > 0.8:\n return actual_state\n else:\n return int(not actual_state)\n\ndef simulate(steps, p1, actual_state, line_set, policy):\n reward = 0\n m = line_set[:,1] - line_set[:,0]\n b = line_set[:,0]\n for i in range(steps):\n measurement = take_measurement(actual_state)\n p1 = update_belief_after_measurement(p1, measurement)\n p0 = p1\n policy_line = line_set[np.argmax(m*p1 + b)]\n action_to_take = policy[(policy_line[0], policy_line[1])]\n reward += control_action_rewards[action_to_take][actual_state]\n if action_to_take == 0 or action_to_take == 1:\n break\n else: \n prev_state = actual_state\n actual_state = take_step_u3(actual_state)\n p1 = update_belief_after_state_change(p1)\n print(\"Step: {}, x_prev: {}, z: {}, p_after_measure: {}, x_after: {}, p_after_state_transition: {}\".format(i, prev_state, measurement, p0, actual_state, p1))\n print(\"Step: {}, measurement: {}, Final p1: {} Final Reward: {}\".format(i, measurement, p1, reward))\n\nif __name__ == \"__main__\":\n T=20\n gamma = 1.0\n policy, line_set = calculate_policy(T, gamma)\n plt.show()\n for i in range(10):\n simulate(T, 0.6, 1.0, line_set, policy)","sub_path":"pomdp_planning/pomdp.py","file_name":"pomdp.py","file_ext":"py","file_size_in_byte":6430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"122007794","text":"\nimport time,re\n# current_time=time.localtime()\n# #print(current_time)\n# current_clock_time=time.strftime(\"%y/%m/%d-%H:%M:%S\")\n# print(current_clock_time)\nName=input(\"enter\")\nprice=input(\"enter\")\ndef valid_product(Name,price):\n val1=re.match(\"([a-z]+)([a-z]+)([a-z]+)$\",Name)\n val2=re.match(\"[0-9]{0,7}$\",price)\n if val1 and val2:\n return True\n else:\n return False\nprint(valid_product(Name,price))\n","sub_path":"day11/tt.py","file_name":"tt.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"159981923","text":"## Script (Python) \"guard_cancelled_object\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=\n##title=\n##\n\nwf_tool = context.portal_workflow\n\n# Can't do anything to the object if it's cancelled\nif wf_tool.getInfoFor(context, 'cancellation_state') == \"cancelled\":\n return False\n\nreturn True\n\n","sub_path":"bika/lims/skins/bika/guard_cancelled_object.py","file_name":"guard_cancelled_object.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"361105412","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 fileinput\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) == 4:\n tags_file = sys.argv[1]\n ref_species = sys.argv[2]\n out_file = sys.argv[3]\nelse:\n sys.exit(\"The usage shoud be: ./FinderSBH.py in_file tag_file output_file\")\n\n#VARIABLES\n#!/usr/bin/env python3\n\n#VARIABLES\nquery_species = \"\"\nSBH_dict = {}\nspecies_counter = {}\ncluster_dict = {}\n\n\"\"\"\nRead TAGs file foreach primate species used in the analysis\nand store it in a Pandas DataFrame\n\"\"\"\n\nSpecies_tags = pd.read_csv(tags_file, sep='\\t', low_memory=False)#panda creation\ncolnames = ['Target{}'.format(num) for num in range(1, len(Species_tags))]\nfinalnames = ['Query'] + colnames\nSBH_df = pd.DataFrame(columns=finalnames)\n\n\n\"\"\"\nFUNCTIONS\n\"\"\"\n\n\"\"\"\nStore in a dictionary all target species so as to keep a counter\nfor unique species as best hits\n\"\"\"\n\ndef store_target_species_count_in_dict(Species_df, reference):\n target_species = Species_df['Species'].to_list()\n print(reference)\n target_species.remove(reference)\n species_counter = {name:0 for name in target_species}\n return species_counter\n\n\n\"\"\"\nHere, we create a function that parses the clusters of sequences to retrieve all\nIDs from the cluster appart from the representative one\n\"\"\"\n\ndef parse_cluster_file(clusters_file, clusters_dict):\n with open(clusters_file, \"rt\") as in_fh:\n id = \"\"\n clustered = []\n for line in in_fh:\n line = line.rstrip()\n if line.startswith(\">\") and not id:\n continue\n elif line.startswith(\">\"):\n clusters_dict[representative] = clustered\n id = \"\"\n clustered = []\n else:\n id = line.split(\">\")[1].split(\".\")[0]\n if line[-1] == \"*\":\n representative = id\n else:\n clustered.append(id)\n clusters_dict[representative] = clustered\n return clusters_dict\n\n\n\"\"\"\nAnother function here helps us to identify extra species by looking whether the\nID of the species match any of the clusters, and retrieves all the other\ntarget IDs associated\n\"\"\"\n\n\ndef check_all_species_in_cluster(ident, query, clusters_dict, best_hit_dict,\nsp_counter):\n sp_counter, best_hit_dict = include_only_best_hit_foreach_species_target(ident,\n best_hit_dict, query, sp_counter)\n if ident in clusters_dict:\n for value in clusters_dict[ident]:\n sp_counter, best_hit_dict = include_only_best_hit_foreach_species_target(value,\n best_hit_dict, query, sp_counter)\n return sp_counter, best_hit_dict\n\n\n\"\"\"\nHere, the function includes only a species once, as the best hit for our reference\nspecies. Then, with that in mind, filters for species appearing more than once\nas hits for a specific query entry\n\"\"\"\n\n#FUNCTION TO INCLUDE ONLY A SPECIES ONCE (BEST HIT)\ndef include_only_best_hit_foreach_species_target(elem, best_hit_dict, query,\nsp_counter):\n for item in Species_tags['Tag']:\n if elem.startswith(item):\n current_species = Species_tags.loc[Species_tags['Tag'] == item].Species.item()\n if current_species in sp_counter:\n if sp_counter[current_species] == 0:\n sp_counter[current_species] += 1\n best_hit_dict[query].append(elem)\n return sp_counter, best_hit_dict\n\n\n\"\"\"\nLast function to print the ouput in Pandas format for the Query and\nTarget columns in our dataframe\n\"\"\"\n\n#FUNCTION TO INCLUDE ONLY A SPECIES ONCE (BEST HIT)\ndef append_out_BBHs_pandas_format(sbh_dict, sbh_df, query):\n query_row = [query] + sbh_dict[query] + \\\n list(np.repeat(np.nan, len(sbh_df.columns)-len(sbh_dict[query])-1))\n sbh_df = sbh_df.append(pd.Series(query_row, index=sbh_df.columns),\n ignore_index=True)\n return sbh_df\n\n\n\n\"\"\"\nMAIN\n\"\"\"\n\nspecies_counter = store_target_species_count_in_dict(Species_tags, ref_species)\n\n#cluster_dict = parse_cluster_file(clust_file, cluster_dict)\n\ncount = 0\nin_fh = iter(sys.stdin)\nfor line in in_fh:\n line = line.rstrip()\n if line.startswith(\"Query=\") and query_species == \"\":\n query_fields = line[7:].split(\" \")\n query_species = \"_\".join(query_fields[0:1])\n SBH_dict[query_species] = []\n elif line.startswith(\"Query=\"):\n SBH_df = append_out_BBHs_pandas_format(SBH_dict, SBH_df,\n query_species)\n query_fields = line[7:].split(\" \")\n query_species = \"_\".join(query_fields[0:1])\n SBH_dict[query_species] = []\n species_counter = {k:0 for k in species_counter}\n elif line.startswith(\"Sequences producing significant alignments\"):\n next(in_fh)\n line_new = next(in_fh).rstrip()\n while (any(letter.isalnum() for letter in line_new)):\n ID_fields = line_new.split(\" \")\n ID = \"_\".join(ID_fields[2:3])\n species_counter, SBH_dict = include_only_best_hit_foreach_species_target(ID, SBH_dict,\n query_species, species_counter)\n line_new = next(in_fh).rstrip()\n\n#REPEAT THIS AFTER LOOP`FOR LAST HOMOLOG ENTRY\nSBH_df = append_out_BBHs_pandas_format(SBH_dict, SBH_df,\nquery_species)\n#Print_SBHs_in_Pandas_format(SBH_dict, SBH_df, out_file)\nSBH_df.to_csv(out_file, sep = \"\\t\", index=False)\n","sub_path":"Orthologies_human_driven_refs/BlastP/BBHs/FinderSBH.py","file_name":"FinderSBH.py","file_ext":"py","file_size_in_byte":5650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"491461380","text":"###Edit by Hanlin Gu on 1/9/2020\n###obtain population of different conformations, 'result$.txt' is the revised version of '2nd_stage_brute_force_classification_result.dat', removed:@\n###2nd_stage_brute_force_classification_result.dat has 8 columns, the 1st column is the number, 2nd-7th columns are distance of three conformations in two range(so is 6)\n### 8th column is the minmum distance of 2nd-7th distance, 9th column is the conformation number which will assign. \n###Actually here we have three conformations in two range, so is 6 classes, even number classes are right which represent blue range and odd number classes are wrong which\n### represent the green range\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef cal(path):\n data = np.loadtxt(path)\n print(data.shape)\n open = 0\n intermmediate = 0\n close = 0\n distance = []\n distance1 = []\n distance2 = []\n for i in range(data.shape[0]):\n if data[i, 8] == 0:\n open = open + 1\n distance.append(data[i, 7])\n if data[i, 8] == 2:\n distance1.append(data[i, 7])\n intermmediate = intermmediate + 1\n if data[i, 8] == 4:\n distance2.append(data[i, 7])\n\n close = close + 1\n\n plt.scatter(np.arange(len(distance)), distance)\n plt.savefig('large_range_distribution.png')\n plt.show()\n print(close)\n sum = open + close + intermmediate\n exp = [float(open / sum), float(intermmediate / sum), float(close / sum)]\n return exp\n\n\nif __name__ == '__main__':\n path = ['result1.txt', 'result2.txt',\n 'result3.txt']\n array = []\n real = [0.4, 0.3, 0.3]\n\n for i in range(3):\n print(path[i])\n exp = cal(path[i])\n print(exp)\n array.append(exp)\n fig = plt.figure(num=1, figsize=(15, 8), dpi=80)\n plt.title('propotion comparison')\n plt.plot(np.arange(3), exp, color='y', label='experiment3')\n plt.plot(np.arange(3), real, color='r', label='real')\n plt.legend(loc='upper right')\n \n \n plt.savefig('proportion_comparison')\n mean = np.mean(array, 0)\n rows = ['%d' % x for x in range(3)]\n std = np.std(array, 0)\n\n plt.cla()\n columns = ('mean', 'std')\n cell_text = np.transpose(np.array([mean, std]))\n table = plt.table(cellText=cell_text,\n rowLabels=rows,\n colLabels=columns, loc='center')\n table.scale(1, 4)\n table.set_fontsize(14)\n plt.axis('off')\n plt.title('three score')\n plt.savefig( 'comparison table')\n","sub_path":"two_stage_matching/analyze_population.py","file_name":"analyze_population.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"441060622","text":"import cv2 as cv\nimport time\nfrom imutils.video import VideoStream\nimport imutils\nimport pickle\nimport cv2\nimport dlib\nimport numpy as np\n\n\ndef detector(image):\n frame = image \n detector = dlib.fhog_object_detector('mysign.svm')\n detector_light = dlib.fhog_object_detector('mytraffic_light.svm')\n # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n rects = detector(frame, 0)\n rects_light = detector_light(frame, 0) \n\n if len(rects) > 0:\n for rect in rects:\n (bX, bY, bW, bH) = (rect.left(), rect.top(), rect.right(), rect.bottom())\n if bX < 0:\n bX = 0\n if bY < 0:\n bY = 0\n if bW < 0:\n bW = 0\n if bH < 0:\n bH = 0\n\n cv2.rectangle(frame, (bX, bY), (bW, bH),(255, 255, 255), 5)\n\n\n\n# vs = VideoStream(usePiCamera=True).start()\nvs = VideoStream(src=0).start()\ntime.sleep(2)\nwhile True:\n frame = vs.read()\n frame = imutils.resize(frame, width=750)\n # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n frame = cv2.GaussianBlur(frame, (5, 5), 0)\n\n\n lap = cv2.Laplacian(frame, cv2.CV_64F)\n lap = np.uint8(np.absolute(lap))\n # cv2.imshow(\"Laplacian\", lap)\n # cv2.waitKey(0)\n\n # Sobel edge detection\n sobelX = cv2.Sobel(frame, cv2.CV_64F, 1, 0)\n sobelY = cv2.Sobel(frame, cv2.CV_64F, 0, 1)\n\n sobelX = np.uint8(np.absolute(sobelX))\n sobelY = np.uint8(np.absolute(sobelY))\n\n sobelCombined = cv2.bitwise_or(sobelX, sobelY)\n detector(sobelCombined)\n cv2.imshow(\"Frame\", sobelCombined)\n key = cv2.waitKey(100)\n if key == ord(\"q\"):\n break\ncv2.destroyAllWindows()\nvs.stop()\n","sub_path":"img_processing/f_my_edge_sobel.py","file_name":"f_my_edge_sobel.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"549806564","text":"from wx import *\n\nclass MyApp(App):\n def OnInit(self):\n f = Frame(None, -1, \"Titulo\")\n p = Panel(f)\n s = BoxSizer(VERTICAL)\n t1 = self.t1 = TextCtrl(p)\n t2 = self.t2 = TextCtrl(p)\n b = Button(p, -1, \"Suma\")\n r = self.r = StaticText(p)\n b.Bind(EVT_BUTTON, self.sumar)\n s.Add(t1)\n s.Add(t2)\n s.Add(b)\n s.Add(r)\n p.SetSizer(s)\n f.Show()\n\n return True\n\n def sumar(self, e):\n self.r.SetLabel(str(int(self.t1.Value) + int(self.t2.Value)))\n\n\napp = MyApp()\napp.MainLoop()\n\n","sub_path":"18wx-001.py","file_name":"18wx-001.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"371279436","text":"from .layers import Linear\nfrom ..utils import glorot\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Discriminator(nn.Module):\n def __init__(self, name, dim, mlp_dim=None):\n super(Discriminator, self).__init__()\n self.dim = dim\n self.mlp_dim = mlp_dim\n self.layer = disc_dict[name.lower()](dim, mlp_dim)\n\n def forward(self, x, y, outer=False):\n score = self.layer(x, y, outer)\n return score\n\n\nclass InnerProd(nn.Module):\n def __init__(self, dim, mlp_dim):\n super(InnerProd, self).__init__()\n self.dim = dim\n\n def forward(self, x, y, outer=False):\n if outer:\n score = torch.matmul(x, y.transpose(1,0)) \n else:\n score = torch.sum((x * y), dim=-1)\n return score\n\n\nclass Bilinear(nn.Module):\n def __init__(self, dim, mlp_dim):\n super(Bilinear, self).__init__()\n self.dim = dim\n self.bil = nn.Bilinear(dim, dim, 1)\n self.weight = glorot([dim, dim])\n\n def forward(self, x, y, outer=False):\n if outer:\n score = torch.matmul(torch.matmul(x, self.weight), y.transpose(1,0))\n else:\n score = torch.squeeze(self.bil(x, y), dim=-1)\n return score\n\n\nclass MLP(nn.Module):\n def __init__(self, dim, mlp_dim):\n super(MLP, self).__init__()\n self.dim = dim\n self.layers = nn.ModuleList()\n self.mlp_dim = mlp_dim\n for i in range(1, len(self.mlp_dim) - 1):\n self.layers.append(Linear(self.mlp_dim[i - 1], self.mlp_dim[i], act=F.relu))\n self.layers.append(Linear(self.mlp_dim[-2], self.mlp_dim[-1], act=lambda x: x))\n\n def forward(self, x, y, outer=False):\n h = torch.cat([x, y], dim=1)\n for layer in self.layers:\n h = layer(h)\n return torch.squeeze(h, dim=-1)\n\n\ndisc_dict = {\n \"inner\": InnerProd,\n \"bilinear\": Bilinear,\n \"mlp\": MLP\n}\n","sub_path":"src/opengcl/framework/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"314747050","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/svpino/dev/tensorflow-object-detection-sagemaker/todl/tensorflow-object-detection/research/object_detection/protos/anchor_generator_pb2.py\n# Compiled at: 2020-04-05 21:16:38\n# Size of source mod 2**32: 6890 bytes\nimport google.protobuf as _descriptor\nimport google.protobuf as _message\nimport google.protobuf as _reflection\nimport google.protobuf as _symbol_database\n_sym_db = _symbol_database.Default()\nimport object_detection.protos as object__detection_dot_protos_dot_flexible__grid__anchor__generator__pb2\nimport object_detection.protos as object__detection_dot_protos_dot_grid__anchor__generator__pb2\nimport object_detection.protos as object__detection_dot_protos_dot_multiscale__anchor__generator__pb2\nimport object_detection.protos as object__detection_dot_protos_dot_ssd__anchor__generator__pb2\nDESCRIPTOR = _descriptor.FileDescriptor(name='object_detection/protos/anchor_generator.proto',\n package='object_detection.protos',\n syntax='proto2',\n serialized_options=None,\n serialized_pb=b'\\n.object_detection/protos/anchor_generator.proto\\x12\\x17object_detection.protos\\x1a 1]\n\n print('Building common features...')\n graph_ids, graph_texts, class_weights, node_classes, edge_classes, max_num_nodes, coarse_pos_tags, fine_pos_tags, \\\n node_texts = get_common_info(graphs, class_mapping)\n\n print('Calculating graph features...')\n # convert edge labels to ids\n for i, (_, g, _) in enumerate(graphs):\n for u, v, old_attrs in g.edges(data=True):\n edge_class_id = edge_classes.index(transform.get_label_for_edge(old_attrs))\n g.edges[u, v].update({\n 'class_one_hot': tf.one_hot(edge_class_id, depth=len(edge_classes), dtype=tf.float32),\n 'class_ordinal': edge_class_id\n })\n for n_id, old_attrs in g.nodes(data=True):\n node_class = transform.get_node_class_for_node(old_attrs, class_mapping)\n if node_class != transform.IRRELEVANT_CLASS:\n node_class_id = node_classes.index(node_class)\n node_class_one_hot = tf.one_hot(node_class_id, depth=len(node_classes), dtype=tf.float32)\n else:\n node_class_id = -1\n node_class_one_hot = tf.zeros((len(node_classes),))\n pos_tag_attrs = {}\n for pos_tags, pos_tag_names in [('coarse_pos_tags', coarse_pos_tags), ('fine_pos_tags', fine_pos_tags)]:\n pos_tag_ids = [pos_tag_names.index(p) for p in old_attrs.get(pos_tags, [transform.IRRELEVANT_CLASS])]\n pos_tag_attrs[f'{pos_tags}_ordinal'] = pos_tag_ids\n pos_tag_attrs[f'{pos_tags}_encoded'] = tf.math.add_n([\n tf.one_hot(i, depth=len(pos_tag_names))\n for i in pos_tag_ids\n ])\n g.nodes[n_id].update({\n 'class_one_hot': node_class_one_hot,\n 'class_ordinal': node_class_id,\n 'is_target': node_class not in [transform.IRRELEVANT_CLASS]\n })\n g.nodes[n_id].update(pos_tag_attrs)\n\n node_feature = node_feature_builder(n_id, old_attrs, g)\n if type(node_feature) in [int, float]:\n new_node_feature_len = 1\n elif type(node_feature) in [np.ndarray, tf.Tensor, EagerTensor]:\n new_node_feature_len = node_feature.shape[0]\n elif type(node_feature) in [list, set]:\n new_node_feature_len = len(node_feature)\n else:\n raise ValueError(f'Unsupported feature type {type(node_feature)}.')\n if node_feature_len is None:\n node_feature_len = new_node_feature_len\n else:\n assert node_feature_len == new_node_feature_len, 'Inconsistent node feature lengths. Make sure the ' \\\n 'FeatureBuilder always returns the same size features.' \\\n f'new: {new_node_feature_len} vs old: {node_feature_len}'\n g.nodes[n_id].update({\n 'feature': node_feature,\n })\n print(f'\\rDone with graph {i + 1}/{len(graphs)}', end='')\n print()\n\n print('Converting NetworkX graphs to DGL graphs...')\n dgl_graphs: Dict[int, dgl.DGLHeteroGraph] = {}\n for i, (g_id, g, _) in enumerate(graphs):\n dgl_graph: dgl.DGLHeteroGraph = dgl.from_networkx(\n g,\n edge_attrs=['class_one_hot', 'class_ordinal'],\n node_attrs=['class_one_hot', 'class_ordinal', 'is_target', 'feature']\n )\n dgl_graphs[i] = dgl_graph\n print(f'\\rDone with graph {i + 1}/{len(graphs)}', end='')\n print()\n\n return {\n 'ids': np.array(graph_ids),\n 'texts': graph_texts,\n 'class_weights': class_weights,\n 'node_classes': node_classes,\n 'edge_classes': edge_classes,\n 'max_num_nodes': max_num_nodes,\n 'node_feature_len': node_feature_len,\n\n 'dgl_graphs': dgl_graphs,\n\n 'node_texts': node_texts\n }\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Processing utility for our datasets.')\n parser.add_argument(\n '--dataset',\n required=True,\n type=str,\n help='Path to the dataset to process.'\n )\n parser.add_argument(\n '--target',\n required=True,\n type=str,\n help='Path to the target file.'\n )\n parser.add_argument(\n '--features',\n type=str,\n help='Node features to build.',\n default='none',\n choices=['none', *Word2VecFeatureBuilder.SUPPORTED_MODELS, 'debug', 'bert', 'fine-pos', 'coarse-pos', 'concat']\n )\n parser.add_argument(\n '--mappings',\n nargs='*',\n required=False,\n help='One or many class mappings in the form :, '\n 'e.g. to change all Events to Tasks use Event:Task'\n )\n args = parser.parse_args()\n\n feature_builder: BaseNodeFeatureBuilder\n if args.features == 'none' or args.features == 'None':\n feature_builder = IdNodeFeatureBuilder()\n elif args.features == 'debug':\n feature_builder = DebugFeatureBuilder()\n elif args.features == 'bert':\n feature_builder = BertFeatureBuilder()\n elif args.features in ['fine-pos', 'coarse-pos']:\n feature_builder = PosFeatureBuilder(args.features)\n elif args.features in Word2VecFeatureBuilder.SUPPORTED_MODELS:\n feature_builder = Word2VecFeatureBuilder(args.features)\n elif args.features == 'concat':\n feature_builder = ConcatFeatureBuilder()\n else:\n raise ValueError(f'Unknown feature builder \"{args.features}\"')\n\n class_mapping = {}\n if args.mappings:\n for mapping in args.mappings:\n source, target = mapping.split(':')\n if target == '':\n target = None\n class_mapping[source] = target\n print(f'Using class mapping {class_mapping}')\n\n print(f'Converting {args.dataset} to networkx graphs...')\n transformed_graphs = process_mrp_to_networkx(args.dataset)\n print('Done!')\n data = process_networkx_to_dgl(transformed_graphs, node_feature_builder=feature_builder, class_mapping=class_mapping)\n\n pickled = pickle.dumps(data)\n print(f'Writing approximately {len(pickled) / 1e6:.1f}MB of processed data to disk...')\n os.makedirs(os.path.dirname(args.target), exist_ok=True)\n with open(args.target, 'wb') as out_file:\n out_file.write(pickled)\n\n print('Done!')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ucca4bpm/data/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":10408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"335059852","text":"from PIL import Image, ImageDraw\nimport optparse\nimport face_recognition\n'''\n打印脸部特征轮廓\n'''\ndef faceFeature(picture):\n\t# 将jpg文件加载到numpy 数组中\n\timage = face_recognition.load_image_file(picture)\n\n\t# 查找图像中所有面部的所有面部特征\n\tface_landmarks_list = face_recognition.face_landmarks(image)\n\n\tprint(\"I found {} face(s) in this photograph.\".format(len(face_landmarks_list)))\n\n\tfor face_landmarks in face_landmarks_list:\n\n\t #打印此图像中每个面部特征的位置\n\t facial_features = [\n\t 'chin',\n\t 'left_eyebrow',\n\t 'right_eyebrow',\n\t 'nose_bridge',\n\t 'nose_tip',\n\t 'left_eye',\n\t 'right_eye',\n\t 'top_lip',\n\t 'bottom_lip'\n\t ]\n\n\t for facial_feature in facial_features:\n\t print(\"The {} in this face has the following points: {}\".format(facial_feature, face_landmarks[facial_feature]))\n\n\t #让我们在图像中描绘出每个人脸特征!\n\t pil_image = Image.fromarray(image)\n\t d = ImageDraw.Draw(pil_image)\n\n\t for facial_feature in facial_features:\n\t d.line(face_landmarks[facial_feature], width=5)\n\n\t pil_image.show()\n\ndef main():\n\tparser = optparse.OptionParser('usage%prog '+'-p ') \n\tparser.add_option('-p', dest='picture', type='string', help='specify picture file') \n\t(options, args) = parser.parse_args() \n\tpicture = options.picture\n\tif picture == None: \n\t\tprint(parser.usage) \n\t\texit(0)\n\tfaceFeature(picture)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"face_recognition/FaceFeature.py","file_name":"FaceFeature.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"72454256","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 21 08:47:32 2020\n\n@author: xavi2\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\narr_pand = np.random.randint(0,10,6).reshape(2,3)\n\ndf1 = pd.DataFrame(arr_pand)\ns1 = df1[0]\ns2 = df1[1]\ns3 = df1[2]\n\ndf1[3] = s1\ndf1[4] = s1 * s2\n\ndatos_fisicos_uno = pd.DataFrame(\n arr_pand,\n columns = [\n 'Estatura (cm)',\n 'Peso (kg)',\n 'Edad (anios)'])\n\ndatos_fisicos_dos = pd.DataFrame(\n arr_pand,\n columns = [\n 'Estatura (cm)',\n 'Peso (kg)',\n 'Edad (anios)'],\n index = [\n 'Rodman',\n 'Xavier'])\n\nserie_peso = datos_fisicos_dos['Peso (kg)']\ndatos_rodman = serie_peso['Rodman']\nprint(serie_peso)\nprint(datos_rodman)\n\ndf1.index = ['Rodman', 'Xavier']\ndf1.index = ['Wendy', 'Carolina']\ndf1.columns = ['A', 'B', 'C', 'D', 'E']\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"03-Pandas/c_dateframes.py","file_name":"c_dateframes.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"368878092","text":"from zeep import Client\nfrom zeep.wsse.username import UsernameToken\nimport xmltodict\n\nimport os\n\nif \"BFT_DEBUG\" in os.environ:\n import logging.config\n\n logging.config.dictConfig({\n 'version': 1,\n 'formatters': {\n 'verbose': {\n 'format': '%(name)s: %(message)s'\n }\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'verbose',\n },\n },\n 'loggers': {\n 'zeep.transports': {\n 'level': 'DEBUG',\n 'propagate': True,\n 'handlers': ['console'],\n },\n }\n })\n\nfrom boardfarm.lib.bft_logging import LoggerMeta\n\nclass FriendlyACS():\n __metaclass__ = LoggerMeta\n log = \"\"\n log_calls = \"\"\n\n model = \"friendly_acs_soap\"\n\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n self.username = self.kwargs['username']\n self.password = self.kwargs['password']\n self.ipaddr = self.kwargs['ipaddr']\n self.wsdl = \"http://\" + self.kwargs['ipaddr'] + \"/ftacsws/acsws.asmx?WSDL\"\n self.client = Client(wsdl=self.wsdl, wsse=UsernameToken(self.username, self.password))\n self.port = self.kwargs.get('port', '80')\n self.log = \"\"\n\n name = \"acs_server\"\n\n def __str__(self):\n return \"FriendlyACS\"\n\n def close(self):\n pass\n\n def get(self, serial_number, param, source=0):\n # source = 0 (CPE), source = 1 (DB)\n ret = self.client.service.FTGetDeviceParameters(devicesn=serial_number, source=source, arraynames=[param])\n if None == ret['Params']:\n return None\n else:\n return ret['Params']['ParamWSDL'][0]['Value']\n\n def set(self, serial_number, attr, value):\n array_of_param = self.client.get_type('{http://www.friendly-tech.com}ArrayOfParam')\n\n arr = array_of_param([{'Name': attr, 'Value': value}])\n\n # TODO: investigate push, endsession, reprovision, priority to make sure they are what we want\n self.client.service.FTSetDeviceParameters(devicesn=serial_number, \\\n arrayparams=arr, \\\n push=True, \\\n endsession=False, \\\n priority=0)\n\n def rpc(self, serial_number, name, content):\n ''' Invoke custom RPC on specific CM'''\n ret = self.client.service.FTRPCInvoke(devicesn=serial_number, rpcname=name, soapcontent=content)\n return xmltodict.parse(ret['Response'])\n\n def rpc_GetParameterAttributes(self, serial_number, name):\n content = '%s' % name\n\n ret = self.rpc(serial_number, name, content)\n\n return ret['cwmp:GetParameterAttributesResponse']['ParameterList']['ParameterAttributeStruct']\n\n def rpc_GetParameterValues(self, serial_number, name):\n content = '%s' % name\n\n ret = self.rpc(serial_number, name, content)\n\n return ret['cwmp:GetParameterValuesResponse']['ParameterList']['ParameterValueStruct']['Value']['#text']\n\n def getcurrent(self, serial_number, param, source=0):\n self.client.service.FTGetDeviceParameters(devicesn=serial_number, source=source, arraynames=[param+'.'])\n\n def rpc_SetParameterAttributes(self, serial_number, name, set_value):\n content = '%s1%s0' %(name, set_value)\n\n self.rpc(serial_number, name, content)\n\n def rpc_AddObject(self, serial_number, obj_name):\n content = '%s.'% obj_name\n self.rpc(serial_number, obj_name, content)\n\n def rpc_DeleteObject(self, serial_number, obj_name):\n content = '%s.' % obj_name\n self.rpc(serial_number, obj_name, content)\n\n def is_online(self, serial_number):\n ret = self.client.service.FTCPEStatus(devicesn=serial_number)\n return ret['Online']\n\nif __name__ == '__main__':\n import sys\n\n if ':' in sys.argv[1]:\n ip = sys.argv[1].split(':')[0]\n port = sys.argv[1].split(':')[1]\n else:\n ip = sys.argv[1]\n port = 80\n\n acs = FriendlyACS(ipaddr=ip, port=port, username=sys.argv[2], password=sys.argv[3])\n\n ret = acs.rpc_GetParameterAttributes('DEAP815610DA', 'Device.WiFi.SSID.1.SSID')\n print(ret['Notification'])\n\n ret = acs.get('DEAP815610DA', 'Device.DeviceInfo.SoftwareVersion')\n print(ret)\n\n ret = acs.get ('DEAP815610DA', 'Device.WiFi.SSID.1.SSID')\n print(ret)\n","sub_path":"boardfarm/devices/friendly_acs_soap.py","file_name":"friendly_acs_soap.py","file_ext":"py","file_size_in_byte":5591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"192381249","text":"from twisted.internet.defer import inlineCallbacks\nfrom twisted.internet.task import LoopingCall\n\nfrom bravo.blocks import blocks, items, furnace_fuel, unstackable\nfrom bravo.inventory import Slot\nfrom bravo.inventory.windows import FurnaceWindow\n\n# TODO: move this out of the module into plug-in\nfurnace_recipes = {\n blocks[\"gold-ore\"].slot : Slot(items[\"gold-ingot\"].slot, 0, 1),\n blocks[\"iron-ore\"].slot : Slot(items[\"iron-ingot\"].slot, 0, 1),\n blocks[\"diamond-ore\"].slot : Slot(items[\"diamond\"].slot, 0, 1),\n blocks[\"log\"].slot : Slot(items[\"coal\"].slot, 1, 1), # charcoal\n blocks[\"cactus\"].slot : Slot(items[\"dye\"].slot, 2, 1), # green dye\n blocks[\"sand\"].slot : Slot(blocks[\"glass\"].slot, 0, 1),\n blocks[\"cobblestone\"].slot : Slot(blocks[\"stone\"].slot, 0, 1),\n items[\"clay-balls\"].slot : Slot(items[\"clay-brick\"].slot, 0, 1),\n items[\"raw-porkchop\"].slot : Slot(items[\"cooked-porkchop\"].slot, 0, 1),\n items[\"raw-fish\"].slot : Slot(items[\"cooked-fish\"].slot, 0, 1)\n}\n\nclass FurnaceManager(object):\n\n def __init__(self, factory):\n self.factory = factory\n self.furnaces = {}\n self.cleanup_timer = LoopingCall(self.cleanup)\n\n def start(self):\n \"\"\"\n Enable this manager.\n\n While this manager is running, furnaces will be reaped every 5\n minutes.\n \"\"\"\n\n self.cleanup_timer.start(300)\n\n def stop(self):\n self.cleanup_timer.stop()\n\n @inlineCallbacks\n def update(self, coords):\n # We've got informed that furnace content is changed\n if coords not in self.furnaces:\n bigx, smallx, bigz, smallz, y = coords\n chunk = yield self.factory.world.request_chunk(bigx, bigz)\n tile = chunk.tiles[(smallx, y, smallz)]\n self.furnaces[coords] = FurnaceProcess(tile, coords)\n self.furnaces[coords].factory = self.factory\n self.furnaces[coords].update()\n\n def remove(self, coords):\n if coords in self.furnaces:\n del(self.furnaces[coords])\n\n def cleanup(self):\n # remove processes that do not run\n for c in self.furnaces.keys():\n if not self.furnaces[c].running:\n self.remove(c)\n\nclass FurnaceProcess(object):\n '''\n NOTE: Our furnace process doesn't operate with world ticks.\n We do updates twice per second. It's our UI update rate.\n '''\n def __init__(self, tile, coords):\n self.tile = tile\n self.coords = coords\n self.running = False\n self.burning = LoopingCall(self.burn)\n\n def update(self):\n if not self.running:\n if self.hasFuel and self.canCraft:\n self.tile.burntime = 0\n self.tile.cooktime = 0\n self.burning.start(0.5) # start burning loop\n\n def burn(self):\n # -----------------------------\n # --- item crafting ---\n # -----------------------------\n if self.canCraft:\n self.tile.cooktime += 1\n # Notchian time is ~9.25-9.50 sec.\n if self.tile.cooktime == 20: # cooked!\n source = self.tile.inventory.crafting[0]\n product = furnace_recipes[source.primary]\n self.tile.inventory.crafting[0] = source.decrement()\n if self.tile.inventory.crafted[0] is None:\n self.tile.inventory.crafted[0] = product\n else:\n item = self.tile.inventory.crafted[0]\n self.tile.inventory.crafted[0] = item.increment(product.quantity)\n self.update_all_windows_slot(0, self.tile.inventory.crafting[0])\n self.update_all_windows_slot(2, self.tile.inventory.crafted[0])\n self.tile.cooktime = 0\n else:\n self.tile.cooktime = 0\n\n # ----------------------------\n # --- fuel consume ---\n # ----------------------------\n if self.tile.burntime == 0:\n if self.hasFuel and self.canCraft: # burn next portion of the fuel\n fuel = self.tile.inventory.fuel[0]\n self.tile.burntime = self.burn_max = furnace_fuel[fuel.primary]\n self.tile.inventory.fuel[0] = fuel.decrement()\n if not self.running:\n self.on_off(True)\n self.update_all_windows_slot(1, self.tile.inventory.fuel[0])\n else: # out of fuel or no need to burn more\n self.burning.stop()\n self.on_off(False)\n # reset cook time\n self.tile.cooktime = 0\n self.update_all_windows_progress(0, 0)\n return\n self.tile.burntime -= 1\n\n # ----------------------------\n # --- update progress bars ---\n # ----------------------------\n cook_progress = 185 * self.tile.cooktime / 19\n burn_progress = 250 * self.tile.burntime / self.burn_max\n self.update_all_windows_progress(0, cook_progress)\n self.update_all_windows_progress(1, burn_progress)\n\n def on_off(self, state):\n self.running = state\n bigx, smallx, bigz, smallz, y = self.coords\n block = state and blocks[\"burning-furnace\"] or blocks[\"furnace\"]\n d = self.factory.world.request_chunk(bigx, bigz)\n @d.addCallback\n def replace_furnace_block(chunk):\n chunk.set_block((smallx, y, smallz), block.slot)\n self.factory.flush_chunk(chunk)\n\n def update_all_windows_slot(self, slot, item):\n # update all opened windows\n for p in self.factory.protocols.itervalues():\n if p.windows and type(p.windows[-1]) == FurnaceWindow:\n window = p.windows[-1]\n if window.coords == self.coords:\n if item is None:\n p.write_packet(\"window-slot\",\n wid=window.wid, slot=slot, primary=-1)\n else:\n p.write_packet(\"window-slot\",\n wid=window.wid, slot=slot, primary=item.primary,\n secondary=item.secondary, count=item.quantity)\n\n def update_all_windows_progress(self, bar, value):\n # update all opened windows\n for p in self.factory.protocols.itervalues():\n if p.windows and type(p.windows[-1]) == FurnaceWindow:\n window = p.windows[-1]\n if window.coords == self.coords:\n p.write_packet(\"window-progress\", wid=window.wid,\n bar=bar, progress=value)\n\n @property\n def hasFuel(self):\n # if the furnace hase something to burn\n if self.tile.inventory.fuel[0] is None:\n return False\n else:\n return self.tile.inventory.fuel[0].primary in furnace_fuel\n\n @property\n def canCraft(self):\n # if have somethig to craft from...\n if self.tile.inventory.crafting[0] is None:\n return False\n if self.tile.inventory.crafting[0].primary in furnace_recipes:\n #...and has space for it\n if self.tile.inventory.crafted[0] is None:\n return True\n else:\n crafting = self.tile.inventory.crafting[0]\n crafted = self.tile.inventory.crafted[0]\n if furnace_recipes[crafting.primary][0] != crafted.primary:\n return False\n elif crafted.primary in unstackable:\n return False\n elif crafted.quantity + furnace_recipes[crafting.primary].quantity > 64:\n return False\n else:\n return True\n else:\n return False\n","sub_path":"bravo/utilities/furnace.py","file_name":"furnace.py","file_ext":"py","file_size_in_byte":7717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"156232353","text":"from __future__ import with_statement, division\n\nimport ij.process as process\nfrom ij import ImageStack\n\ntry:\n import sc.fiji.i5d.Image5D\n import sc.fiji.i5d as i5d\nexcept:\n import i5d.Image5D\n import i5d as i5d\n\nimport struct\n\nfrom loci.formats import ImageReader , MetadataTools, IFormatWriter, FormatTools\nimport ome.xml.model.enums.DimensionOrder as DimensionOrder\nimport ome.xml.model.primitives.PositiveInteger as PositiveInteger\nimport ome.xml.model.primitives.NonNegativeInteger as NonNegativeInteger\nimport ome.xml.model.enums.PixelType as PixelType\nfrom loci.formats import ImageWriter, ImageReader\nfrom loci.plugins import BF\nimport ome.units.quantity.Length as Length\nimport ome.units.UNITS as units\n\nimport loci.common.DataTools as DataTools\n\nimport xml.etree.ElementTree as et\n\n\ndef convert_imc_to_image(imc_acquisition):\n \"\"\"\n Load an MCD and convert it to a image5d Tiff\n :param filename: Filename of the MCD\n :return: an image5d image\n \"\"\"\n ac_id = imc_acquisition.image_ID\n print('Contstruct image from data: %s' %ac_id)\n\n img_channels = imc_acquisition.n_channels\n channel_names = imc_acquisition.channel_metals\n channel_labels = imc_acquisition.channel_labels\n\n img_data = imc_acquisition.get_img_stack_cyx()\n\n if channel_labels is not None:\n channel_ids = [lab + '_' + name for name, lab in\n zip(channel_names, channel_labels)]\n else:\n channel_ids = channel_names\n print('Add planes to stack:')\n imgstack = stack_to_imagestack(img_data, channel_ids=channel_ids)\n\n file_name = imc_acquisition.original_filename.replace('.mcd','')\n file_name = file_name.replace('.txt', '')\n description = imc_acquisition.image_description\n if description is not None:\n file_name = '_'.join((file_name,'a'+ac_id, 'd'+description))\n else:\n file_name = '_'.join((file_name, 'a' + ac_id))\n\n i5d_img = get_image5d(file_name, imgstack, channel_ids)\n\n i5d_img.setDefaultColors()\n print('finished image: %s' %ac_id)\n\n return i5d_img\n\n\ndef stack_to_imagestack(cxy_stack, img_stack=None, channel_ids=None):\n \"\"\"\n\n :param cxy_stack:\n :param img_stack:\n :return:\n \"\"\"\n\n c, x, y = (len(cxy_stack), len(cxy_stack[0]), len(cxy_stack[0][0]))\n if img_stack is None:\n img_stack = ImageStack(y, x)\n\n for i in range(c):\n cur_proc = process.FloatProcessor(cxy_stack[i])\n cur_proc.flipVertical()\n cur_proc = cur_proc.rotateRight()\n if channel_ids is None:\n img_stack.addSlice(cur_proc)\n else:\n img_stack.addSlice(channel_ids[i], cur_proc)\n\n return img_stack\n\n\ndef get_image5d(imgName, img_stack, channel_names):\n \"\"\"\n\n :param imgName:\n :param img_stack:\n :param channel_names:\n :return:\n \"\"\"\n\n nchannels = len(channel_names)\n for i, lab in enumerate(channel_names):\n img_stack.setSliceLabel(lab, i+1)\n i5dimg = i5d.Image5D(imgName, img_stack, nchannels,1,1)\n\n for i,cid in enumerate(channel_names):\n i5dimg.getChannelCalibration(i+1).setLabel(str(cid))\n\n i5dimg.setDefaultColors()\n return i5dimg\n\ndef load_ome_img(file_name):\n \"\"\"\n\n :param file_name:\n :return:\n \"\"\"\n imps = BF.openImagePlus(file_name)\n imag = imps[0]\n # parse metadata\n reader = ImageReader()\n omeMeta = MetadataTools.createOMEXMLMetadata()\n reader.setMetadataStore(omeMeta)\n reader.setId(file_name)\n print(omeMeta)\n reader.close()\n\n return (imag, omeMeta)\n\ndef generate_ome_fromimc(imc_acquisition):\n \"\"\"\n\n :param imc_acquisition:\n :return:\n \"\"\"\n\n y, x, c = imc_acquisition.shape\n print(x,y,c)\n metadata = MetadataTools.createOMEXMLMetadata()\n filename= '/home/vitoz/temp/test.ome.tiff'\n MetadataTools.populateMetadata(metadata, 0, filename, True, \"XYZTC\",\n FormatTools.getPixelTypeString(6), x, y, 1, c, 1, 1)\n if imc_acquisition.origin == 'mcd':\n ac_id = imc_acquisition.image_ID\n meta_xml = et.XML(imc_acquisition.original_metadata)\n ns = '{'+meta_xml.tag.split('}')[0].strip('{')+'}'\n\n channel_xml = [channel_xml for channel_xml in meta_xml.findall(ns + 'AcquisitionChannel')\n if channel_xml.find(ns + 'AcquisitionID').text == ac_id]\n\n ac_xml = [tx for tx in meta_xml.findall(ns + 'Acquisition')\n if tx.find(ns + 'ID').text == ac_id][0]\n # AcquisitionDate = ac_xml.find(ns+'StartTimeStamp').text\n # Description = ac_xml.find(ns+'Description').text\n # AblationPower = ac_xml.find(ns + 'AblationPower').text\n # AblationDistanceBetweenShots = ac_xml.find(ns + 'AblationDistanceBetweenShots').text\n # AblationFrequency = ac_xml.find(ns + 'AblationFrequency').text\n # ROIID = ac_xml.find(ns + 'ROIID').text\n # OrderNumber = ac_xml.find(ns + 'OrderNumber').text\n # SignalType = ac_xml.find(ns + 'SignalType').text\n # DataStartOffset = ac_xml.find(ns + 'DataStartOffset').text\n # DataEndOffset = ac_xml.find(ns + 'DataEndOffset').text\n # StartTimeStamp = ac_xml.find(ns + 'StartTimeStamp').text\n # EndTimeStamp = ac_xml.find(ns + 'EndTimeStamp').text\n # SegmentDataFormat = ac_xml.find(ns + 'SegmentDataFormat').text\n # ValueBytes = ac_xml.find(ns + 'ValueBytes').text\n #\n # chan_order = [int(cxml.find(ns+'OrderNumber').text) for cxml in channel_xml]\n metadata.setImageID(ac_id,0 )\n metadata.setImageName(ac_id,0)\n metadata.setPixelsDimensionOrder(DimensionOrder.XYCZT, 0)\n metadata.setPixelsSizeX(PositiveInteger(x), 0)\n metadata.setPixelsSizeY(PositiveInteger(y), 0)\n metadata.setPixelsSizeC(PositiveInteger(c), 0)\n metadata.setPixelsSizeZ(PositiveInteger(1), 0)\n metadata.setPixelsSizeT(PositiveInteger(1), 0)\n\n metadata.setPixelsPhysicalSizeX(Length(1, units.MICROM), 0)\n metadata.setPixelsPhysicalSizeY(Length(1, units.MICROM), 0)\n metadata.setPixelsPhysicalSizeZ(Length(1, units.MICROM), 0)\n\n metadata.setPixelsID(ac_id, 0)\n metadata.setPixelsType(PixelType.FLOAT, 0)\n metadata.setPixelsInterleaved(False, 0)\n\n # metadata.setTiffDataFirstC(NonNegativeInteger(0), 0, 0)\n # metadata.setTiffDataFirstZ(NonNegativeInteger(0), 0, 0)\n # metadata.setTiffDataFirstT(NonNegativeInteger(0), 0, 0)\n print(c)\n for i in range(c):\n metadata.setChannelSamplesPerPixel(PositiveInteger(1), 0, i)\n for cxml in channel_xml:\n cnr = int(cxml.find(ns+'OrderNumber').text)-3\n if cnr >=0:\n name = cxml.find(ns + 'ChannelName').text\n label = cxml.find(ns + 'ChannelLabel')\n if label.text is None:\n label = name\n else:\n print(label.text)\n label = label.text\n print(label)\n print(name)\n cid = '_'.join([label, name])\n cid = cid.strip('(').strip(')')\n name = name.replace('(','').strip(')')\n metadata.setChannelFluor(name, 0, cnr)\n metadata.setChannelName(cid, 0, cnr)\n metadata.setChannelID(cid, 0, cnr)\n # for i in range(c):\n # metadata.setPlaneTheC(NonNegativeInteger(i),0,i)\n # metadata.setPlaneTheZ(NonNegativeInteger(0), 0, i)\n # metadata.setPlaneTheT(NonNegativeInteger(0), 0, i)\n\n\n return metadata\n\n else:\n ac_id = imc_acquisition.image_ID\n metadata.setImageID(ac_id, 0)\n metadata.setImageName(ac_id, 0)\n metadata.setPixelsDimensionOrder(DimensionOrder.XYCZT, 0)\n metadata.setPixelsSizeX(PositiveInteger(x), 0)\n metadata.setPixelsSizeY(PositiveInteger(y), 0)\n metadata.setPixelsSizeC(PositiveInteger(c), 0)\n metadata.setPixelsSizeZ(PositiveInteger(1), 0)\n metadata.setPixelsSizeT(PositiveInteger(1), 0)\n\n metadata.setPixelsPhysicalSizeX(Length(1, units.MICROM), 0)\n metadata.setPixelsPhysicalSizeY(Length(1, units.MICROM), 0)\n metadata.setPixelsPhysicalSizeZ(Length(1, units.MICROM), 0)\n\n metadata.setPixelsID(ac_id, 0)\n metadata.setPixelsType(PixelType.FLOAT, 0)\n metadata.setPixelsInterleaved(False, 0)\n\n # metadata.setTiffDataFirstC(NonNegativeInteger(0), 0, 0)\n # metadata.setTiffDataFirstZ(NonNegativeInteger(0), 0, 0)\n # metadata.setTiffDataFirstT(NonNegativeInteger(0), 0, 0)\n print(c)\n for i in range(c):\n metadata.setChannelSamplesPerPixel(PositiveInteger(1), 0, i)\n for cnr, metal, label in zip(range(c), imc_acquisition.channel_metals, imc_acquisition.channel_labels):\n metadata.setChannelFluor(metal, 0, cnr)\n metadata.setChannelName(label, 0, cnr)\n metadata.setChannelID(label, 0, cnr)\n\n return metadata\n\n\ndef save_ome_tiff(filename, image, metadata):\n reader = ImageReader()\n writer = ImageWriter()\n writer.setMetadataRetrieve(metadata)\n writer.setId(filename)\n nchan = image.getNChannels()\n stack = image.getImageStack()\n print(image.getStackSize())\n for i in range(nchan):\n writer.setSeries(0)\n process = stack.getProcessor(i+1)\n pixels = process.getPixels()\n pixels = DataTools.floatsToBytes(pixels, True)\n writer.saveBytes(i, pixels)\n writer.close()\n\n\n\n\n","sub_path":"imctools/imagej/library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":9472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"19714615","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport re\nimport logging\nfrom collections import namedtuple\nimport pytest\nimport datetime\n\nimport produtil\n\nfrom metplus.wrappers.regrid_data_plane_wrapper import RegridDataPlaneWrapper\nfrom metplus.util import met_util as util\nfrom metplus.util import time_util\n\n# --------------------TEST CONFIGURATION and FIXTURE SUPPORT -------------\n#\n# The test configuration and fixture support the additional configuration\n# files used in METplus\n# !!!!!!!!!!!!!!!\n# !!!IMPORTANT!!!\n# !!!!!!!!!!!!!!!\n# The following two methods should be included in ALL pytest tests for METplus.\n#\n#\n#def pytest_addoption(parser):\n# parser.addoption(\"-c\", action=\"store\", help=\" -c \")\n\n\n# @pytest.fixture\n#def cmdopt(request):\n# return request.config.getoption(\"-c\")\n\n\n# -----------------FIXTURES THAT CAN BE USED BY ALL TESTS----------------\n#@pytest.fixture\ndef rdp_wrapper(metplus_config):\n \"\"\"! Returns a default RegridDataPlane with /path/to entries in the\n metplus_system.conf and metplus_runtime.conf configuration\n files. Subsequent tests can customize the final METplus configuration\n to over-ride these /path/to values.\"\"\"\n\n config = metplus_config()\n config.set('config', 'DO_NOT_RUN_EXE', True)\n return RegridDataPlaneWrapper(config)\n\n# ------------------------ TESTS GO HERE --------------------------\n\n# conf_dict is produtil config items set before creating grid_stat wrapper instance\n# out_dict is grid_stat wrapper c_dict values set by initialization\n@pytest.mark.parametrize(\n 'conf_dict, expected_field_info_list', [\n\n # 0) 1 item from var list\n ({'OBS_VAR1_NAME': 'APCP',\n 'OBS_VAR1_LEVELS': \"A06\"},\n [{'index': '1', 'obs_name': 'APCP', 'obs_level': 'A06'}]\n ),\n\n # 1) 1 item with level replaced from wrapper-specific\n ({'OBS_VAR1_NAME': 'P06M_NONE',\n 'OBS_VAR1_LEVELS': \"\\\"(*,*)\\\"\",\n 'OBS_REGRID_DATA_PLANE_VAR1_INPUT_LEVEL': '\"({valid?fmt=%Y%m%d_%H%M%S},*,*)\"'},\n [{'index': '1', 'obs_name': 'P06M_NONE', 'obs_level': '\"(20180201_000000,*,*)\"'},\n ]\n ),\n\n # 2) 2 items from var list\n ({'OBS_VAR1_NAME': 'APCP',\n 'OBS_VAR1_LEVELS': \"A06\",\n 'OBS_VAR2_NAME': 'ACPCP',\n 'OBS_VAR2_LEVELS': \"A03\",},\n [{'index': '1', 'obs_name': 'APCP', 'obs_level': 'A06'},\n {'index': '2', 'obs_name': 'ACPCP', 'obs_level': 'A03'},\n ]\n ),\n\n # 3) 2 items from var list, 3rd from wrapper-specific\n ({'OBS_VAR1_NAME': 'APCP',\n 'OBS_VAR1_LEVELS': \"A06\",\n 'OBS_VAR2_NAME': 'ACPCP',\n 'OBS_VAR2_LEVELS': \"A03\",\n 'OBS_REGRID_DATA_PLANE_VAR3_INPUT_FIELD_NAME': 'NAME_FOR_3'},\n [{'index': '1', 'obs_name': 'APCP', 'obs_level': 'A06'},\n {'index': '2', 'obs_name': 'ACPCP', 'obs_level': 'A03'},\n {'index': '3', 'obs_name': 'NAME_FOR_3'},\n ]\n ),\n\n # 4) 3 items from var list, 1 replaced and 4th from wrapper-specific\n ({'OBS_VAR1_NAME': 'APCP',\n 'OBS_VAR1_LEVELS': \"A06\",\n 'OBS_VAR2_NAME': 'ACPCP',\n 'OBS_VAR2_LEVELS': \"A03\",\n 'OBS_VAR3_NAME': 'ACPCP',\n 'OBS_VAR3_LEVELS': \"A02\",\n 'OBS_REGRID_DATA_PLANE_VAR3_INPUT_FIELD_NAME': 'NAME_FOR_3',\n 'OBS_REGRID_DATA_PLANE_VAR4_INPUT_FIELD_NAME': 'NAME_FOR_4',\n 'OBS_REGRID_DATA_PLANE_VAR4_INPUT_LEVEL': 'LEVEL_FOR_4'},\n [{'index': '1', 'obs_name': 'APCP', 'obs_level': 'A06'},\n {'index': '2', 'obs_name': 'ACPCP', 'obs_level': 'A03'},\n {'index': '3', 'obs_name': 'NAME_FOR_3', 'obs_level': 'A02'},\n {'index': '4', 'obs_name': 'NAME_FOR_4', 'obs_level': 'LEVEL_FOR_4'},\n ]\n ),\n\n # 5) 1 item from var list add output name\n ({'OBS_VAR1_NAME': 'APCP',\n 'OBS_VAR1_LEVELS': \"A06\",\n 'OBS_REGRID_DATA_PLANE_VAR1_OUTPUT_FIELD_NAME': 'OUT_NAME',},\n [{'index': '1', 'obs_name': 'APCP', 'obs_level': 'A06', 'obs_output_name': 'OUT_NAME'}]\n ),\n\n # 6) 3 items from var list, 1 replaced and 4th from wrapper-specific, add output name\n ({'OBS_VAR1_NAME': 'APCP',\n 'OBS_VAR1_LEVELS': \"A06\",\n 'OBS_VAR2_NAME': 'ACPCP',\n 'OBS_VAR2_LEVELS': \"A03\",\n 'OBS_VAR3_NAME': 'ACPCP',\n 'OBS_VAR3_LEVELS': \"A02\",\n 'OBS_REGRID_DATA_PLANE_VAR3_INPUT_FIELD_NAME': 'NAME_FOR_3',\n 'OBS_REGRID_DATA_PLANE_VAR4_INPUT_FIELD_NAME': 'NAME_FOR_4',\n 'OBS_REGRID_DATA_PLANE_VAR4_INPUT_LEVEL': 'LEVEL_FOR_4',\n 'OBS_REGRID_DATA_PLANE_VAR4_OUTPUT_FIELD_NAME': 'OUT_NAME_4'},\n [{'index': '1', 'obs_name': 'APCP', 'obs_level': 'A06'},\n {'index': '2', 'obs_name': 'ACPCP', 'obs_level': 'A03'},\n {'index': '3', 'obs_name': 'NAME_FOR_3', 'obs_level': 'A02'},\n {'index': '4', 'obs_name': 'NAME_FOR_4', 'obs_level': 'LEVEL_FOR_4', 'obs_output_name': 'OUT_NAME_4'},\n ]\n ),\n ]\n)\n\ndef test_get_field_info_list(metplus_config, conf_dict, expected_field_info_list):\n config = metplus_config()\n\n data_type = 'OBS'\n\n for key, value in conf_dict.items():\n config.set('config', key, value)\n\n input_dict = {'valid': datetime.datetime.strptime(\"201802010000\", '%Y%m%d%H%M'),\n 'lead': 0}\n time_info = time_util.ti_calculate(input_dict)\n\n var_list = util.parse_var_list(config, time_info, data_type=data_type)\n\n rdp = RegridDataPlaneWrapper(config)\n\n field_info_list = rdp.get_field_info_list(var_list, data_type, time_info)\n print(f\"FIELD INFO LIST: {field_info_list}\")\n print(f\"EXPECTED FIELD INFO LIST: {expected_field_info_list}\")\n is_good = True\n if len(field_info_list) != len(expected_field_info_list):\n assert(False)\n\n for actual_field, expected_field in zip(field_info_list, expected_field_info_list):\n for key, value in expected_field.items():\n if actual_field[key] != value:\n print(f\"{actual_field[key]} not equal to {value}\")\n is_good = False\n\n# field info is the input dictionary with name and level info to parse\n# expected_arg is the argument that should be set by the function\n# note: did not include OBS because they are handled the same way as FCST\n@pytest.mark.parametrize(\n 'field_info, expected_arg', [\n\n # 0) name/level\n ({'fcst_name': 'F_NAME',\n 'fcst_level': \"\\\"(1,*,*)\\\"\"},\n \"-field 'name=\\\"F_NAME\\\"; level=\\\"(1,*,*)\\\";'\"\n ),\n\n # 1) python embedding script\n ({'fcst_name': 'my_script.py some args',\n 'fcst_level': \"\"},\n \"-field 'name=\\\"my_script.py some args\\\";'\"\n ),\n\n # 2) name/level\n ({'fcst_name': 'F_NAME',\n 'fcst_level': \"A06\"},\n \"-field 'name=\\\"F_NAME\\\"; level=\\\"A06\\\";'\"\n ),\n\n # 3) name, no level\n ({'fcst_name': 'F_NAME',\n 'fcst_level': \"\"},\n \"-field 'name=\\\"F_NAME\\\";'\"\n ),\n\n # 4) python embedding script\n ({'fcst_name': 'my_script.py some args',\n 'fcst_level': \"\"},\n \"-field 'name=\\\"my_script.py some args\\\";'\"\n ),\n ]\n)\n\ndef test_set_field_command_line_arguments(metplus_config, field_info, expected_arg):\n data_type = 'FCST'\n\n config = metplus_config()\n\n rdp = RegridDataPlaneWrapper(config)\n\n rdp.set_field_command_line_arguments(field_info, data_type)\n assert(rdp.args[0] == expected_arg)\n\n@pytest.mark.parametrize(\n 'field_info, input_name, expected_name', [\n\n # 0) use fcst name\n ({'fcst_output_name': 'F_NAME'},\n \"INPUT_NAME\",\n 'F_NAME',\n ),\n\n # 1) empty fcst name, use input name\n ({'fcst_output_name': ''},\n \"INPUT_NAME\",\n 'INPUT_NAME',\n ),\n\n # 2) no fcst name, use input name\n ({'fcst_name': 'F_NAME'},\n \"INPUT_NAME\",\n 'INPUT_NAME',\n ),\n ]\n)\ndef test_get_output_name(metplus_config, field_info, input_name, expected_name):\n data_type = 'FCST'\n\n config = metplus_config()\n rdp = RegridDataPlaneWrapper(config)\n\n assert(rdp.get_output_name(field_info, data_type, input_name) == expected_name)\n\ndef test_run_rdp_once_per_field(metplus_config):\n data_type = 'FCST'\n\n input_dict = {'valid': datetime.datetime.strptime(\"201802010000\",'%Y%m%d%H%M'),\n 'lead': 0}\n time_info = time_util.ti_calculate(input_dict)\n\n var_list = [{'index': '1', 'fcst_name': 'FNAME1', 'fcst_level': 'A06'},\n {'index': '2', 'fcst_name': 'FNAME2', 'fcst_level': 'A03', 'fcst_output_name': 'OUTNAME2'},\n ]\n\n wrap = rdp_wrapper(metplus_config)\n wrap.c_dict['ONCE_PER_FIELD'] = True\n wrap.c_dict['FCST_OUTPUT_TEMPLATE'] = '{valid?fmt=%Y%m%d%H}_accum{level?fmt=%2H}.nc'\n\n wrap.c_dict['FCST_INPUT_TEMPLATE'] = '{valid?fmt=%Y%m%d%H}_ZENITH'\n wrap.c_dict['METHOD'] = 'BUDGET'\n wrap.c_dict['WIDTH'] = 2\n wrap.c_dict['VERIFICATION_GRID'] = 'VERIF_GRID'\n wrap.c_dict['FCST_OUTPUT_DIR'] = os.path.join(wrap.config.getdir('OUTPUT_BASE'),\n 'RDP_test')\n\n wrap.run_at_time_once(time_info, var_list, data_type)\n\n expected_cmds = [f\"{wrap.app_path} -v 2 -method BUDGET -width 2 -field 'name=\\\"FNAME1\\\"; \"\n \"level=\\\"A06\\\";' -name FNAME1 2018020100_ZENITH \\\"VERIF_GRID\\\" \"\n f\"{wrap.config.getdir('OUTPUT_BASE')}/RDP_test/2018020100_accum06.nc\",\n f\"{wrap.app_path} -v 2 -method BUDGET -width 2 -field 'name=\\\"FNAME2\\\"; \"\n \"level=\\\"A03\\\";' -name OUTNAME2 2018020100_ZENITH \\\"VERIF_GRID\\\" \"\n f\"{wrap.config.getdir('OUTPUT_BASE')}/RDP_test/2018020100_accum03.nc\",\n ]\n\n test_passed = True\n\n if len(wrap.all_commands) != len(expected_cmds):\n print(\"Number of commands run is not the same as expected\")\n print(f\"Actual commands: {wrap.all_commands}\\n\")\n print(f\"Expected commands: {expected_cmds}\\n\")\n assert(False)\n\n for (cmd, _), expected_cmd in zip(wrap.all_commands, expected_cmds):\n print(f\" ACTUAL:{cmd}\")\n print(f\"EXPECTED:{expected_cmd}\")\n if cmd != expected_cmd:\n test_passed = False\n\n assert(test_passed)\n\ndef test_run_rdp_all_fields(metplus_config):\n data_type = 'FCST'\n\n input_dict = {'valid': datetime.datetime.strptime(\"201802010000\",'%Y%m%d%H%M'),\n 'lead': 0}\n time_info = time_util.ti_calculate(input_dict)\n\n var_list = [{'index': '1', 'fcst_name': 'FNAME1', 'fcst_level': 'A06'},\n {'index': '2', 'fcst_name': 'FNAME2', 'fcst_level': 'A03', 'fcst_output_name': 'OUTNAME2'},\n ]\n\n wrap = rdp_wrapper(metplus_config)\n wrap.c_dict['ONCE_PER_FIELD'] = False\n wrap.c_dict['FCST_OUTPUT_TEMPLATE'] = '{valid?fmt=%Y%m%d%H}_ALL.nc'\n\n wrap.c_dict['FCST_INPUT_TEMPLATE'] = '{valid?fmt=%Y%m%d%H}_ZENITH'\n wrap.c_dict['METHOD'] = 'BUDGET'\n wrap.c_dict['WIDTH'] = 2\n wrap.c_dict['VERIFICATION_GRID'] = 'VERIF_GRID'\n wrap.c_dict['FCST_OUTPUT_DIR'] = os.path.join(wrap.config.getdir('OUTPUT_BASE'),\n 'RDP_test')\n\n wrap.run_at_time_once(time_info, var_list, data_type)\n\n expected_cmds = [f\"{wrap.app_path} -v 2 -method BUDGET -width 2 -field 'name=\\\"FNAME1\\\"; \"\n \"level=\\\"A06\\\";' -field 'name=\\\"FNAME2\\\"; level=\\\"A03\\\";' \"\n \"-name FNAME1,OUTNAME2 2018020100_ZENITH \\\"VERIF_GRID\\\" \"\n f\"{wrap.config.getdir('OUTPUT_BASE')}/RDP_test/2018020100_ALL.nc\",\n ]\n\n test_passed = True\n\n if len(wrap.all_commands) != len(expected_cmds):\n print(\"Number of commands run is not the same as expected\")\n assert(False)\n\n for (cmd, _), expected_cmd in zip(wrap.all_commands, expected_cmds):\n print(f\" ACTUAL:{cmd}\")\n print(f\"EXPECTED:{expected_cmd}\")\n if cmd != expected_cmd:\n test_passed = False\n\n assert(test_passed)\n\ndef test_set_command_line_arguments(metplus_config):\n test_passed = True\n wrap = rdp_wrapper(metplus_config)\n\n expected_args = ['-width 1',]\n\n wrap.set_command_line_arguments()\n if wrap.args != expected_args:\n test_passed = False\n print(\"Test 0 failed\")\n print(f\"ARGS: {wrap.args}\")\n print(f\"EXP: {expected_args}\")\n\n wrap.c_dict['GAUSSIAN_DX'] = 2\n\n expected_args = ['-width 1',\n '-gaussian_dx 2',\n ]\n\n wrap.args.clear()\n\n wrap.set_command_line_arguments()\n if wrap.args != expected_args:\n test_passed = False\n print(\"Test 1 failed\")\n print(f\"ARGS: {wrap.args}\")\n print(f\"EXP: {expected_args}\")\n\n wrap.args.clear()\n\n wrap.c_dict['METHOD'] = 'BUDGET'\n\n expected_args = ['-method BUDGET',\n '-width 1',\n '-gaussian_dx 2',\n ]\n\n wrap.set_command_line_arguments()\n if wrap.args != expected_args:\n test_passed = False\n print(\"Test 2 failed\")\n print(f\"ARGS: {wrap.args}\")\n print(f\"EXP: {expected_args}\")\n\n wrap.args.clear()\n\n wrap.c_dict['GAUSSIAN_RADIUS'] = 3\n\n expected_args = ['-method BUDGET',\n '-width 1',\n '-gaussian_dx 2',\n '-gaussian_radius 3',\n ]\n\n wrap.set_command_line_arguments()\n if wrap.args != expected_args:\n test_passed = False\n print(\"Test 3 failed\")\n print(f\"ARGS: {wrap.args}\")\n print(f\"EXP: {expected_args}\")\n\n wrap.args.clear()\n\n wrap.c_dict['WIDTH'] = 4\n\n expected_args = ['-method BUDGET',\n '-width 4',\n '-gaussian_dx 2',\n '-gaussian_radius 3',\n ]\n\n wrap.set_command_line_arguments()\n if wrap.args != expected_args:\n test_passed = False\n print(\"Test 4 failed\")\n print(f\"ARGS: {wrap.args}\")\n print(f\"EXP: {expected_args}\")\n\n wrap.args.clear()\n\n assert(test_passed)\n","sub_path":"internal_tests/pytests/regrid_data_plane/test_regrid_data_plane.py","file_name":"test_regrid_data_plane.py","file_ext":"py","file_size_in_byte":14207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"607066046","text":"#!/usr/bin/env python\n# encoding: UTF-8\n\n\"\"\"\n This file is part of commix (@commixproject) tool.\n Copyright (c) 2015 Anastasios Stasinopoulos (@ancst).\n https://github.com/stasinopoulos/commix\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n For more see the file 'readme/COPYING' for copying permission.\n\"\"\"\n\nimport re\nimport base64\n\nfrom src.utils import menu\n\n\"\"\"\n Check for added headers.\n\"\"\"\n\ndef do_check(request):\n \n # Check if defined any HTTP Host header.\n if menu.options.host:\n Host = menu.options.host\n request.add_header('Host', Host)\n \n # Check if defined any HTTP Referer header.\n if menu.options.referer:\n Referer = menu.options.agent\n request.add_header('Referer', Referer)\n \n # Check if defined any HTTP User-Agent header.\n if menu.options.agent:\n Agent = menu.options.agent\n request.add_header('User-Agent', Agent)\n \n # Check if defined any HTTP Cookie header.\n if menu.options.cookie:\n Cookie = menu.options.cookie\n request.add_header('Cookie', Cookie)\n\n # Check if defined any HTTP Basic Authentication credentials.\n if menu.options.auth_cred:\n b64_string = base64.encodestring(menu.options.auth_cred).replace('\\n', '')\n request.add_header(\"Authorization\", \"Basic \" + b64_string +\"\")\n \n # Check if defined any extra HTTP headers.\n if menu.options.headers:\n extra_headers = menu.options.headers\n extra_headers = extra_headers.split(\":\")\n extra_headers = ':'.join(extra_headers)\n extra_headers = extra_headers.split(\"\\\\n\")\n # Remove empty strings\n extra_headers = [x for x in extra_headers if x]\n for extra_header in extra_headers:\n # Extra HTTP Header name \n http_header_name = re.findall(r\"(.*):\", extra_header)\n http_header_name = ''.join(http_header_name)\n # Extra HTTP Header value\n http_header_value = re.findall(r\":(.*)\", extra_header)\n http_header_value = ''.join(http_header_value)\n request.add_header(http_header_name, http_header_value)\n\n#eof","sub_path":"src/core/requests/headers.py","file_name":"headers.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"272774742","text":"from django.shortcuts import render, redirect, HttpResponse\n\n# Create your views here.\n\ndef view_bag(request):\n ''' a view that renders the bag content'''\n return render(request, 'bag/bag.html')\n\n\ndef add_to_bag(request, item_name):\n \"\"\" Add a product/service to bag \"\"\"\n\n redirect_url = request.POST.get('redirect_url')\n bag = request.session.get('bag', {})\n\n if item_name in list(bag.keys()):\n bag[item_name]\n else:\n bag[item_name] = item_name\n\n request.session['bag'] = bag\n return render(request, 'bag/bag.html')\n\n\ndef remove_from_bag(request, item_name):\n \"\"\" remove the item from bag\"\"\"\n\n bag = request.session.get('bag', {})\n if item_name in list(bag.keys()):\n print(bag)\n bag.pop(item_name)\n print(bag)\n\n request.session['bag'] = bag\n return HttpResponse(status=200)","sub_path":"bag/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"389832244","text":"from db_operations.connection import dictionary\n\n# Variables\nwords_on_game = []\nwords_already_played = []\n\ndef create_theme(name: str, words: list) -> int:\n \"\"\"\n Esta es la función encargada de crear un nuevo tema en el juego.\n :param name: Nombre del tema.\n :param words: Palabras incluídas en el tema.\n :return: 1. Creado correctamente, 2. Problema de inserción, 3. Nombre inválido, 4.Tema ya creado\n \"\"\"\n valid_theme = True\n valid_theme &= True if \"\".join(name.strip().split()).isalpha() and len(name) > 1 else False\n\n theme_names = list(dictionary.find({'name': name.strip().title()}))\n\n valid_theme &= True if len(theme_names) == 0 else False\n\n # Verificamos las palabras ingresadas\n valid_words = []\n\n for word in words:\n valid = True\n valid &= True if word.strip().isalpha() else False\n valid &= True if len(word) > 1 else False\n\n if valid:\n ready_word = word.strip().title()\n valid_words.append(ready_word)\n\n if len(theme_names) == 0:\n if valid_theme:\n theme = {\n 'name': name.strip().title(),\n 'words': valid_words,\n 'times_used': 0\n }\n\n try:\n dictionary.insert_one(theme)\n return 1\n except:\n return 2\n else:\n return 3\n else:\n return 4\n\n\ndef get_themes() -> list:\n \"\"\"\n Esta función trae todos los temas de la base de datos.\n :return: Una lista con los nombres de cada tema.\n \"\"\"\n themes = ['Agregar tema', 'Todos los temas']\n all_themes = list(dictionary.find())\n\n for theme in all_themes:\n themes.append(theme['name'])\n\n return themes\n\n\ndef setup_words(themes: list) -> None:\n \"\"\"\n Esta función se encarga de crear un arreglo de forma local con todas las palabras\n traídas de la base de datos correspondientes a los temas activos del juego actual.\n :param themes: Una lista con los nombres de los temas en juego.\n :return: Nada\n \"\"\"\n if \"Todos los temas\" in themes:\n all_themes = list(dictionary.find())\n for theme in all_themes:\n for word in theme['words']:\n words_on_game.append(word)\n else:\n db_themes = list(dictionary.find())\n for theme in db_themes:\n if theme['name'] in themes:\n for word in theme['words']:\n words_on_game.append(word)\n\n\ndef check_word(word: str) -> int:\n \"\"\"\n Verifica si la palabra recibida está dentro de las palabras jugadas.\n :param word: Palabra ingresada por el usuario.\n :return: 1. Palabra ya jugada, 2. Palabra no jugada.\n \"\"\"\n if word.title() in words_on_game:\n return 1\n else:\n return 2\n\n\ndef is_word_played(word: str) -> int:\n \"\"\"\n Esta función recibe una palabra y verifica si dicha palabra ya fue usada en el juego.\n :param word: Palabra ingresada por el jugador\n :return: 1. Palabra no usada, 2. Palabra usada.\n \"\"\"\n if word.title() in words_already_played:\n return 2\n else:\n return 1\n\n\ndef add_word_db(word: str, theme: str) -> int:\n \"\"\"\n Esta función añade la palabra a la base de datos del tema ingresado.\n :param word: Palabra ingresada por el usuario.\n :param theme: Tema elegido por el usuario.\n :return: 1. Inserción exitosa, 2. Inserción fallida.\n \"\"\"\n\n\n db_theme = list(dictionary.find({'name': theme}))[0]\n previous_length = len(db_theme['words'])\n\n word = word.title()\n dictionary.update(\n {'name': theme},\n {'$push': {'words': word}}\n )\n\n db_theme = list(dictionary.find({'name': theme}))[0]\n after_length = len(db_theme['words'])\n\n if after_length == (previous_length + 1):\n return 1\n return 2\n\n\ndef get_words(theme: str) -> list:\n \"\"\"\n Esta función buscará en la base de datos el tema que recibe por parámetro\n y devuelve una lista con las palabras encontradas.\n :param theme: Nombre del tema a buscar.\n :return: Lista con las palabras encontradas.\n \"\"\"\n my_theme = list(dictionary.find({'name': theme}))[0]\n\n return my_theme['words']\n\n\ndef update_word_db(prev_word: str, after_word: str, theme:str) -> int:\n \"\"\"\n Esta función se encargará de modificar la palabra dada en la base de datos.\n :param prev_word: Palabra seleccionada de la base de datos por el usuario.\n :param after_word: Palabra editada y válida que se ingresará a la base de datos reemplazando el valor de prev_word.\n :param theme: Tema que contiene la palabra que se va a editar.\n :return: 1. Transacción exitosa, 2. Transacción fallida.\n \"\"\"\n\n\n try:\n dictionary.update(\n {'name': theme, 'words': prev_word},\n {'$set': {'words.$': after_word}}\n )\n return 1\n except:\n return 2\n\n\ndef delete_word_db(word: str, theme: str) -> int:\n \"\"\"\n Esta función se encarga de eliminar una palabra de la base de datos.\n :param word: Palabra a eliminar.\n :param theme: Tema del que será eliminada la palabra.\n :return: 1. Transacción exitosa, 2. Transacción fallida.\n \"\"\"\n\n try:\n dictionary.update(\n {'name': theme},\n {'$pull': {'words': word}}\n )\n return 1\n except:\n return 2\n\n\n\n\n\n\n\n\n\n","sub_path":"db_operations/themes.py","file_name":"themes.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"136472005","text":"import time\n\nclass PIDController:\n def __init__(self, k_P, k_I, k_D, target_value = 0):\n self.k_P = k_P\n self.k_I = k_I\n self.k_D = k_D\n self.e_P = 0\n self.e_I = 0\n self.e_D = 0\n self.target_value = target_value\n self.adjusted_value = target_value\n self.last_time = None\n def send_value(self, value):\n # Check for first run\n if self.last_time == None:\n self.last_time = time.time()\n self.e_P = value - self.target_value\n return\n # Update the time difference\n new_time = time.time()\n dt = new_time - self.last_time\n self.last_time = new_time\n # Update the errors\n new_error = value - self.target_value\n self.e_D = (new_error - self.e_P) / dt\n self.e_I += new_error * dt\n self.e_P = new_error\n # Update the adjusted value\n self.adjusted_value = self.target_value - (self.k_P * self.e_P + self.k_I * self.e_I + self.k_D * self.e_D)\n","sub_path":"gnc/pid.py","file_name":"pid.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"13024452","text":"from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom exeapp.models.idevices.idevice import Idevice\nfrom exeapp.models.idevices.genericidevice import GenericIdevice\nfrom exeapp.models.idevices import fields\n\nclass ClozeIdevice(GenericIdevice):\n\n group = Idevice.TEST\n name = _(\"Cloze\")\n title = models.CharField(max_length=100, default=name)\n author = _(\"University of Auckland\")\n purpose = _(\"\"\"
Cloze exercises are texts or\n sentences where students must fill in\n missing words. They are often used for the\n following purposes:
\n \n
To check knowledge of core course\n concepts (this could be a pre-check,\n formative exercise, or summative check).
\n
To check reading comprehension.
\n
To check vocabulary knowledge.
\n
To check word formation and/or grammatical\n competence.
\"\"\")\n emphasis = Idevice.SOMEEMPHASIS\n icon = \"icon_question.gif\"\n description = fields.RichTextField(blank=True, default=\"\",\n help_text=_(\"\"\"Provide instruction on how the cloze activity should be\ncompleted. Default text will be entered if there are no changes to this field.\n\"\"\"))\n cloze_text = fields.ClozeTextField(blank=True, default=\"\",\n help_text=_(\"\"\"Enter the text for the cloze activity in to the cloze field\nby either pasting text from another source or by typing text directly into the\nfield.To select words to hide, double click on the word to select it and\nclick on the underscore button in the toolbar.\"\"\"))\n feedback = fields.FeedbackField(blank=True, default=\"\",\n help_text=_(\"\"\"Enter any feedback you wish to provide the learner\n with-in the feedback field. This field can be left blank.\"\"\"))\n drag_n_drop = models.BooleanField(default=False)\n\n class Meta:\n app_label = \"exeapp\"\n\n","sub_path":"exeapp/models/idevices/clozeidevice.py","file_name":"clozeidevice.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"354562911","text":"# -*- coding: utf-8 -*-\nimport json\nimport requests\nfrom back.encrpyt import interfaceDes\nfrom back.log import Log\n\nclass testApi:\n def __init__(self):\n self.header1 = {'Accept': '* / *',\n 'Accept - Encoding': 'gzip, deflate, br',\n 'Accept - Language': 'zh, en - US;q = 0.9, en;q = 0.8, zh - CN;q = 0.7',\n 'Connection': 'keep - alive',\n 'Content - Type': 'text/html;charset=utf-8'\n }\n self.header2 = {'content-type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*'}\n\n def lRequest(self, url, service, method='post', data='', headers=''): # 接口请求\n if type(service) is str: service = {\"service\": service}\n if 'webapi' in url:\n if any(data) and any(headers) is False:\n headers = self.header1\n if 'test' in url:\n data = data\n else:\n print(data)\n print(type(data))\n data = interfaceDes(data)\n else:\n if any(data) and any(headers) is False:\n headers = self.header2\n if 'test' in url:\n data = data\n else:\n data = interfaceDes(data, web_api=False)\n try:\n r = requests.request(method, url, data=data, headers=headers, params=service)\n response_code = r.status_code\n response_text1 = json.loads(r.text) # 对返回的指定字段断言,字段名取自Excel的期望2\n Log().info(' 【成功发起POST请求】 请求结果code为:%s, 请求结果字段为:%s' % (response_code, json.loads(r.text)))\n return response_code, response_text1\n except Exception as e:\n Log().error('【post请求出错】 出错原因:%s' % e)\n return {'code': 1, 'result': 'post请求出错,出错原因:%s' % e}","sub_path":"back/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"339483091","text":"from selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport csv\r\nimport requests\r\nSTART_URL = \"https://exoplanets.nasa.gov/exoplanet-catalog/\"\r\nbrowser = webdriver.Chrome(\"chromedriver_win32\\chromedriver.exe\")\r\nbrowser.get(START_URL)\r\ntime.sleep(10)\r\n\r\nheaders = [\"Star\", \"Constellation\", \"Right ascensation\", \"App_mag\", \"Distance\",\"hyperlink\"]\r\nplanet_data=[]\r\ndef scrap():\r\n for i in range(1,430):\r\n while True :\r\n time.sleep(2)\r\n soup = BeautifulSoup(browser.page_source, \"html.parser\")\r\n current_page_numb=int(soup.find_all(\"input\",attributes={\"class\",\"page_numb\"}).get(\"value\"))\r\n if current_page_numb < i :\r\n browser.find_element_by_xpath('//*[@id=\"primary_column\"]/footer/div/div/div/nav/span[2]/a').click()\r\n elif current_page_numb>i:\r\n browser.find_element_by_xpath('//*[@id=\"primary_column\"]/footer/div/div/div/nav/span[1]/a').click()\r\n else:\r\n break\r\n\r\n for ul_tag in soup.find_all(\"ul\", attrs={\"class\", \"exoplanet\"}):\r\n li_tags = ul_tag.find_all(\"li\")\r\n temp_list = []\r\n for index, li_tag in enumerate(li_tags):\r\n if index == 0:\r\n temp_list.append(li_tag.find_all(\"a\")[0].contents[0])\r\n else:\r\n try:\r\n temp_list.append(li_tag.contents[0])\r\n except:\r\n temp_list.append(\"\")\r\n hyerlink_li_tag=li_tags[0]\r\n temp_list.append(\"https://en.wikipedia.org/wiki/List_of_brown_dwarfs\"+hyperlink_li_tag.find_all(\"a\",href=True)[0][\"href\"])\r\n \r\n planet_data.append(temp_list)\r\n browser.find_element_by_xpath('//*[@id=\"primary_column\"]/footer/div/div/div/nav/span[2]/a').click()\r\n print(f\"{i} page done1\")\r\ndef scrap_more_data(hyperlink):\r\n try:\r\n page=request.get(hyperlink)\r\n soup=BeautifulSoup(page.content,\"html.parser\")\r\n for tr_tag in soup.find_all (\"tr\",attrs={\"class\":\"fact_rope\"}):\r\n tr_tags=tr_tags.find_all(\"td\")\r\n temp_list=[]\r\n for td_tag in td_tags:\r\n try:\r\n temp_list.append(td_tag.find_all(\"div\",attrs={\"class\",\"value\",})[0].contents[0])\r\n except:\r\n temp_list.append(\"\")\r\n new_planet_data.append(temp_list)\r\n except:\r\n time.sleep(1)\r\n scrap_more_data(hyerlink)\r\n\r\nscrap()\r\nfor data in planet_data:\r\n scrap_more_data(data[5])\r\n print(f\"{index+1} page done2\")\r\nfinal_planet_data=[]\r\n\r\nfor index,data in enumerate (planet_data):\r\n new_planet_data_element=new_planet_data_element[index]\r\n new_planet_data_element=[elem.replace(\"\\n\",\"\")for elem in new_planet_data_element]\r\n new_planet_data_element=new_planet_data_element[:7]\r\n final_planet_data.append(data+new_planet_data_element)\r\n\r\nwith open (\"final.csv\",\"w\") as f:\r\n csvwriter=csv.writer(headers)\r\n csvwriter.writerow(headers)\r\n csvwriter.writerows(final_planet_data)","sub_path":"scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"566715022","text":"# def 函式名稱(參數名稱=預設資料):\n# 函式內部的程式碼\n#參數可給預設值 但必須放在一般參數之後\ndef say(msg=\"hello\"):\n print(msg)\nsay(\"hihi\")\nsay() #會印出預設資料 hello\n\n#名稱對應\n# def 函式名稱(名稱1, 名稱2):\n# 函式內部的程式碼\n# #呼叫函式 以參數名稱對應資料\n# 函式名稱(名稱2=3, 名稱1=5) 若不指定 要造順序給\ndef divide(n1, n2):\n result=n1/n2\n print(\"divide: \", result)\ndivide(2, 4)\ndivide(n2=2, n1=4)\n\n#無限參數\n# def 函式名稱(*無限參數) #參數名稱前面+ \"*\"等於無限參數\n# 無限參數以Tuple資料形態處理\n# 函式內部的程式碼\n# #呼叫函式,可傳入無線數量的參數\n# 函式名稱(資料1, 資料2, 資料3)\n\n#範例\n#函式接受無限參數msgs\ndef saylimit(*msgs):\n #以Tuple的方式處理\n for msgg in msgs:\n print(msgg)\nsaylimit(\"hi\", \"hihi\", \"hihihi\")\n\n\n\nprint(\"=====實際程式撰寫======\")\n#實際程式撰寫\n#參數的預設資料 和參數的名稱對應\ndef power(base, exp=0):\n print(base**exp)\npower(3,2)\npower(exp=3, base=2) #參數的名稱對應\npower(4) #預設為0 所以4的0次方為1\n\n#無限/不定量 參數資料\n#做總量平均數 但數字量不固定 avg(3,4) avg(3,5,10) avg(1,4,-1,-8)\nprint(\"做總量平均數 但數字量不固定 avg(3,4) avg(3,5,10) avg(1,4,-1,-8)\")\ndef avg(*num):\n sum = 0\n avgs = 0\n for i in num:\n sum = sum + i\n avgs = sum / len(num)\n print(avgs)\n\navg(3, 4)\navg(3, 5, 10)\navg(1 ,4, -1, -8)\n\n#另外寫法\n# def avg(*num):\n# sum = 0\n# for i in num:\n# sum = sum + i\n# print(sum / len(num))\n#\n# avg(3, 4)\n# avg(3, 5, 10)\n# avg(1 ,4, -1, -8)\n","sub_path":"learn/8_def_adv.py","file_name":"8_def_adv.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"379585071","text":"# manducaGraph\n# This function animates a beautiful movie of one or more Manducas racing along.\n# It works from a file that has saved data from a prior simulation run.\n#\n# Inputs:\n#\tmode: -\t0 means display each file as a horizontally-moving worm;\n#\t\tone file (i.e., one worm) per line in the movie. In this\n#\t\tcase, 'arg' is how many seconds the full movie should last and\n#\t\t'varargin' is an alternating list of (the name of a file of\n#\t\tworm data, followed by a label for that worm).\n#\t - 1 means display one worm only, but display it as a sequence\n#\t\tof 'arg' stills, one over the other. In this case, 'varargin'\n#\t\tis the name of exactly one file of worm data.\n#\targ, varargin: as indicated above.\n# A common call might then be\n#\tmanducaGraph (0, 20, 'C:\\users\\johnM\\matlab\\graph1.txt', 'Slow worm',\n#\t\t\t 'C:\\users\\johnM\\matlab\\graph2.txt', 'Fast worm');\n# This would display both worms (one from graph1.txt and one from graph2.txt)\n# racing against each other. The two animated worms would be labeled\n# 'Slow worm' and Fast worm'.\n#\n# Another common call might be\n#\tmanducaGraph (1, 20, 'C:\\users\\johnM\\matlab\\graph1.txt')\n# This would take the worm-motion data from graph1.txt, pull out 20 stills at\n# evenly-spaced times, and display them.\n#\n# The worm-data files are typically produced by manducaFitness(), which can\n# be told to save all simulation data into a file.\n\n# Constants.\nFPS = 30\t\t# frames per second.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.patches as patches\n\ndef manducaGraph (mode, arg, *rest):\n global points\n # Build points[n_frames,15,n_worms]\n # The 2nd dimension is 15: t, 5 x values, 5 leg_locked and 4 muscle_on.\n # The 3rd dimension is always the number of worms to draw one above another.\n # The 1st dimension is the number of frames to time-sequence for each worm.\n if (mode==0):\t\t# video of one or more worms racing.\n # Read the file(s) and build points[n_frames][15 items][n_worms]\n wall_time = int(arg)\n n_frames = 1 + wall_time*FPS\n if (len(rest) & 1 != 0):\n raise Exception ('Missing label name for file')\n\n n_files = len(rest)//2\n labels = [rest[2*f+1] for f in range(n_files)]\n points = np.empty ((n_frames,15,n_files))\n for f in range(n_files):\n points[:,:,f] = read_file (rest[2*f], n_frames)\n elif (mode==1):\t\t# a few stills of one worm.\n # In this mode, we just read one file of data (from one worm).\n # Then we extract 'n_stills' evenly-spaced stills from it to\n # build points[1][15 items][n_stills].\n n_stills = arg\n points = np.empty ((1,15,n_stills))\n pts = read_file (rest[0], n_stills)\n # We now take our N frames, extracted from one worm over time, and\n # pretend that they are 1 frame each from N worms. That will result in\n # a sequence of N stills.\n for st in range(n_stills):\n points[:,:,st] = pts[st,:]\n labels = ['t='+str(100*st/(n_stills-1)) for st in range(n_stills)]\n else:\n raise Exception ('Illegal mode: must be 0 or 1')\n\n # We now have points[n_display_timepoints][15][n_worms]. Run the movie.\n display (points, labels)\n\n# Inputs:\n# -\tfile: a filename. The file has one line per simulation timepoint.\n#\tEach line is comma-separated values with the format\n#\ttime, x1,x2,x3,x4,x5, lock1...lock5, musc1...musc5\n# - n_frames: the number of frames to return. So if the file contains data\n#\tfrom t=0 to t=100 and we want to return 3 frames, then we will sample\n#\tevery 50s of simulated time.\n# Return a 2D array where row #i is the simulation data at frame #i.\n# So the first row is for t=0. The last row is for the simulation end time \n# which is always t=100).\n# The returned array has the same number of columns (with the same meaning) as\n# the simulation file.\ndef read_file (file, n_frames):\n print ('Sampling file', file, 'to create',n_frames,'frames.')\n\n # Read the file, starting at the 2nd line (the top line is a comment).\n # Now we have an array where each line is\n #\t(time, x1,x2,x3,x4,x5, lock1...lock5, musc1...musc5)\n with open (file, 'r') as fp:\n lines = fp.readlines() # one list item per line.\n # The top line is just a comment\n del lines[0]\n n_rows = len(lines)\n n_cols = len(lines[0].split(','))\n # Do a double-nested list comprehension to get the data.\n pts_list = [[float(val) for val in line.split(',')] for line in lines]\n raw = np.array (pts_list)\n\n # Sanity check that we have 15 columns.\n assert (raw.shape[1] == 15) # time, x1-5, 5 lock values, 4 muscles.\n # Sanity check that the leg-lock values are all 0 or 1.\n assert ((raw[:,6:11]==0) | (raw[:,6:11]==1)).all()\n # And the muscle values are all 0 or 100.\n assert ((raw[:,11:15]==0) | (raw[:,11:15]==100)).all()\n\n # How often must we sample to get n_frames frames?\n # Note the .00001; we want to ensure that the final value of desired_t below\n # is not actually *bigger* than raw[-1,0]; that would make us skip the last\n # point\n t_final = raw[-1,0] - .00001\n interval = t_final/(n_frames-1)\n\n # Now do the interpolation.\n # Note that the file may occasionally have such small timesteps that,\n # when we print out with finite precision, it seems like two consecutive\n # rows share the same time. The algorithm below is robust to that.\n\n # It should always be true that desired_t = interval * (points_row-1).\n desired_t = 0\t\t# The timepoint we want numbers for.\n points_row = 0\t\t# We will put this row in points(points_row,:).\n\n # The big picture: this loop keeps stepping through 'raw' until desired_t\n # is in [row r.time, row r+1.time]. Then it interpolates to find the data at\n # desired_t (and any other desired timepoints that are also in the interval)\n # The first time around the loop, desired_t=0 and the interval really is\n # closed on the left; afterwards, it is always (].\n # At the bottom of this loop, we will always have desired_t > raw[r+1].time,\n # since we will have kept incrementing desired_t until it is out of the\n # interval.\n points = np.empty((n_frames,15))\n for r in range(raw.shape[0]-1):\t# For every row pair (r,r+1)\n time1 = raw[r,0]\t\t# timepoint for this table row\n time2 = raw[r+1,0]\t\t# timepoint for the next table row\n while (desired_t <= time2):\n inter = interpolate(raw,r,desired_t)\n points[points_row,:] = interpolate(raw,r,desired_t)\n desired_t += interval\n points_row += 1\n return (points)\n\n# Given:\n#\t- raw: an array of (time, x1,x2,x3,x4,x5,lock1...lock5) for all\n#\t timepoints that were integration timesteps.\n#\t- t: the timepoint we really want.\n#\t- r: says where to find t=next_interval in 'raw'.\n# Assume that the desired time 't' obeys raw(r,1)<= t <= raw(r+1,1).\n# Perform linear interpolation based on that time and return a full 15-element\n# row vector where:\n#\t- [0] is the desired time 't'\n#\t- [1:5] are the interpolated 'x' positions of the five body segments.\n#\t- [6:10] are the lock conditions from raw(r,6:10)\n#\t- [11:14] are the muscles from raw(r,11:14).\ndef interpolate (raw,r,t):\n ###print ('Interpolating row',r,'and',r+1,'for time=',t)\n assert ((raw[r,0]<=t) & (raw[r+1,0]>=t))\n frac = (t-raw[r,0])/(raw[r+1,0]-raw[r,0])\n # Interpolate the X values (1:5). Also interpolate time as a sanity check.\n points = np.empty((15))\n points[0:6] = raw[r,0:6] + frac*(raw[r+1,0:6]-raw[r,0:6])\n assert (abs (points[0]-t) < .0001)\n\n # The leg-lock values just get dragged along.\n points[6:15] = raw[r,6:15]\t\t# Leg-lock values & muscles.\n\n # Very occasionally, the Matlab ODE solver will squish the worm so much that\n # a front leg gets pushed behind a back leg! Fix that here -- we really\n # should fix the ODEs instead :-(, but I've not gotten around to debugging\n # it.\n for i in range (2,6):\n points[i] = max (points[i-1],points[i])\n return (points)\n\n############################################################\n# The rest of the file is for window display\n############################################################\n\n# Set up the plot window.\n# We create axes, scaled so that:\n#\t* x ranges over the min/max x values from the simulation.\n#\t* y ranges from 0 to n_worms; i.e., each worm is allocated a vertical\n#\t space of 1.\ndef display (points, labels):\n n_worms = points.shape[2]\n print ('making',n_worms,'worms')\n\n # Get min & max value in 'points'. Make sure to only min/max over the X\n # values (i.e., columns 1:5), not the leg-locks & muscles.\n x_min = np.min(points[:,1:6,:])\n x_max = np.max(points[:,1:6,:])\n\n # Set up the figure and its axes.\n fig,axes = plt.subplots()\n axes.axis ([x_min,x_max,0,n_worms])\n axes.set_autoscale_on(False)\n # print ('x limits=', axes.get_xlim(), ', y limits=', axes.get_ylim())\n\n draw_labels (labels, axes)\t\t# Label each worm with text on the left\n init_pats(n_worms, axes)\t\t# Create all of the moving shapes\n\n msecPerFrame = 1000/FPS\n ani = animation.FuncAnimation(fig, per_frame, frames=points.shape[0],\n interval=msecPerFrame, blit=True,\n repeat=False)\n print (\"Finished animation\")\n plt.show()\n\n# Create all of the rectangles that make up the legs and body segments for all\n# of the worms. Just put them anywhere at all; per_frame() will move them.\n# Each worm has:\n# - 5 legs. A leg is a single vertical rectangle.\n# - 4 body segments. Each one is a horizontal rectangle (perhaps with a bit of\n# curvature), as well as a horizontal line in it if the segment's muscle is on\n# We keep all of these objects in\n# - Legs[5][n_worms]\n# - BodySegs[4][2][n_worms]. For this, [*][0][*] is the main-segment rectangle,\n# and [*][1][*] is the corresponding muscle-on band.\ndef init_pats(n_worms, axes):\n global legs, bodySegs, allPatches\n legs = np.empty ((5, n_worms), dtype=object)\n bodySegs = np.empty ((4, 2, n_worms), dtype=object)\n\n for w in range(n_worms):\n for l in range(5):\t# Build the red legs\n pat = patches.Rectangle ((0,0),.1,.1, facecolor='r')\n axes.add_patch (pat)\n legs[l][w] = pat\n\n for bs in range(4):\n pat = patches.Rectangle ((0,0),.1,.1, facecolor='g')\n axes.add_patch (pat)\t# Green body segments\n bodySegs[bs][0][w] = pat\n pat = patches.Rectangle ((0,0),.1,.1, facecolor='k')\n axes.add_patch (pat)\t# Black muscle-on bands\n bodySegs[bs][1][w] = pat\n\n # Collect up all of the rectangles into one big list, so that per_frame()\n # can return the list.\n allPatches = [legs[l][w] for l in range(5) for w in range(n_worms)]\n bs = [bodySegs[bs][0][w] for bs in range(4) for w in range(n_worms)]\n m = [bodySegs[bs][1][w] for bs in range(4) for w in range(n_worms)]\n allPatches.extend (bs)\n allPatches.extend (m)\n\n# The per-frame animation function.\n# Inputs: 'points' is a full array with[n_timepoints][data][n_worms] (where\n#\tn_timepoints is the number of frames to be displayed).\n# Remember that our display axes are:\n#\t* x ranges over the min/max x values from the simulation.\n#\t* y ranges from 0 to n_worms; i.e., each worm is allocated a vertical\n#\t space of 1.\ndef per_frame (f):\n global legs, bodySegs, points, allPatches\n for y in range(legs.shape[1]):\t# For each worm (& draw worm #i at y=i)\n # Make a slice with just this frame & worm. It has [0:5]=legX,\n # [6:10]=legLocked, [10:14]=muscle\n pts = points[f,1:,y]\n leg_width=30\n for l in range(5):\n legX = pts[l]; lock=pts[l+5]\n # A leg is 'width' wide, centered at 'x'.\n # Its top is at y+.5; it drops down to y+(lock?.3:.4).\n x_l = legX-leg_width/2\n y_b = y + (.4 - lock/10)\n legs[l][y].set_bounds (x_l,y_b, leg_width, y+.5-y_b)\n\n for bs in range(4):\n x1 = pts[bs]; x2=pts[bs+1]; musc=pts[bs+10]\n # Draw the segment from x1+(leg_width/2) to x2-(leg_width/2).\n # However, it may be that x2-x1 <= leg_width, in which case the body\n # part would vanish -- in that case, we pretend that leg is skinnier\n if (x1 + leg_width >= x2):\n leg_width = (x2-x1)/4\n\n # The height goes from y=.7 to y=.5.\n # So the LL is (x1+(leg_width/2),.5).\n LL_x = x1+(leg_width/2)\n dx = x2-(leg_width/2) - LL_x\n bodySegs[bs][0][y].set_bounds (LL_x,.5+y, dx,.2)\n\n # If the muscle is on, draw a black band across the segment.\n bodySegs[bs][1][y].set_visible (musc==100)\n bodySegs[bs][1][y].set_bounds (LL_x,.58+y, dx,.04)\n\n # We must return a list of everything that's moving this frame. Just assume\n # that everything moves (which it mostly does), and thus return the same\n # list of all rectangles all the time.\n return allPatches\n\n# Draw the names of the worm(s), on the left side of the screen.\ndef draw_labels (labels, axes):\n L = len(labels)\n for i,label in enumerate(labels):\n y = (i+.5)\n axes.text (.05,y,label)\n\n# Actually run the program.\n# manducaGraph (0, 30, 'crawl6_final_output.txt', 'worm@20')","sub_path":"5_ManducaModel/manducaGraph.py","file_name":"manducaGraph.py","file_ext":"py","file_size_in_byte":13418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"384535754","text":"import math\nimport numpy as np\nfrom scipy import special, integrate, optimize\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm as gauss\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom numpy import sqrt, pi, exp, log\nfrom scipy.linalg import norm\n\n# import mpmath as mp\n# from mpmath import sqrt, exp, log, pi, norm\n\nfrom blackscholes import *\n\n# Robbins-Monro (RM) iterations\nM = 500\n# Monte Carlo (MC) iterations\nN = 500000\n\ns0 = 100\nT = 1\nr = 0.05\nsigma = 0.2\n# strike price\nK = 1.4*s0\n# s0 = 1\n# T = 1\n# r = 0\n# sigma = 1\n\nBS = BlackScholes(s0, r, sigma, T)\n\n\ndef F(x):\n e = exp(x) - K\n if e > 0:\n return 50 * e\n else:\n return 0\n\ndef H(theta, x):\n xi = (sqrt(10) - 2) / 3 * theta\n if x < log(K) - xi:\n return 0\n # a = (theta - xi - x) * exp(-(x+xi)**2 + 0.5*(x+xi-theta)**2 + 0.5*x**2 - 0.25*(x-xi)**2 - 100*norm(theta))\n # return F(x+xi)**2*a\n a = (theta - xi - x) * exp(-1/4*x**2 - (2/3 + sqrt(10)/6)*x*theta + 2*x + (2*sqrt(10)/3 - 4/3)*theta)\n return a\n\ndef Hexpl(theta, x):\n return F(x)**2 * (theta - x) * exp(-0.75*x**2 + 0.5*(x-theta)**2 - 0.5*theta**2 - norm(theta))\n\ndef RM(theta, x):\n if x < log(K):\n return 0\n # a1 = (theta - x)*exp(-0.5*x**2 + 0.5*(x-theta)**2 - (3/2+1)*norm(theta)**2)\n a1 = (theta - x)*exp(-0.5*x**2 + 0.5*(x-theta)**2)\n # print(a1)\n if a1 == 0:\n print('NULL!!')\n return 0\n elif a1 < 0:\n a = sqrt(-a1)\n return -(50*(exp(x + log(a)) - K*a))**2\n else:\n a = sqrt(a1)\n return (50*(exp(x + log(a)) - K*a))**2\n\ndef RMput(theta, x):\n # if x > log(K):\n # return 0\n # a1 = (theta - x)*exp(-x**2 + 0.5*(x-theta)**2 - 0.5*norm(theta)**2)\n a1 = (theta - x)*exp(-0.5*x**2 - theta*x - 100*norm(theta))\n if a1 == 0:\n return 0\n elif a1 < 0:\n a = sqrt(-a1)\n return -(50*(exp(x + log(a))))**2\n else:\n a = sqrt(a1)\n return (50*(exp(x + log(a))))**2\n\ndef RMminus(theta, x):\n if x < log(K) + theta:\n return 0\n return (50*(exp(x - theta) - K))**2 * (2*theta - x) * exp(-2*norm(theta))\n # print(a1)\n # if a1 == 0:\n # print('NULL!!')\n # return 0\n # elif a1 < 0:\n # a = sqrt(-a1)\n # return -(50*(exp(x + log(a)) - K*a))**2\n # else:\n # a = sqrt(a1)\n # return (50*(exp(x + log(a)) - K*a))**2\n\ndef RMArouna(theta, x):\n if x < log(K):\n return 0\n # return (50*(exp(x)-K))**2 * (theta - x) * exp(-theta*x + 0.5*norm(theta)**2)\n return (50*(exp(x)-K))**2 * (theta - x) * exp(-theta*x)\n\ndef RMArounaplus(theta, x):\n if x < log(K) - theta:\n return 0\n return (50*(exp(x+theta)-K))**2 * -x * exp(-2*theta*x - norm(theta)**2)\n\n\ndef RMp(theta, x):\n if x < log(K):\n return 0\n # a1 = (theta - x)*exp(-x**2 + 0.5*(x-theta)**2 - 0.5*norm(theta)**2)\n a1 = (theta - x)*exp(-0.5*x**2 - theta*x - norm(theta))\n if a1 == 0:\n return 0\n elif a1 < 0:\n a = sqrt(-a1)\n return -(50*(exp(x + log(a)) - K*a))**2\n else:\n a = sqrt(a1)\n return (50*(exp(x + log(a)) - K*a))**2\n\ndef esscher():\n theta = 0\n for n in range(M):\n pass\n\ndef rhoCall(theta):\n return exp(-2*sigma*sqrt(T)*abs(theta))\n\ndef FCall(x, K):\n e = s0*exp(sigma*sqrt(T)*x + (r-0.5*sigma**2)*T) - K\n if e > 0:\n return exp(-r*T) * e\n else:\n return 0\n\ndef rhoPut(theta):\n return 1\n\ndef FPut(x):\n e = K - s0*exp(sigma*sqrt(T)*x + (r-0.5*sigma**2)*T)\n if e > 0:\n return exp(-r*T) * e\n else:\n return 0\n\ndef adaptiv(rho, F):\n C1 = 1\n C2 = 10 * s0**2\n theta = 0\n for n in range(1, M+1):\n X = np.random.normal()\n theta = theta - C1/(C2 + n) * rho(theta) * F(X-theta)**2 * (2*theta-X)\n\n thetaM = theta\n print('thetaM = ', thetaM)\n\n mu = 0\n gSqSum = 0\n gs = np.zeros(N)\n mus = np.zeros(N)\n for n in range(1, N+1):\n X = np.random.normal()\n g = F(X+theta)*exp(-theta*X - 0.5 * theta**2)\n gSqSum = gSqSum - 1/n * (gSqSum - g**2)\n mu = mu - 1/n * (mu - g)\n theta = theta - C1/(C2 + M + n) * rho(theta) * F(X-theta)**2 * (2*theta-X)\n gSqSum = gSqSum - 1/n * (gSqSum - g**2)\n varest = gSqSum - mu**2\n\n if n % 100000 == 0 or n == N:\n print('theta = ', theta, 'mu = ', mu, 'varest = ', varest)\n\n return thetaM, theta, mu, varest\n\ndef crude(F):\n mu = 0\n gSqSum = 0\n for n in range(1, N+1):\n X = np.random.normal()\n g = F(X)\n mu = mu - 1/n * (mu - g)\n gSqSum = gSqSum - 1/n * (gSqSum - g**2)\n varest = gSqSum - mu**2\n if n % 100000 == 0 or n == N:\n print('mu = ', mu, 'varest = ', varest)\n\n\n\n\n# importance sampling by mean translation\ndef translation():\n # optimize theta by RM\n # theta = log(K)\n # theta = 6.22\n # theta = 0.82\n theta = 0\n for n in range(M):\n X = np.random.normal()\n thetaold = theta\n\n # theta -= 1 / 30000 / (n+1) * RM(theta, X)\n theta -= 1 / (n+1) * RMArouna(theta, X)\n # theta -= 1 / 0.121 / (n+1) * H2(theta, X)\n # theta -= 1 / 4500 / (n+1) * RMminus(theta, X)\n if norm(theta) > sqrt(n):\n print('le le le le Chen!!', theta)\n if n % 2:\n theta = 0.5\n else:\n theta = -0.5\n\n\n if theta != thetaold:\n print(str(thetaold) + ' -> ' + str(theta))\n if n % 1000 == 0:\n print(n, theta)\n input()\n # run MC with optimized theta\n res = np.zeros(N)\n for n in range(N):\n X = np.random.normal()\n res[n] = F(X + theta) * exp(-theta*X - 0.5*theta**2)\n if n % 1000 == 0:\n print(n, np.mean(res[:n+1]), np.var(res[:n+1]))\n\ndiscCall = 0\ndiscPut = 0\ndef call(x):\n global discCall\n e = s0 * exp(-0.5*sigma**2 * T + sigma * x)\n if e > Kprime:\n return e - Kprime\n else:\n discCall += 1\n return 0\n\ndef put(x):\n global discPut\n e = s0 * exp(-0.5*sigma**2 * T + sigma * x)\n if e < Kprime:\n return Kprime - e\n else:\n discPut += 1\n return 0\n\ndef MC():\n resCall = np.zeros(N)\n resPut = np.zeros(N)\n for n in range(N):\n X = np.random.normal(0, sqrt(T))\n resCall[n] = call(X)\n resPut[n] = put(X)\n if n % 1000 == 0:\n mput = np.mean(resPut[:n+1])\n print(n, np.mean(resCall[:n+1]), np.var(resCall[:n+1]), mput, np.var(resPut[:n+1]), s0 - Kprime + mput, discCall, discPut)\n print(exactCall(), exactCallVar(), exactPut(), exactPutVar())\n\ndef plotCallPutPrices():\n plt.figure()\n plt.title('Prices of call and put for different strikes')\n Ks = np.linspace(0.5, 1.5)\n call = [BS.exactCallPrice(K) for K in Ks]\n put = [BS.exactPutPrice(K) for K in Ks]\n plt.plot(Ks, call, label='call')\n plt.plot(Ks, put, label='put')\n plt.xlabel('strike')\n plt.ylabel('price')\n plt.legend()\n\ndef plotCallPutVar():\n plt.figure()\n plt.title('Exact variance of call and put for different strikes')\n Ks = np.linspace(0.5, 1.5)\n callvar = [BS.exactCallVar(K) for K in Ks]\n putvar = [BS.exactPutVar(K) for K in Ks]\n plt.plot(Ks, callvar, 'b', label='call')\n plt.plot(Ks, putvar, 'g', label='put')\n # call2 = [BS.callSquared(K) for K in Ks]\n # put2 = [BS.putSquared(K) for K in Ks]\n # plt.plot(Ks, call2, 'r', label='call2')\n # plt.plot(Ks, put2, 'k', label='put2')\n plt.xlabel('strike')\n plt.ylabel('variance')\n plt.legend()\n\ndef plotISVar():\n plt.figure()\n plt.title('Variance optimization problem (call)')\n for K in [0.6, 0.8, 1.0, 1.2, 1.4]:\n theta = np.linspace(-0.3, 1.6)\n var = [BS.exactCallVar(K, theta) for theta in theta]\n minth = theta[np.argmin(var)]\n line, = plt.plot(theta, var, label=str(K))\n plt.axvline(minth, color=line.get_color())\n\n plt.xlabel(r'$\\theta$')\n plt.ylabel('call variance')\n plt.legend(title='strike', loc='upper left')\n plt.autoscale(tight=True)\n\n plt.figure()\n plt.title('Variance optimization problem (put)')\n for K in [0.6, 0.8, 1.0, 1.2, 1.4]:\n theta = np.linspace(-1.6, 0.0)\n var = [BS.exactPutVar(K, theta) for theta in theta]\n minth = theta[np.argmin(var)]\n line, = plt.plot(theta, var, label=str(K))\n plt.axvline(minth, color=line.get_color())\n\n plt.xlabel(r'$\\theta$')\n plt.ylabel('put variance')\n plt.legend(title='strike', loc='upper left')\n plt.autoscale(tight=True)\n\ndef plotOptimalTheta():\n plt.figure()\n plt.title(r'Optimal $\\theta$ for different strikes')\n Ks = np.linspace(0.5, 1.5)\n optth = [optimize.brentq(lambda th: BS.callSquaredDeriv(s0*K, th), -5, 5) for K in Ks]\n plt.xlabel(r'$K/s_0$')\n plt.ylabel(r'$\\theta_{opt}$')\n plt.plot(Ks, optth)\n\ndef plot3DISVars():\n @np.vectorize\n def getVar(K, theta):\n return BS.exactCallVar(K, theta)\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n K = np.linspace(0.6, 1.4)\n theta = np.linspace(0.3, 1.8)\n # K = np.linspace(0.0, 1.4)\n # theta = np.linspace(-3, 3)\n Km, thetam = np.meshgrid(K, theta)\n z = getVar(Km, thetam)\n minth = []\n minvar = []\n for i in range(len(K)):\n minvar.append(np.min(z[:,i]))\n minth.append(theta[np.argmin(z[:,i])])\n ax.plot(K, minth, minvar, 'r')\n ax.plot_surface(Km, thetam, z, cmap=plt.cm.jet, rstride=1, cstride=1, vmax=0.5)\n ax.set_xlabel('strike')\n ax.set_ylabel(r'$\\theta$')\n\ndef plotVarRM():\n plt.figure()\n plt.title('Call second moment and derivative')\n theta = np.linspace(0.4, 1.0)\n var = [BS.callSquared(K, theta) for theta in theta]\n deriv = [exp(-norm(theta)**2)*BS.callSquaredDeriv(K, theta) for theta in theta]\n plt.plot(theta, var, label='variance')\n plt.plot(theta, deriv, label='derivative')\n plt.xlabel(r'$\\theta$')\n plt.legend()\n\ndef plotISCall():\n x = np.linspace(-10, 10)\n y = 1/sqrt(2*pi*T)*exp(-x**2/(2*T))*(s0*exp(-0.5*sigma**2*T + sigma*sqrt(T)*x)-K*exp(-r*T))\n plt.plot(x, y)\n\ndef testExactVar():\n for K in np.linspace(0.6, 1.4, 5):\n for theta in np.linspace(0.0, 1.6, 5):\n print(K, theta)\n numIntC = integrate.quad(lambda x: BS.callISVar(K*s0, theta, x), -np.infty, np.infty)[0]\n numIntP = integrate.quad(lambda x: BS.putISVar(K*s0, theta, x), -np.infty, np.infty)[0]\n exactC = BS.callSquared(K*s0, theta)\n exactP = BS.putSquared(K*s0, theta)\n print(numIntC, exactC, np.abs(numIntC - exactC) / exactC)\n print(numIntP, exactP, np.abs(numIntP - exactP) / exactP)\n\ndef testCallSquaredDeriv():\n for K in np.linspace(0.6, 1.4, 5):\n for theta in np.linspace(0.0, 1.6, 5):\n print(K, theta)\n numIntC = integrate.quad(lambda x: BS.RM(K, theta, x), -np.infty, np.infty)[0]\n epsilon = 1e-10\n numDerivC = (BS.callSquared(K, theta+epsilon)-BS.callSquared(K, theta-epsilon))/2/epsilon\n exactC = BS.callSquaredDeriv(K, theta)\n print(numIntC, numDerivC, exactC, np.abs(numIntC - exactC) / exactC)\n\ndef testVarEquiv():\n for K in np.linspace(0.6, 1.4, 5):\n for theta in np.linspace(0.0, 1.6, 5):\n numIntC = integrate.quad(lambda x: BS.callISVar(K, 0, x), -np.infty, np.infty)[0]\n print(K, theta, BS.callSquared(K, theta), numIntC, exp(2*theta)*BS.callSquared(K/exp(theta), 0))\n\n\n\ndef main():\n fl = open('adaptiv_call.dat', 'w')\n fl.write('Knorm, exact, mu, thopt, thend, thM, exactvar, varest, vratio\\n')\n for K in [0.4, 0.7, 1.0, 1.2, 1.4]:\n thetaM, thetaend, mu, varest = adaptiv(rhoCall, lambda x: FCall(x, K*s0))\n exakt = BS.exactCallPrice(K*s0)\n exvar = BS.callSquared(K*s0)-exakt**2\n thopt = optimize.brentq(lambda th: BS.callSquaredDeriv(K*s0, th), -5, 5)\n fl.write(str(K) + ', ' + str(exakt) + ', ' + str(mu) + ', ' + str(thopt) + ', ' + str(thetaend) + ', ' + str(thetaM) + ', ' + str(exvar) + ', ' + str(varest) + ', ' + str(exvar/varest) + '\\n')\n\n # crude(FCall)\n # print(BS.callSquared(K)-BS.exactCallPrice(K)**2)\n # print(BS.callSquared(K, theta)-BS.exactCallPrice(K)**2)\n # optth = optimize.brentq(lambda th: BS.callSquaredDeriv(K, th), -5, 5)\n # print('optimal theta = ', optth)\n # testExactVar()\n # testCallSquaredDeriv()\n # testVarEquiv()\n\n # plotCallPutPrices()\n\n # plotCallPutVar()\n # plotISVar()\n # plotOptimalTheta()\n\n # plot3DISVars()\n # plotVarRM()\n # translation()\n # MC()\n # plotISCall()\n\n # plt.show()\n\n # theta = np.linspace(-10000, 10000)\n # # y = [sqrt(integrate.quad(lambda x: RMp(theta, x)**2, log(K), np.infty)[0]) for theta in theta]\n # # y = [sqrt(mp.quad(lambda x: RMp(theta, x)**2, [log(K), mp.inf])) for theta in theta]\n # y = [log(sqrt(mp.quad(lambda x: RMput(theta, x)**2, [-mp.inf, mp.inf]))) for theta in theta]\n # print(y)\n # # y = [sqrt(mp.quad(lambda x: Hexpl(theta, x)**2, [log(K), mp.inf])) for theta in theta]\n # plt.plot(theta, y)\n # plt.show()\n\n # mp.plot(lambda theta: sqrt(mp.quad(lambda x: H(theta, x)**2, [log(K), mp.inf])), [100, 1000000000])\n # mp.plot(lambda theta: sqrt(mp.quad(lambda x: H(theta, x)**2, [log(K), mp.inf])), [100, 1000000000])\n\n # pf = []\n # # for th in [0, 100, 10000, 1000000, 100000000]:\n # x = np.linspace(-5, 5)\n # for th in [0, 1, 2, 10]:\n # pf.append(lambda x: H(th, x))\n # print(pf[-1](0))\n # y = [H(th, x)**2 for x in x]\n # plt.plot(x, y, label=str(th))\n\n # plt.legend()\n # plt.show()\n # mp.plot(pf, [-5,5])\n\n # mp.plot(lambda theta: sqrt(mp.quad(lambda x: Hexpl(theta, x)**2, [log(K), mp.inf])), [100, 1000000000])\n # mp.plot(lambda theta: log(sqrt(mp.quad(lambda x: Hexpl(theta, x)**2, [log(K), mp.inf]))), [100, 1000000000])\n\nif __name__ == '__main__':\n main()\n","sub_path":"normal.py","file_name":"normal.py","file_ext":"py","file_size_in_byte":13890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"21611161","text":"import numpy as np\nimport gym\nfrom gym import spaces\nfrom datetime import datetime\n\nfrom time import sleep\nfrom fcntl import fcntl, F_GETFL, F_SETFL\nfrom os import O_NONBLOCK\nimport Queue\nimport threading\nimport subprocess\n\nclass Simulation():\n \n def __init__(self):\n self.p = None\n \n def start(self, x, y, psi):\n # TODO send initial settings to simulation\n self.p = subprocess.Popen(\"../EvolutionaryLearning/EL\", stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n shell=False, universal_newlines=True, close_fds=True)\n # set the O_NONBLOCK flag of p.stdout file descriptor:\n flags = fcntl(self.p.stdout, F_GETFL) # get current p.stdout flags\n fcntl(self.p.stdout, F_SETFL, flags | O_NONBLOCK)\n \n def end(self):\n if self.p is not None and self.p.poll() is None:\n self.p.stdout.flush()\n self.p.stdin.flush()\n self.p.kill()\n self.p.wait()\n\n def write_action(self, action):\n try:\n self.p.stdin.write(str(action) + \"\\n\")\n self.p.stdin.flush()\n except IOError:\n return\n \n def read_state(self):\n result = None\n errors = 0\n while result is None:\n try:\n result = self.p.stdout.readline().strip()\n #except OSError:\n # the os throws an exception if there is no data\n # print '[No more data]'\n except IOError:\n errors += 1\n # print 'not ready'\n if errors > 4:\n self.end()\n sleep(0.1)\n self.start(2,2,0)\n errors = 0\n \n sleep(0.05)\n \n result = np.array([float(i) for i in result.split()])\n return result\n\nclass DelflyEnv(gym.Env):\n metadata = {\n 'render.modes' : ['human', 'rgb_array'],\n 'video.frames_per_second' : 25\n }\n \n def __init__(self):\n \n self.viewer = None\n \n self.max_angle = 2*0.523809524 # 30 deg\n self.action_low = np.array([-self.max_angle, 0.04])\n self.action_high = np.array([self.max_angle, 5])\n self.action_space = spaces.Box(low=self.action_low, high=self.action_high) # angle offset to track\n \n #action_low = -self.max_angle\n #action_high = self.max_angle\n #self.action_space = spaces.Box(low=action_low, high=action_high, shape=(1,)) # angle offset to track\n \n _low = np.array([0,0,0,0,0,0,0,0,0,0,-3.142857143]) # apple detector location, apple detector size, average disparity\n _high = np.array([16,16,16,16,16,16,16,16,16,16,3.142857143])\n self.observation_space = spaces.Box(low = _low, high = _high)\n\n self.observation = np.array([0,0,0,0,0,0,0,0,0,0,0])\n self.state = None\n\n self._seed()\n self._reset()\n self.done = True\n \n self.sim = Simulation()\n \n self.poles = np.array([])\n \n #return observation, reward, done, info\n \n def _step(self, action):\n if self.done is True:\n self.sim.end()\n # reinitialise simulation with new initial conditions\n self.sim.start(2,2,0)\n self.done = False\n self.poles = self.sim.read_state()\n \n # run sim step\n orig_action = action\n action = np.clip(action, self.action_low, self.action_high)\n\n for a in action:\n self.sim.write_action(a)\n \n # read observations\n self.state = self.sim.read_state()\n \n if self.state.size == 0 or self.state[11] >= 0 or self.state[11] < -10:\n self.done = True\n\n if self.state.size >= 12:\n self.observation = self.state[0:11]\n self.reward = self.state[11] # -distance to goal in dm\n #print self.reward, (abs(orig_action[0]) > self.max_angle), 0.1/(abs(orig_action[1]+0.1))\n self.reward = self.reward - (abs(orig_action[0]) > self.max_angle) - 0.1/(abs(orig_action[1]+0.1)) # penalize large actions\n #print self.reward\n \n return self.observation, self.reward, self.done, {}\n \n def _reset(self):\n return self.observation\n \n def _render(self, mode='human', close=False):\n if close:\n if self.viewer is not None:\n self.viewer.close()\n self.viewer = None\n return\n\n screen_width = 600\n screen_height = 600\n\n world_width = 8\n scale = screen_width/world_width\n \n appleWidth = 0.5*scale\n \n delflyWidth = 0.3*scale\n delflyHeight = 0.3*scale\n \n polewidth = 5.0\n polelen = 30.0\n\n if self.viewer is None:\n from gym.envs.classic_control import rendering\n self.viewer = rendering.Viewer(screen_width, screen_height)\n \n # add Delfly\n l,r,t,b = -delflyWidth/2, delflyWidth/2, delflyHeight/2, -delflyHeight/2\n delfly = rendering.FilledPolygon([(l,b), (0,t), (0,t), (r,b)]) # triangle\n self.delflyTrans = rendering.Transform()\n delfly.add_attr(self.delflyTrans)\n self.viewer.add_geom(delfly)\n \n lof = rendering.Line(start=(0.0, 0.0), end=(5*delflyWidth*0.5, 5*delflyWidth*0.866)) # line of sight\n lof.add_attr(self.delflyTrans)\n self.viewer.add_geom(lof)\n \n lof = rendering.Line(start=(0.0, 0.0), end=(-5*delflyWidth*0.5, 5*delflyWidth*0.866)) # line of sight\n lof.add_attr(self.delflyTrans)\n self.viewer.add_geom(lof)\n \n l,r,t,b = -polewidth/2,polewidth/2,polelen-polewidth/2,-polewidth/2\n set_point = rendering.FilledPolygon([(l,b), (l,t), (r,t), (r,b)])\n set_point.set_color(.8,.6,.4)\n self.set_pointtrans = rendering.Transform(translation=(0, 0))\n set_point.add_attr(self.set_pointtrans)\n self.viewer.add_geom(set_point)\n \n self.poleTrans = []\n\n if self.state is None: return None\n \n if self.poles.size > 0:\n if len(self.poleTrans) is not self.poles.size / 2:\n self.poleTrans = []\n for i in range(0,self.poles.size/2):\n pole = rendering.make_circle(appleWidth/2)\n pole.set_color(.5,.5,.8)\n self.poleTrans.append(rendering.Transform(translation=(0,0)))\n pole.add_attr(self.poleTrans[i])\n self.viewer.add_geom(pole)\n # add poles\n for i in range(0,self.poles.size/2):\n self.poleTrans[i].set_translation(self.poles[i*2]*scale, self.poles[i*2 + 1]*scale)\n self.poles = np.array([])\n return None\n\n if self.state.size < 14: return None\n\n x = self.state\n self.delflyTrans.set_translation(x[12]*scale, x[13]*scale)\n self.delflyTrans.set_rotation(x[10]-1.571428571)\n \n self.set_pointtrans.set_translation(x[12]*scale, x[13]*scale)\n self.set_pointtrans.set_rotation(x[14]-1.571428571)\n\n return self.viewer.render(return_rgb_array = mode=='rgb_array')\n","sub_path":"gym/envs/local/delfly_pole.py","file_name":"delfly_pole.py","file_ext":"py","file_size_in_byte":7437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"496108454","text":"#!/usr/bin/env python\n# Author: Nhat Ngo (2017)\n# Nifty python program to submit job directly to Jenkins\n# \n# PREREQUISITE:\n# pip install tenacity\n# export JENKINS_USERNAME=\n# export JENKINS_TOKEN=\n\nimport os\nimport sys\nimport json\nimport tenacity\nimport argparse\nimport requests\n\nimport pprint\nfrom textwrap import dedent\n\n\ndef cli():\n \"\"\"Parse the CLI arguments\"\"\"\n \n cli_usage = \"\"\" Create tempest compute host check on Nectar Jenkins.\n PREREQUISITE:\n export JENKINS_USERNAME=\n export JENKINS_TOKEN=\n \"\"\"\n cloud_usage = \"\"\" Cloud to run tempest on: production, testing, development.\n Default to production.\"\"\"\n az_usage = \"\"\" Zone to run the the test on. See:\n https://wiki.rc.nectar.org.au/wiki/Tempest#AVAILABILITY_ZONES\n \"\"\"\n hosts_usage = \"\"\" Nova hosts to test. You can add multiple hosts. Eg: -s qh2-rcc10 -s qh2-rcc11\n Host must be in AVAILABILITY_ZONE; if not nova will return a 'No Valid Host' error.\n Leave blank to let scheduler choose a host.\n \"\"\"\n wait_usage = \"\"\" Do not wait for job to start, return the queue url immediately.\"\"\"\n debug_usage = \"\"\" Debug mode.\"\"\"\n\n parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,\n description=cli_usage)\n parser.add_argument(\"AVAILABILITY_ZONE\", type=str, action=\"store\",\n help=dedent(az_usage))\n parser.add_argument(\"--host\", \"-s\", type=str, action=\"append\",\n help=dedent(hosts_usage))\n parser.add_argument(\"--cloud\", \"-c\", type=str, action=\"store\", default=None,\n help=dedent(cloud_usage))\n parser.add_argument(\"--nowait\", action=\"store_true\",\n help=dedent(wait_usage))\n parser.add_argument(\"--debug\", action=\"store_true\",\n help=dedent(debug_usage))\n return parser.parse_args()\n\n\ndef get_auth():\n \"\"\"Return basic HTTP token needed to for requests\"\"\"\n username = os.environ.get('JENKINS_USERNAME')\n token = os.environ.get('JENKINS_TOKEN')\n\n if username is None or token is None:\n err_msg = \"\"\" JENKINS_USERNAME/TOKEN not found. Have you set your environment?\n export JENKINS_USERNAME=\n export JENKINS_TOKEN=\n \"\"\"\n raise EnvironmentError(dedent(err_msg))\n\n if DEBUG:\n sys.stdout.write(\"Login as: %s:%s\\n\" % (username, token))\n sys.stdout.flush()\n return (username, token)\n\n\ndef compute_host_check_build(az, host=None, cloud=None):\n \"\"\"Build jenkins compute host with the describe parameters\"\"\"\n # Request.utils.quote escape the string for URL encoding\n params = [\"AVAILABILITY_ZONE=%s\" % requests.utils.quote(az)]\n if host is not None:\n params.append(\"HOST=%s\" % requests.utils.quote(host))\n if cloud is not None:\n params.append(\"CLOUD=%s\" % requests.utils.quote(cloud))\n \n url = \"%s/buildWithParameters?%s\" % (JURL, \"&\".join(params))\n \n if DEBUG:\n sys.stdout.write(\"POST to: %s\\n\" % url)\n sys.stdout.flush()\n\n # Submit the job and get the responding Jenkins queue URL from the headers\n return requests.post(url, auth=AUTH)\n\n\ndef get_queue_json(build_response):\n \"\"\"Return the queue JSON\"\"\"\n queue_url = \"%sapi/json\" % build_response.headers[\"Location\"]\n queue_response = requests.get(queue_url, auth=AUTH)\n return queue_response.json()\n\ndef compute_host_check_submitted(build_response):\n \"\"\"Print out the confirmation of the submitted jenkins.\"\"\"\n response = get_queue_json(build_response)\n queue_url = \"%sapi/json\" % build_response.headers[\"Location\"]\n \n if DEBUG:\n sys.stdout.write(\"Queue response:=======================\\n\")\n pp.pprint(response)\n sys.stdout.write(\"======================================\\n\")\n sys.stdout.flush()\n\n # Get and format the submitted parameters\n params = response[u\"params\"][response[u\"params\"].find(\"AVAILABILITY\"):]\n params = \" \".join(param.split(\"=\")[1] for param in params.split(\"\\n\"))\n result = \"%s submitted: %s\\n\" % (params, queue_url)\n \n sys.stdout.write(result)\n\n\n@tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, max=15),\n stop=tenacity.stop_after_delay(600))\ndef compute_host_check_wait(build_response):\n \"\"\"\n Wait and return the job URL. Stop after 10 minutes.\n Retry exponential from 1 second up to 15 seconds then 15 seconds afterward.\n \"\"\"\n response = get_queue_json(build_response)\n\n if u\"Queue$LeftItem\" not in response[u\"_class\"]:\n err_msg = \"\"\" Waiting timeout after 600 seconds.\n Jenkins is very busy, please check API later.\n \"\"\"\n raise QueuingException(dedent(err_msg))\n \n if DEBUG:\n sys.stdout.write(\"Success response:=======================\\n\")\n pp.pprint(response)\n sys.stdout.write(\"========================================\\n\")\n sys.stdout.flush()\n\n job_url = response[u\"executable\"][u\"url\"]\n\n # Get and format the submitted parameters\n params = response[u\"params\"][response[u\"params\"].find(\"AVAILABILITY\"):]\n params = \" \".join(param.split(\"=\")[1] for param in params.split(\"\\n\"))\n \n # Result\n result = \"%s started: %s\\n\" % (params, job_url)\n \n sys.stdout.write(result)\n\nif __name__ == \"__main__\":\n \n args = cli()\n\n # Set global variables\n global DEBUG\n DEBUG = args.debug\n if DEBUG:\n global pp\n pp = pprint.PrettyPrinter(indent=2)\n\n global AUTH\n AUTH = get_auth()\n global JURL\n JURL = \"https://jenkins.rc.nectar.org.au/job/tempest-compute-host-check\"\n\n CLOUD = args.cloud\n HOSTS = args.host\n AVAILABILITY_ZONE = args.AVAILABILITY_ZONE\n WAIT = not args.nowait\n\n responses = [compute_host_check_build(AVAILABILITY_ZONE,\n host=HOST,\n cloud=CLOUD)\n for HOST in HOSTS]\n \n for resp in responses:\n if WAIT:\n try:\n compute_host_check_wait(resp)\n except QueuingException as ex:\n sys.stdout.write(\"Queue error: %s\\n\" % ex)\n sys.stdout.flush()\n compute_host_check_submitted(resp)\n else:\n compute_host_check_submitted(resp)","sub_path":"tempest_compute_check.py","file_name":"tempest_compute_check.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"621138787","text":"from hier_config import HConfig\nfrom hier_config.host import Host\nimport yaml\n\noptions = yaml.load(open('./tests/files/test_options_ios.yml'))\nhost = Host('brborder1', 'ios', options)\n\n# Build HConfig object for the Running Config\n\nrunning_config_hier = HConfig(host=host)\nrunning_config_hier.load_from_file('./tests/files/brborder1_shrun.log')\n\n# Build Hierarchical Configuration object for the Compiled Config\n\ncompiled_config_hier = HConfig(host=host)\ncompiled_config_hier.load_from_file('./tests/files/brborder1_add.log')\n\n# Merge additional(compiled) config to running config\n\nfor child in compiled_config_hier.children:\n# print(child)\n if 'no ' in str(child):\n child_str = str(child)\n child_str = child_str.lstrip('no ')\n# print(child_str)\n running_config_hier.del_child_by_text(child_str)\n else:\n running_config_hier.add_deep_copy_del_of(child, merged=True)\n\nfor line in running_config_hier.all_children():\n print(line.cisco_style_text())\n","sub_path":"hier_config_sample.py","file_name":"hier_config_sample.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"407788711","text":"''' 1 ВАРИАНТ\nНапишем пять функций, которые рассчитывают для каждог�� покупателя необходимый параметр.\n\nНа вход функции получают словарь из ключей - имена покупателей, и значений — списки с суммами.\nВсе функции возвращают словарь по всем покупателям и соответствуещее значение одного из параметров:\n1. число покупок;\n2. среднюю сумму покупки;\n3. максимальную сумму покупки;\n4. минимальную сумму покупки;\n5. общую сумму всех покупок.\n'''\n\n\n# Функция подсчитывает число покупок\ndef n_sale(name):\n s = dict()\n for k in name:\n s[k] = len(name[k])\n return s\n\n\n# Функция подсчитывает среднюю сумму покупки\ndef middle_sum(name):\n s = dict()\n for i in name:\n summ = 0\n for j in range(len(name[i])):\n summ += name[i][j]\n s[i] = float('{:.2f}'.format(summ/len(name[i])))\n return s\n\n\n# Функция опрелеляет сумму максимальной покупки\ndef max_sale(name):\n s = dict()\n for i in name:\n s[i] = max(name[i])\n return s\n\n\n# Функция опрелеляет сумму минимальной покупки\ndef min_sale(name):\n s = dict()\n for i in name:\n s[i] = min(name[i])\n return s\n\n\n# Функция подсчитывает общую сумму всех покупок\ndef sum_m(name):\n s = dict()\n for i in name:\n summ = 0\n for j in range(len(name[i])):\n summ += name[i][j]\n s[i] = summ\n return s\n\n\nsale = {'Алла': [100, 22, 63, 152, 415, 78, 459, 958, 10, 63],\n 'Борис': [122, 52, 36, 256, 398, 45, 145, 147, 15],\n 'Валентин': [54, 45, 789, 369, 52, 14, 16, 35, 14, 747, 95, 8],\n 'Галина': [56, 25, 96, 357, 496, 1258, 12, 45, 65, 36, 45],\n 'Дмитрий': [145, 85, 85, 96, 45, 75, 36, 45, 75, 45, 85, 58],\n 'Дианна': [152, 875, 5, 0.96, 455, 15, 6, 75, 7, 96, 54, 123]}\n\n# Выводим результат в виде таблицы\nprint('Имя Количество Стоимость покупки')\nprint('покупателя', ' покупок', ' Средняя ', ' Максимальная', 'Минимальная ', 'Общая')\nprint('{:_^72}'.format(' 1 ВАРИАНТ с пятью функциями'))\nfor i in sale:\n print('{:<11}'.format(i), '{:<12}'.format(n_sale(sale)[i]), '{:<12}'.format(middle_sum(sale)[i]),\n '{:<12}'.format(max_sale(sale)[i]), '{:<12}'.format(min_sale(sale)[i]), '{:<12}'.format(sum_m(sale)[i]))\n\n\n''' 2 ВАРИАНТ\nНапишим одну функцию - sale_info(name), рассчитывающую для каждого покупателя следующие параметры:\n1. число покупок;\n2. среднюю сумму покупки;\n3. максимальную сумму покупки;\n4. минимальную сумму покупки;\n5. общую сумму всех покупок.\n\nНа вход функция получает словарь из ключей - имена покупателей, и значений — списки с суммами.\nФункция возвращает словарь в виде имен покупателей и списка значений по всем соответствующем параметрам\n'''\n\n\ndef sale_info(name):\n s = dict()\n for i in name:\n summ = 0\n for j in range(len(name[i])):\n summ += name[i][j]\n s[i] = [len(name[i]), float('{:.2f}'.format(summ/len(name[i]))), max(name[i]), min(name[i]), summ]\n return s\n\n\nprint('{:_^72}'.format(' 2 ВАРИАНТ с одной функцией'))\nfor i in sale:\n print('{:<11}'.format(i), end=' ')\n for j in range(len(sale_info(sale)[i])):\n print('{:<12}'.format(sale_info(sale)[i][j]), end=' ')\n print()","sub_path":"DZ_0507_sale.py","file_name":"DZ_0507_sale.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"244728223","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom torch.nn.parameter import Parameter\nimport torch.nn.init as init\nimport torch.nn.functional as F\nfrom torchvision.utils import make_grid\nimport matplotlib.ticker as ticker\n\n# download data\nbatch_size = 128\nimage_size = 64\n\ndataset = dset.CIFAR10(root='../../data/', download=True, train=True,\n transform=transforms.Compose([transforms.Resize(image_size),\n transforms.ToTensor()]))\n# check device is cuda\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# show image\ndef show(img):\n npimg = img.numpy()\n ax = plt.gca()\n ax.grid(False)\n plt.imshow(np.transpose(npimg, (1,2,0)), interpolation='nearest')\n plt.axis('off')\n\n# define model\nclass ConvAutoEncoder(nn.Module):\n \n def __init__(self):\n \n super(ConvAutoEncoder, self).__init__()\n self.encoder = nn.Sequential(\n nn.Conv2d(3, 512, 4, 2, 0, bias=False), \n nn.BatchNorm2d(512),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(512, 128, 4, 2, 1, bias=False),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(128, 32, 4, 2, 1, bias=False),\n nn.BatchNorm2d(32),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(32, 8, 4, 2, 1, bias=False),\n nn.Sigmoid()\n )\n \n self.decoder = nn.Sequential(\n nn.ConvTranspose2d(8, 32, 4, 2, 0, bias=False), \n nn.BatchNorm2d(32),\n nn.LeakyReLU(0.2, inplace=True),\n nn.ConvTranspose2d(32, 128, 4, 2, 1, bias=False),\n nn.BatchNorm2d(128),\n nn.LeakyReLU(0.2, inplace=True),\n nn.ConvTranspose2d(128, 512, 4, 2, 1, bias=False),\n nn.BatchNorm2d(512),\n nn.LeakyReLU(0.2, inplace=True),\n nn.ConvTranspose2d(512, 3, 4, 2, 1, bias=False),\n nn.Sigmoid()\n )\n \n def forward(self, input):\n encoded = self.encoder(input)\n output = self.decoder(encoded)\n return output\n \n# define training method\ndef train(model, optimiser, criterion, epochs):\n losses = []\n for epoch in range(epochs):\n for idx, (data, label) in enumerate(dataloader):\n model.zero_grad()\n x = data.to(device)\n output = model(x)\n loss = criterion(output, x)\n losses.append(loss)\n loss.backward()\n optimiser.step()\n print('Done: [%d/%d][%d/%d] Loss: %.4f ' % (epoch, epochs, idx, len(dataloader), loss.item()))\n return losses\n\n# define autoencoder\ncae = ConvAutoEncoder().to(device)\n\n# define optim and criterion\noptimizer = torch.optim.Adam(cae.parameters(), lr = 0.001, weight_decay=1e-5)\ncriterion = nn.MSELoss()\n\n# train \nlosses = train(cae, optimizer, criterion, 15)\n\n# plot losses\nplt.figure()\nplt.plot(losses)\n \n","sub_path":"conv_ae.py","file_name":"conv_ae.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"96560695","text":"import sys\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.contrib.sites.models import Site\nfrom django.http import Http404\nfrom django.shortcuts import redirect, render\nfrom django.urls import reverse, reverse_lazy\nfrom django.utils.http import url_has_allowed_host_and_scheme\nfrom sfdo_template_helpers.oauth2.salesforce.views import SalesforcePermissionsError\n\nfrom config.settings.base import IP_RESTRICTED_MESSAGE\n\nGENERIC_ERROR_MSG = \"An internal error occurred while processing your request.\"\n\n\ndef custom_permission_denied_view(request, exception):\n message = GENERIC_ERROR_MSG\n if isinstance(exception, SalesforcePermissionsError):\n message = str(exception)\n\n return render(\n request,\n \"index.html\",\n context={\"JS_CONTEXT\": {\"error_message\": message}},\n status=403,\n )\n\n\ndef custom_500_view(request):\n message = GENERIC_ERROR_MSG\n value = sys.exc_info()[1]\n\n if \"ip restricted\" in value.args[0]:\n message = IP_RESTRICTED_MESSAGE\n\n return render(\n request,\n \"index.html\",\n context={\"JS_CONTEXT\": {\"error_message\": message}},\n status=500,\n )\n\n\n@user_passes_test(lambda user: user.is_superuser, login_url=reverse_lazy(\"admin:login\"))\ndef set_site(request):\n \"\"\"\n Put the selected `site_id` into the session. The ID is then used in favor of the\n current request's domain in `CurrentSiteMiddleware`.\n \"\"\"\n next_url = request.GET.get(\"next\", \"\")\n try:\n site = Site.objects.get(pk=request.GET.get(\"site_id\"))\n except (Site.DoesNotExist, ValueError):\n raise Http404(\"Couldn't find a matching site\")\n request.session[\"site_id\"] = site.id\n\n # Ensure the URL is safe\n if not url_has_allowed_host_and_scheme(next_url, settings.ALLOWED_HOSTS):\n next_url = reverse(\"admin:index\")\n\n # Don't redirect to a change view for an object that won't exist on the selected\n # site - go to its list view instead\n if next_url.endswith(\"/change/\"):\n # Remove the ID, \"/change/\" suffix, and trailing slash\n parts = next_url.split(\"/\")[:-3]\n next_url = \"/\".join(parts) + \"/\"\n\n return redirect(next_url)\n","sub_path":"metadeploy/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"351146566","text":"# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass ScaleScript:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'name': 'str',\n 'uri': 'str',\n 'parameters': 'str',\n 'nodes': 'list[str]',\n 'active_master': 'bool',\n 'fail_action': 'str',\n 'action_stage': 'str'\n }\n\n attribute_map = {\n 'name': 'name',\n 'uri': 'uri',\n 'parameters': 'parameters',\n 'nodes': 'nodes',\n 'active_master': 'active_master',\n 'fail_action': 'fail_action',\n 'action_stage': 'action_stage'\n }\n\n def __init__(self, name=None, uri=None, parameters=None, nodes=None, active_master=None, fail_action=None, action_stage=None):\n \"\"\"ScaleScript\n\n The model defined in huaweicloud sdk\n\n :param name: 弹性伸缩自定义自动化脚本的名称,同一个集群的自定义自动化脚本名称不允许相同。 只能由数字、英文字符、空格、中划线和下划线组成,且不能以空格开头。 可输入的字符串长度为1~64个字符。\n :type name: str\n :param uri: 自定义自动化脚本的路径。设置为OBS桶的路径或虚拟机本地的路径。 - OBS桶的路径:直接手动输入脚本路径。示例:obs://XXX/scale.sh - 虚拟机本地的路径:用户需要输入正确的脚本路径。脚本所在的路径必须以‘/’开头,以.sh结尾。\n :type uri: str\n :param parameters: 自定义自动化脚本参数。 多个参数间用空格隔开。 可以传入以下系统预定义参数: - ${mrs_scale_node_num}:扩缩容节点数 - ${mrs_scale_type}:扩缩容类型,扩容为scale_out,缩容为scale_in - ${mrs_scale_node_hostnames}:扩缩容的节点主机名称 - ${mrs_scale_node_ips}:扩缩容的节点IP - ${mrs_scale_rule_name}:触发扩缩容的规则名 其他用户自定义参数使用方式与普通shell脚本相同,多个参数中间用空格隔开。\n :type parameters: str\n :param nodes: 自定义自动化脚本所执行的节点组名称。\n :type nodes: list[str]\n :param active_master: 自定义自动化脚本是否只运行在主Master节点上。 缺省值为false,表示自定义自动化脚本可运行在所有Master节点上。\n :type active_master: bool\n :param fail_action: 自自定义自动化脚本执行失败后,是否继续执行后续脚本和创建集群。 说明: - 建议您在调试阶段设置为“continue”,无论此自定义自动化脚本是否执行成功,则集群都能继续安装和启动。 - 由于缩容成功无法回滚,因此缩容后执行的脚本“fail_action”必须设置为“continue”。 枚举值: - continue:继续执行后续脚本。 - errorout:终止操作。\n :type fail_action: str\n :param action_stage: 脚本执行时机。 枚举值: - before_scale_out:扩容前 - before_scale_in:缩容前 - after_scale_out:扩容后 - after_scale_in:缩容后\n :type action_stage: str\n \"\"\"\n \n \n\n self._name = None\n self._uri = None\n self._parameters = None\n self._nodes = None\n self._active_master = None\n self._fail_action = None\n self._action_stage = None\n self.discriminator = None\n\n self.name = name\n self.uri = uri\n if parameters is not None:\n self.parameters = parameters\n self.nodes = nodes\n if active_master is not None:\n self.active_master = active_master\n self.fail_action = fail_action\n self.action_stage = action_stage\n\n @property\n def name(self):\n \"\"\"Gets the name of this ScaleScript.\n\n 弹性伸缩自定义自动化脚本的名称,同一个集群的自定义自动化脚本名称不允许相同。 只能由数字、英文字符、空格、中划线和下划线组成,且不能以空格开头。 可输入的字符串长度为1~64个字符。\n\n :return: The name of this ScaleScript.\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this ScaleScript.\n\n 弹性伸缩自定义自动化脚本的名称,同一个集群的自定义自动化脚本名称不允许相同。 只能由数字、英文字符、空格、中划线和下划线组成,且不能以空格开头。 可输入的字符串长度为1~64个字符。\n\n :param name: The name of this ScaleScript.\n :type name: str\n \"\"\"\n self._name = name\n\n @property\n def uri(self):\n \"\"\"Gets the uri of this ScaleScript.\n\n 自定义自动化脚本的路径。设置为OBS桶的路径或虚拟机本地的路径。 - OBS桶的路径:直接手动输入脚本路径。示例:obs://XXX/scale.sh - 虚拟机本地的路径:用户需要输入正确的脚本路径。脚本所在的路径必须以‘/’开头,以.sh结尾。\n\n :return: The uri of this ScaleScript.\n :rtype: str\n \"\"\"\n return self._uri\n\n @uri.setter\n def uri(self, uri):\n \"\"\"Sets the uri of this ScaleScript.\n\n 自定义自动化脚本的路径。设置为OBS桶的路径或虚拟机本地的路径。 - OBS桶的路径:直接手动输入脚本路径。示例:obs://XXX/scale.sh - 虚拟机本地的路径:用户需要输入正确的脚本路径。脚本所在的路径必须以‘/’开头,以.sh结尾。\n\n :param uri: The uri of this ScaleScript.\n :type uri: str\n \"\"\"\n self._uri = uri\n\n @property\n def parameters(self):\n \"\"\"Gets the parameters of this ScaleScript.\n\n 自定义自动化脚本参数。 多个参数间用空格隔开。 可以传入以下系统预定义参数: - ${mrs_scale_node_num}:扩缩容节点数 - ${mrs_scale_type}:扩缩容类型,扩容为scale_out,缩容为scale_in - ${mrs_scale_node_hostnames}:扩缩容的节点主机名称 - ${mrs_scale_node_ips}:扩缩容的节点IP - ${mrs_scale_rule_name}:触发扩缩容的规则名 其他用户自定义参数使用方式与普通shell脚本相同,多个参数中间用空格隔开。\n\n :return: The parameters of this ScaleScript.\n :rtype: str\n \"\"\"\n return self._parameters\n\n @parameters.setter\n def parameters(self, parameters):\n \"\"\"Sets the parameters of this ScaleScript.\n\n 自定义自动化脚本参数。 多个参数间用空格隔开。 可以传入以下系统预定义参数: - ${mrs_scale_node_num}:扩缩容节点数 - ${mrs_scale_type}:扩缩容类型,扩容为scale_out,缩容为scale_in - ${mrs_scale_node_hostnames}:扩缩容的节点主机名称 - ${mrs_scale_node_ips}:扩缩容的节点IP - ${mrs_scale_rule_name}:触发扩缩容的规则名 其他用户自定义参数使用方式与普通shell脚本相同,多个参数中间用空格隔开。\n\n :param parameters: The parameters of this ScaleScript.\n :type parameters: str\n \"\"\"\n self._parameters = parameters\n\n @property\n def nodes(self):\n \"\"\"Gets the nodes of this ScaleScript.\n\n 自定义自动化脚本所执行的节点组名称。\n\n :return: The nodes of this ScaleScript.\n :rtype: list[str]\n \"\"\"\n return self._nodes\n\n @nodes.setter\n def nodes(self, nodes):\n \"\"\"Sets the nodes of this ScaleScript.\n\n 自定义自动化脚本所执行的节点组名称。\n\n :param nodes: The nodes of this ScaleScript.\n :type nodes: list[str]\n \"\"\"\n self._nodes = nodes\n\n @property\n def active_master(self):\n \"\"\"Gets the active_master of this ScaleScript.\n\n 自定义自动化脚本是否只运行在主Master节点上。 缺省值为false,表示自定义自动化脚本可运行在所有Master节点上。\n\n :return: The active_master of this ScaleScript.\n :rtype: bool\n \"\"\"\n return self._active_master\n\n @active_master.setter\n def active_master(self, active_master):\n \"\"\"Sets the active_master of this ScaleScript.\n\n 自定义自动化脚本是否只运行在主Master节点上。 缺省值为false,表示自定义自动化脚本可运行在所有Master节点上。\n\n :param active_master: The active_master of this ScaleScript.\n :type active_master: bool\n \"\"\"\n self._active_master = active_master\n\n @property\n def fail_action(self):\n \"\"\"Gets the fail_action of this ScaleScript.\n\n 自自定义自动化脚本执行失败后,是否继续执行后续脚本和创建集群。 说明: - 建议您在调试阶段设置为“continue”,无论此自定义自动化脚本是否执行成功,则集群都能继续安装和启动。 - 由于缩容成功无法回滚,因此缩容后执行的脚本“fail_action”必须设置为“continue”。 枚举值: - continue:继续执行后续脚本。 - errorout:终止操作。\n\n :return: The fail_action of this ScaleScript.\n :rtype: str\n \"\"\"\n return self._fail_action\n\n @fail_action.setter\n def fail_action(self, fail_action):\n \"\"\"Sets the fail_action of this ScaleScript.\n\n 自自定义自动化脚本执行失败后,是否继续执行后续脚本和创建集群。 说明: - 建议您在调试阶段设置为“continue”,无论此自定义自动化脚本是否执行成功,则集群都能继续安装和启动。 - 由于缩容成功无法回滚,因此缩容后执行的脚本“fail_action”必须设置为“continue”。 枚举值: - continue:继续执行后续脚本。 - errorout:终止操作。\n\n :param fail_action: The fail_action of this ScaleScript.\n :type fail_action: str\n \"\"\"\n self._fail_action = fail_action\n\n @property\n def action_stage(self):\n \"\"\"Gets the action_stage of this ScaleScript.\n\n 脚本执行时机。 枚举值: - before_scale_out:扩容前 - before_scale_in:缩容前 - after_scale_out:扩容后 - after_scale_in:缩容后\n\n :return: The action_stage of this ScaleScript.\n :rtype: str\n \"\"\"\n return self._action_stage\n\n @action_stage.setter\n def action_stage(self, action_stage):\n \"\"\"Sets the action_stage of this ScaleScript.\n\n 脚本执行时机。 枚举值: - before_scale_out:扩容前 - before_scale_in:缩容前 - after_scale_out:扩容后 - after_scale_in:缩容后\n\n :param action_stage: The action_stage of this ScaleScript.\n :type action_stage: str\n \"\"\"\n self._action_stage = action_stage\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ScaleScript):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"huaweicloud-sdk-mrs/huaweicloudsdkmrs/v2/model/scale_script.py","file_name":"scale_script.py","file_ext":"py","file_size_in_byte":12650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"42015197","text":"from flask import Flask, request\nimport telegram\nfrom telebot.credentials import bot_token, bot_user_name, URL\nimport re\n\nglobal bot\nglobal TOKEN\nTOKEN = bot_token\nbot = telegram.Bot(token=TOKEN)\n\napp = Flask(__name__)\n\n@app.route('/{}'.format(TOKEN), methods=['POST'])\ndef respond():\n update = telegram.Update.de_json(request.get_json(force=True), bot)\n chat_id = update.message.chat.id\n msg_id = update.message.message_id\n text = update.message.text.encode('utf-8').decode()\n print(\"got text message:\", text)\n\n if text == \"/start\":\n bot_welcome = \"\"\"\n Welcome to CoolAvatar bot, the is using the service from \n http://avatars.adorable.io/ to generate cool looking avatars based on the \n name you enter so please enter a name and the bot will reply\n with an avatar for your name.\n \"\"\"\n bot.sendMessage(chat_id = chat_id, text=bot_welcome, reply_to_message_id=msg_id)\n else:\n try:\n text = re.sub(r\"\\W\", \"_\", text)\n url = \"https://api.adorable.io/avatars/285/{}.png\".format(text.strip())\n bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id = msg_id)\n except Exception:\n bot.sendMessage(chat_id=chat_id, text=\"There was a problem with the name, try again\", reply_to_message_id=msg_id)\n \n return 'ok'\n\n@app.route('/set_webhook', methods=['GET', 'POST'])\ndef set_webhook():\n s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN))\n if s:\n return \"webhook setup ok\"\n else:\n return \"webhook setup failed\"\n\n@app.route('/')\ndef index():\n return '.'\n\nif __name__ == '__main__':\n app.run(threaded=True)\n\n","sub_path":"telebot/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"491748474","text":"\n# coding: utf-8\n\n# In[ ]:\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\n\npddata=pd.read_csv('Nile.csv')\nprint(pddata.iloc[:,1].head())\npddata.plot(figsize=(12,4))\nplt.show()\ndata=np.array(pddata.iloc[:,1])\n\n\n# ### 非線形・非ガウス状態空間モデル\n# $\n# \\begin{align}\n# x_{t}&=f_{t}(x_{t-1},\\upsilon_{t})\\\\\n# y_{t}&=h_{t}(x_{t},\\omega_{t})\n# \\end{align}\n# $\n\n# In[ ]:\n\nclass ParticleFilter:\n def __init__(self,y,n_particle,upsilon2,omega2):\n self.y=y\n self.length=len(y)\n self.length_of_time=len(y)\n self.n_particle=n_particle\n self.upsilon2=upsilon2\n self.omega2=omega2\n self.filtered_value = np.zeros(self.length)\n print('OK!!')\n \n def init_particle(self):\n # x(i)_0|0\n particles = []\n predicts = []\n init=np.random.uniform(400,1600,self.n_particle)\n particles.append(init)\n predicts.append(init)\n return({'particles':particles,'predicts':predicts})\n \n def get_likelihood(self,ensemble,t):\n #今回は正規分布を仮定\n likelihoodes=(1/np.sqrt(2*np.pi*self.omega2))*np.exp((-1/(2*self.omega2))*((self.y[t]-ensemble[t])**2))\n return(likelihoodes)\n \n def one_predict(self,ensemble,t):\n # x(i)_t|t-1\n noise=np.random.normal(0,np.sqrt(self.upsilon2),self.n_particle)\n predict=ensemble[t]+noise\n return(predict)\n \n def filtering(self,ensemble,t):\n # x(i)_t|t\n likelihood=self.get_likelihood(ensemble,t)\n beta=likelihood/likelihood.sum()\n #print('beta',beta)\n filtering_value=np.sum(beta*ensemble[t])\n return({'beta':beta,'filtering_value':filtering_value})\n \n def resumpling(self,ensemble,weight):\n # sample=np.zeros(self.n_particle)\n # for i in range(self.n_particle):\n # sample[i]=np.random.choice(ensemble,p=weight)\n sample=np.random.choice(ensemble,p=weight,size=self.n_particle)\n return(sample)\n \n def simulate(self,seed=123):\n np.random.seed(seed)\n particles=self.init_particle()['particles']\n predicts=self.init_particle()['predicts']\n filtered_value=np.zeros(self.length)\n filtered_value[0]=np.sum(particles[0])/self.n_particle\n for t in np.arange(1,self.length):\n print(\"\\r calculating... t={}\".format(t), end=\"\")\n #一期先予測\n predicts.append(self.one_predict(particles,t-1))\n #フィルタリング\n filtered=self.filtering(predicts,t-1)\n filtered_value[t]=filtered['filtering_value']\n resumple=self.resumpling(predicts[t-1],filtered['beta'])\n particles.append(resumple)\n return({'particles':particles,'predicts':predicts,'filtered_value':filtered_value})\n\n\n# In[ ]:\n\nmodel=ParticleFilter(data,10000,np.exp(7.3),np.exp(9.63))\n\n\n# In[ ]:\n\nresult=model.simulate()\n\n\n# In[ ]:\n\n#plt.figure(figsize=(20,9))\nfor i in range(len(pddata)):\n if i==0:\n plt.scatter(np.zeros(len(result['particles'][i]))+i,result['particles'][i],s=1,color='red',alpha=0.1,label='particle')\n plt.scatter(np.zeros(len(result['particles'][i]))+i,result['particles'][i],s=1,color='red',alpha=0.1)\nplt.plot(data,color='blue',label='y')\nplt.plot(result['filtered_value'],color='green',label='estimate')\nplt.legend()\nplt.ylim(400,2000)\nplt.title('particles = {}, upsilon2 = {}, omega2 = {}'.format(model.n_particle,model.upsilon2,model.omega2))\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n","sub_path":"code/pf.py","file_name":"pf.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"121150535","text":"def isValidate(set_line):\n validate = {\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"}\n return set_line == validate\n\n\ndef sudokuCheck(sudoku):\n\n # 가로줄\n for row in sudoku:\n if not isValidate(set(row)):\n return 0\n\n # 세로줄\n zip_sudoku = list(zip(*sudoku))\n for column in zip_sudoku:\n if not isValidate(set(column)):\n return 0\n\n # 3 x 3 을 3개씩 잡아서 검사\n set1 = set()\n set2 = set()\n set3 = set()\n for idx, row in enumerate(sudoku):\n set1.update(row[:3])\n set2.update(row[3:6])\n set3.update(row[6:])\n if idx in [2, 5, 8]:\n if isValidate(set1) and isValidate(set2) and isValidate(set3):\n return 1\n else:\n return 0\n # 다음 3개 하기 전 초기화\n set1 = set()\n set2 = set()\n set3 = set()\n\n\nT = int(input())\n\nfor t in range(1, T+1):\n sudoku = []\n for _ in range(9):\n sudoku.append(input().split())\n\n print(f\"#{t} {sudokuCheck(sudoku)}\")\n","sub_path":"PYTHON/SWEXPERT/익스퍼트미분류/D2/1974_스도쿠_검증/1974_1.py","file_name":"1974_1.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"97767991","text":"from django.shortcuts import render,redirect,get_object_or_404\nfrom .models import signupit,mobile_spec,cart,buy_mobiles\nfrom django.contrib.auth import login,logout\nfrom django.contrib.auth.models import auth,User\n\n# Create your views here.\ndef home(request):\n mobiles=mobile_spec.objects.all()\n print(mobiles)\n return render(request,'ECommerce/homepage.html',{'mobiles':mobiles})\n\ndef signup(request):\n if request.method=='GET':\n return render(request,'ECommerce/signup.html')\n else:\n username=request.POST.get('username')\n password1=request.POST.get('password1')\n password2=request.POST.get('password2')\n email=request.POST.get('email')\n first_name=request.POST.get('first_name')\n last_name=request.POST.get('last_name')\n user=User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name)\n user.save()\n auth.login(request,user)\n return render(request,'ECommerce/homepage.html')\n\ndef login(request):\n if request.method=='GET':\n return render(request,'ECommerce/login.html')\n else:\n username=request.POST.get('username')\n password=request.POST.get('password1')\n user=auth.authenticate(username=username,password=password)\n if user is not None:\n auth.login(request,user)\n return redirect(home)\n else:\n return render(request,'ECommerce/login.html',{'error':'invalid'})\n\ndef logout(request):\n auth.logout(request)\n return redirect('home')\n\ndef specifications(request,mobile_pk):\n mobile=mobile_spec.objects.filter(pk=mobile_pk)\n return render(request,'ECommerce/specifications.html',{'mobile':mobile})\n\ndef carts(request):\n if request.method=='GET': \n mobiles=cart.objects.filter(user=request.user)\n mlist=[]\n for mobile in mobiles:\n m1=mobile.cart_models.all()\n print('This is m1',m1)\n for m3 in m1:\n print('This is m3: ',m3)\n m2=mobile_spec.objects.all()\n for m in m2:\n print('This is m:',m)\n if m==m3:\n print('matched')\n mlist.append(m)\n print(mlist)\n #if m not in mlist:\n # mlist.insert(m) \n return render(request,'Ecommerce/cart.html',{'mlist':mlist}) \n\ndef add_to_cart(request,addmobile_pk):\n m4=mobile_spec.objects.filter(pk=addmobile_pk)\n print(m4)\n a1=cart(user=request.user)\n a1.save()\n p1=a1.cart_models.set(m4)\n return redirect('home')\n\ndef remove_from_cart(request,remove_mobile_pk):\n if request.method=='POST':\n m5=cart.objects.filter(user=request.user)\n m6=mobile_spec.objects.filter(pk=remove_mobile_pk)\n for m7 in m5: \n m8=m7.cart_models.all()\n for m9 in m8:\n for m10 in m6:\n print('this is m8',m8)\n print('this is m6',m6)\n print('this is m9',m9)\n print('this is m10',m10)\n if m10.model==m9.model:\n print('matched delete it',m7)\n m7.delete()\n return redirect('home')\n\ndef buy_now(request,buy_pk):\n mobile=mobile_spec.objects.filter(pk=buy_pk)\n return render(request,'ECommerce/buy_now.html',{'mobile':mobile})\n\ndef buy(request,order_pk):\n if request.method=='POST':\n m4=mobile_spec.objects.filter(pk=order_pk)\n print(m4)\n quantity1=request.POST.get('quantity')\n address1=request.POST.get('address')\n print('quantity',quantity1)\n print('address',address1)\n order=buy_mobiles(quantity=quantity1,address=address1,user=request.user)\n order.save()\n order1=order.cart_models.set(m4)\n return redirect('home')\n\ndef search(request):\n search=request.POST.get('search')\n m3=mobile_spec.objects.filter(model=search)\n print(m3)\n if m3.exists() :\n print('none')\n return render(request,'ECommerce/homepage.html',{'m3':m3})\n else:\n return render(request,'ECommerce/homepage.html',{'error':'page not found'})\n \n\n\n\n\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"72001833","text":"import torch\nfrom torch import nn\n\nimport modules\nfrom datetime import datetime\n\nclass Embeddings(nn.Module):\n def __init__(self, embedding_dim=64):\n super(Embeddings, self).__init__()\n self.embedding_dim = embedding_dim\n self.embeddings_holiday = modules.CharacterEmbeddings(12, embedding_dim)\n self.embeddings_weather = modules.CharacterEmbeddings(11, embedding_dim)\n self.embeddings_weather_detail = modules.CharacterEmbeddings(38, embedding_dim)\n self.embeddings_month = modules.CharacterEmbeddings(12, embedding_dim)\n self.embeddings_dayofweek = modules.CharacterEmbeddings(7, embedding_dim)\n self.embeddings_hour = modules.CharacterEmbeddings(24, embedding_dim)\n\n def forward(self, data_dict):\n embed1 = self.embeddings_holiday.forward(data_dict['code_holiday'])\n embed2 = self.embeddings_weather.forward(data_dict['code_weather'])\n embed3 = self.embeddings_weather_detail.forward(data_dict['code_weather_detail'])\n embed4 = self.embeddings_month.forward(data_dict['code_month'])\n embed5 = self.embeddings_dayofweek.forward(data_dict['code_dayofweek'])\n embed6 = self.embeddings_hour.forward(data_dict['code_hour'])\n return torch.cat([embed1, embed2, embed3, embed4, embed5, embed6], 1)\n\nclass Predictor(nn.Module):\n def __init__(self):\n super(Predictor, self).__init__()\n self.linears = modules.LinearSeq(561, [1024, 128, 64, 32, 16, 6], activation_list=['relu', 'relu', 'relu', 'relu', 'relu', 'logsoftmax'])\n # self.linears = modules.LinearSeq(28, [32, 1], activation_list=['relu', None])\n\n def train(self, x_train, y_train, criterion, optimizer, num_epochs=1000):\n # hparams\n batch_size = 256\n\n # 1. set device\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n # device = 'cpu'\n print('device:', device)\n x_train = x_train.to(device)\n y_train = y_train.to(device)\n\n # 2. network to device\n self.to(device)\n\n # 3. loop over epoch\n with torch.autograd.set_detect_anomaly(True):\n for epoch in range(num_epochs):\n start = datetime.now()\n print('---------------\\nEpoch ', epoch + 1, '\\n')\n epoch_loss = .0\n\n num_batches = x_train.size(0) // batch_size\n\n # 3.1 loop over batch\n batch_count = 0\n while True:\n if batch_count < num_batches:\n batch = x_train[batch_size * batch_count: batch_size * (batch_count + 1)]\n labels = y_train[batch_size * batch_count: batch_size * (batch_count + 1)].squeeze()\n else:\n batch = x_train[batch_size * batch_count:]\n labels = y_train[batch_size * batch_count:].squeeze()\n # print('Epoch:', epoch+1, '/', num_epochs, 'Batch:', batch_count, '/', num_batches)\n # 3.1.0 initialize grads\n optimizer.zero_grad()\n\n # 3.1.1 linears\n preds = self.linears.forward(batch)\n\n # 3.1.3 calc batch loss\n loss = criterion(preds, labels)\n\n # 3.1.4 calc grads\n loss.backward(retain_graph=True)\n\n # 3.1.5 update model params\n optimizer.step()\n\n # 3.1.6 add batch loss to epoch loss\n epoch_loss += loss.item() * batch.size(0)\n # print('epoch loss: ', epoch_loss)\n\n batch_count += 1\n if batch_count > num_batches:\n break\n end = datetime.now()\n # 3.2 calc epoch loss\n epoch_loss /= x_train.size(0)\n print('Epoch', epoch + 1, 'average loss:', epoch_loss, 'elapsed:', (end - start).seconds + round(\n (end - start).microseconds / 1000000, 2))\n\n def eval(self, x_test):\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n # device = 'cpu'\n self.to(device)\n print('device:', device)\n x_test = x_test.to(device)\n with torch.no_grad():\n preds = self.linears.forward(x_test)\n return preds.max(dim=1)[1] + 1 # returns max index + 1\n\n# class Tacotron2(nn.Module):\n# def __init__(self, *args):\n# super(Tacotron2, self).__init__()\n# self.encoder = tacotron.modules.Encoder(*args)\n# self.attention = tacotron.modules.LocationSensitiveAttention(*args)\n# self.decoder = tacotron.modules.Decoder(*args)\n#\n # def pseudo_train(self, criterion, optimizer, num_epochs=100):\n # # 1. set device\n # device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n # print('device:', device)\n #\n # # 2. network to device\n # self.to(device)\n # batch_size = 4\n # max_input_length = 100\n # input_character_indices = torch.randint(0, 30, [3, batch_size, max_input_length])\n # labels = (torch.rand_like(self.decoder.spectrogram_pred),\n # torch.rand_like(self.decoder.spectrogram_length_pred.type(torch.float32)))\n #\n # # 3. loop over epoch\n # with torch.autograd.set_detect_anomaly(True):\n # for epoch in range(num_epochs):\n # print('---------------\\nEpoch ', epoch + 1, '\\n')\n # epoch_loss = .0\n # epoch_correct = 0\n #\n # # 3.1 loop over batch\n # for batch in input_character_indices:\n # # 3.1.0 initialize grads and decoder attributes\n # optimizer.zero_grad()\n # self.decoder.reset(batch_size)\n #\n # # 3.1.1 encoder\n # encoder_output, (encoder_h_n, encoder_c_n) = self.encoder(batch)\n # self.attention.h = encoder_output\n # h_prev_1 = self.decoder.h_prev_1.clone()\n # stop_token_cum = self.decoder.stop_token_cum.clone()\n #\n # # 3.1.2 loop over decoder step\n # for decoder_step in range(self.decoder.max_output_time_length):\n # print('\\n---------------------', 'decoder step: ', decoder_step + 1)\n # context_vector = self.attention.forward(h_prev_1, stop_token_cum)\n # h_prev_1, stop_token_cum = self.decoder.forward(context_vector)\n # if not any(\n # stop_token_cum): # stop decoding if no further prediction is needed for any samples in batch\n # break\n #\n # # 3.1.3 calc batch loss\n # length_pred_norm = self.decoder.spectrogram_length_pred.type(\n # torch.float32) / self.decoder.max_output_time_length\n # preds = (self.decoder.spectrogram_pred, length_pred_norm)\n # loss = criterion(preds, labels)\n #\n # # 3.1.4 calc grads\n # loss.backward()\n #\n # # 3.1.5 update model params\n # optimizer.step()\n #\n # # 3.1.6 add batch loss to epoch loss\n # epoch_loss += loss.item() * batch.size(0)\n #\n # # 3.2 calc epoch loss\n # epoch_loss /= input_character_indices.size(0) * input_character_indices.size(1)\n\n # def train(self, dataloaders_dict, criterion, optimizer, num_epochs=100):\n # # 1. set device\n # device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n # print('device:', device)\n # # 2. network to device\n # self.net.to(device)\n # # 3. loop over epoch\n # for epoch in range(num_epochs):\n # for phase in ['train', 'val']:\n # if phase == 'train':\n # self.net.train()\n # else:\n # self.net.eval()\n #\n # # 5. initialize loss per phase\n # epoch_loss = .0\n # epoch_correct = 0\n #\n # # 7. iterate dataloader\n # for input_character_indices, spectrogram_labels in tqdm(\n # dataloaders_dict[phase]): # dataloader는 자체로 iterable\n # # 8. dataset to device\n # input_character_indices = input_character_indices.to(device)\n # spectrogram_labels = spectrogram_labels.to(device)\n #\n # # 9. initialize grad\n # optimizer.zero_grad()\n #\n # # 10. forward\n # with torch.set_grad_enabled(\n # mode=(phase == 'train')): # enable grad only when training # with + context_manager\n # # Encoder\n # encoder_output, (encoder_h_n, encoder_c_n) = self.encoder.forward(input_character_indices)\n # # Attention&Decoder\n # self.attention.h = encoder_output # attention.h.Size([input length, batch, encoder output units])\n # self.decoder.reset(batch_size)\n # h_prev_1, stop_token_cum = self.decoder.h_prev_1, self.decoder.stop_token_cum # Local variable to speed up\n # for decoder_step in range(self.decoder.max_output_time_length):\n # print('\\n---------------------', 'decoder step: ', decoder_step + 1)\n # context_vector = self.attention.forward(h_prev_1, stop_token_cum)\n # h_prev_1, stop_token_cum = self.decoder.forward(context_vector)\n # if not any(stop_token_cum): # stop decoding if no further prediction is needed for any samples in batch\n # break\n #\n # # Calc loss\n # loss = criterion(self.decoder.spectrogram_pred, spectrogram_labels)\n #\n # # 11. (training)calc grad\n # if phase == 'train':\n # loss.backward()\n # # 12. (training)update parameters\n # optimizer.step()\n #\n # # 13. add loss and correct per minibatch per phase\n # epoch_loss += loss.item() * input_character_indices.size(0)\n #\n # # 14. print epoch summary\n # epoch_loss /= len(dataloaders_dict[phase].dataset) ## len(dataloader): num of datum\n #\n # print('Epoch loss: {:.4f}'.format(epoch_loss))\n\n\n# def checkup():\n# taco = Tacotron2()\n# criterion = tacotron.loss_function.Taco2Loss()\n# optimizer = torch.optim.Adam(taco.parameters())\n# taco.pseudo_train(criterion=criterion,\n# optimizer=optimizer,\n# num_epochs=3)\n#\n#\n# checkup()\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"397149640","text":"import jieba\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\n\n#读取文件\ntext = open(r'test.txt','r').read()\n#使用结巴截取单词\nresult_word = jieba.cut(text,cut_all=True)\n#存放截取的单词\nstr = []\n#读取截取的单词并存放到str中\nfor item in result_word:\n if len(item) >= 1 and item != '\\r\\n':\n str.append(item)\n#存放所有的单词-->key:单词、value:单词出现的次数\ndict = {}\n#统计数组中每个单词出现的次数并将其存放到dict字典中\nfor key in str:\n dict[key] = dict.get(key, 0) + 1\nprint(dict)\n#我们需要的模板图片\nalice_coloring = np.array(Image.open(r\"alice_color.png\"))\n#使用wordcloud的WorldCloud\nwc = WordCloud(background_color=\"white\", max_words=2000,mask=alice_coloring,stopwords=STOPWORDS.add(\"said\"), max_font_size=40,random_state=42)\n\nwc.generate_from_frequencies(dict)\nplt.imshow(wc)\nplt.axis(\"off\")\nplt.show()\nwc.to_file(\"result.png\")","sub_path":"test2/8-11/practice9.py","file_name":"practice9.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"267737952","text":"import os\n# heroku config:set HEROKU=1\n# so we can run debug mode locally, not on heroku\nIS_HEROKU = os.environ.get('HEROKU') == 1\n\nDEFAULT_OUTPUT_FILE = 'output/data.json'\n\nSITES = ['http://news.yahoo.com/',\n 'https://news.google.com/',\n 'http://www.huffingtonpost.com/',\n 'http://www.cnn.com/',\n 'http://www.nytimes.com/']","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"91178954","text":"import uuid\n\nfrom setuptools import setup\nfrom pip.req import parse_requirements\n\nimport versioneer\n\nrequirements = [str(ir.req) for ir in parse_requirements('requirements.txt', session=uuid.uuid1())]\n\nDATA_FILES = [\n 'requirements.txt',\n 'versioneer.py',\n]\n\nTEST_DEPS = [\n 'nose',\n 'nose-parameterized',\n 'mock',\n]\n\nsetup(\n name='pysteam',\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n description='Python library to work with Steam',\n url='http://github.com/scottrice/pysteam',\n author='Scott Rice',\n author_email='',\n license='MIT',\n packages=['pysteam'],\n install_requires=requirements,\n data_files=DATA_FILES,\n dependency_links=[\n ],\n zip_safe=False,\n test_suite='nose.collector',\n tests_require=TEST_DEPS,\n extras_require={'test': TEST_DEPS},\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"151319865","text":"import os\nimport json\nimport math\n\n\n# metadata\nmetadata = {\n 'protocolName': 'Redo Replacement Picking (Greiner MASTERBLOCK 96 Well \\\nPlate 1000 µL)',\n 'author': 'Nick ',\n 'source': 'Custom Protocol Request',\n 'apiLevel': '2.11'\n}\n\n\ndef run(ctx):\n\n tip_track = True\n\n [input_file, input_file2, tuberack_scan, plate_scan, tuberack_scan2,\n plate_scan2, default_disposal_vol, default_transfer_vol,\n p300_mount] = get_values( # noqa: F821\n 'input_file', 'input_file2', 'tuberack_scan', 'plate_scan',\n 'tuberack_scan2', 'plate_scan2', 'default_disposal_vol',\n 'default_transfer_vol', 'p300_mount')\n\n # load labware\n rack = ctx.load_labware('eurofins_96x2ml_tuberack', '2', 'tuberack')\n\n plates = [ctx.load_labware('greinermasterblock_96_wellplate_1000ul', '4')]\n\n if input_file2:\n plates.append(\n ctx.load_labware('greinermasterblock_96_wellplate_1000ul', '1'))\n\n tips300 = [\n ctx.load_labware('opentrons_96_tiprack_300ul', slot)\n for slot in ['11']]\n\n # pipette\n p300 = ctx.load_instrument('p300_single_gen2', p300_mount,\n tip_racks=tips300)\n\n tip_log = {val: {} for val in ctx.loaded_instruments.values()}\n\n folder_path = '/data/tip_track'\n tip_file_path = folder_path + '/tip_log.json'\n if tip_track and not ctx.is_simulating():\n if os.path.isfile(tip_file_path):\n with open(tip_file_path) as json_file:\n data = json.load(json_file)\n for pip in tip_log:\n if pip.name in data:\n tip_log[pip]['count'] = data[pip.name]\n else:\n tip_log[pip]['count'] = 0\n else:\n for pip in tip_log:\n tip_log[pip]['count'] = 0\n else:\n for pip in tip_log:\n tip_log[pip]['count'] = 0\n\n for pip in tip_log:\n if pip.type == 'multi':\n tip_log[pip]['tips'] = [tip for rack in pip.tip_racks\n for tip in rack.rows()[0]]\n else:\n tip_log[pip]['tips'] = [tip for rack in pip.tip_racks\n for tip in rack.wells()]\n tip_log[pip]['max'] = len(tip_log[pip]['tips'])\n\n def _pick_up(pip, loc=None):\n if tip_log[pip]['count'] == tip_log[pip]['max'] and not loc:\n ctx.pause('Replace ' + str(pip.max_volume) + 'µl tipracks before \\\nresuming.')\n pip.reset_tipracks()\n tip_log[pip]['count'] = 0\n if loc:\n pip.pick_up_tip(loc)\n else:\n pip.pick_up_tip(tip_log[pip]['tips'][tip_log[pip]['count']])\n tip_log[pip]['count'] += 1\n\n # check barcode scans (tube, plate)\n tuberack_bar, plate_bar = input_file.splitlines()[3].split(',')[:2]\n if not tuberack_scan[:len(tuberack_scan)-4] == tuberack_bar.strip():\n print(tuberack_scan[:len(tuberack_scan)-4])\n raise Exception(f'Tuberack scans do not match ({tuberack_bar}, \\\n{tuberack_scan})')\n if not plate_scan[:len(plate_scan)-4] == plate_bar.strip():\n raise Exception(f'Plate scans do not match ({plate_bar}, {plate_bar})')\n\n if input_file2:\n tuberack_bar2, plate_bar2 = input_file2.splitlines()[3].split(',')[:2]\n if not tuberack_scan2[:len(tuberack_scan2)-4] == tuberack_bar2.strip():\n print(tuberack_scan2[:len(tuberack_scan2)-4])\n raise Exception(f'Tuberack2 scans do not match ({tuberack_bar2}, \\\n {tuberack_scan2})')\n if not plate_scan2[:len(plate_scan2)-4] == plate_bar2.strip():\n raise Exception(\n f'Plate2 scans do not match ({plate_bar2}, {plate_bar2})')\n\n # parse\n inputdata = [[\n [val.strip() for val in line.split(',')]\n for line in input_file.splitlines()[4:]\n if line and line.split(',')[0].strip()]]\n\n tubelist = [[\n well for col in rack.columns()\n for well in col[:8]]]\n\n if input_file2:\n\n inputdata.append([\n [val.strip() for val in line.split(',')]\n for line in input_file2.splitlines()[4:]\n if line and line.split(',')[0].strip()])\n\n tubelist.append([\n well for col in rack.columns()\n for well in col[8:]])\n\n for data, plate, tubes_ordered in zip(inputdata, plates, tubelist):\n for line in data:\n tube = tubes_ordered[int(line[0])-1]\n well = plate.wells()[int(line[1])-1]\n if len(line) >= 3 and line[2]:\n disposal_vol = float(line[2])\n else:\n disposal_vol = default_disposal_vol\n if len(line) >= 4 and line[3]:\n transfer_vol = float(line[3])\n else:\n transfer_vol = default_transfer_vol\n\n # remove contents of well\n _pick_up(p300)\n\n ctx.max_speeds['A'] = 100 # slow descent\n ctx.max_speeds['Z'] = 100 # slow descent\n\n # effective tip capacity 280 with 20 uL air gap\n reps = math.ceil(disposal_vol / 280)\n\n vol = disposal_vol / reps\n\n for rep in range(reps):\n p300.move_to(well.top())\n p300.air_gap(20)\n p300.aspirate(vol, well.bottom(1))\n p300.dispense(\n vol+20, ctx.fixed_trash.wells()[0].top(-5), rate=1.5)\n ctx.delay(seconds=1)\n\n # to improve completeness of removal\n for clearance in [0.7, 0.4, 0.2, 0]:\n p300.aspirate(20, well.bottom(clearance))\n\n del ctx.max_speeds['A'] # reset to default\n del ctx.max_speeds['Z'] # reset to default\n\n p300.drop_tip()\n\n # transfer tube to well\n _pick_up(p300)\n\n # effective tip capacity 280 with 20 uL air gap\n reps = math.ceil(transfer_vol / 280)\n\n vol = transfer_vol / reps\n\n for rep in range(reps):\n p300.move_to(tube.top())\n p300.air_gap(20)\n p300.aspirate(vol, tube.bottom(0.2))\n p300.dispense(vol+20, well.top(-1), rate=1.5)\n ctx.delay(seconds=1)\n\n p300.drop_tip()\n\n # track final used tip\n if not ctx.is_simulating():\n if not os.path.isdir(folder_path):\n os.mkdir(folder_path)\n data = {pip.name: tip_log[pip]['count'] for pip in tip_log}\n with open(tip_file_path, 'w') as outfile:\n json.dump(data, outfile)\n","sub_path":"protocols/121d15-2-96-Greiner-1000/redoreplacementpicking.ot2.apiv2.py","file_name":"redoreplacementpicking.ot2.apiv2.py","file_ext":"py","file_size_in_byte":6536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"22325254","text":"n = int(input())\ndic = (i for i in range(n))\nwhile True:\n ip = input()\n if ip == 'HELP':\n break\n if ip not in ('YES', 'NO', 'HELP'):\n mlp = set(map(int, input().split()))\n if ip == 'YES':\n dic = dic & mlp\n if ip == 'NO':\n dic = dic - mlp\nprint(*dic)\n","sub_path":"files/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"395228988","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function\nimport collections\nimport json\nimport logging\nimport os\nimport time\nimport warnings\nimport copy\nimport sys\nimport threading\nimport librosa\nimport numpy as np\nimport sounddevice as sd\nimport queue\nimport os\n\n\nimport soundfile as sf\nclass confirmIdentity:\n\n ###########################################################################################\n ###########################################################################################\n #Adding constants for the audio.###########################################################\n ###########################################################################################\n ###########################################################################################\n\n ROOT_FILE_PATH = os.path.dirname(os.path.realpath(__file__)) #The path where this file is located.\n\n MODEL_LABELS_PATH = ROOT_FILE_PATH + '/model_labels.json' #The location of model labels.\n\n MODEL_H5_PATH = ROOT_FILE_PATH + '/model.h5' #The location of model.h5 file.\n\n MODEL_JSON_PATH = ROOT_FILE_PATH + '/model.json' #The location of model.json file.\n\n AUDIO_DEVICE = 0 # Recording device name as listed by `python -m sounddevice`\n\n AUDIO_DURATION = 10 # Duration of audio material to retain, in seconds\n\n SAMPLING_RATE = 44100# Audio sampling rate, other parameters are hand-tuned for 44.1 kHz\n\n CHUNK_SIZE = 882 # Spectrogram hop_size, 882 samples @ 44.1 kHz = 20 ms\n FFT_SIZE = 2 * CHUNK_SIZE # Spectrogram FFT window length\n BLOCK_SIZE = 16 * CHUNK_SIZE # Size of sound device audio capture buffer\n PREDICTION_STEP = 5 # How often new predictions should be output, in blocks\n PREDICTION_STEP_IN_MS = int(PREDICTION_STEP * BLOCK_SIZE / SAMPLING_RATE * 1000)\n SEGMENT_LENGTH = 100 # Lookback window for classification, in chunks, 100 @ 20 ms = 2 s\n\n PROCESSING_DELAY = 0 # Audio streaming delay compensation, in processing steps\n\n MEL_BANDS = 80 # Number of mel frequency bands\n MEL_FREQS = librosa.core.mel_frequencies(n_mels=MEL_BANDS)\n\n AUDIO_MEAN = 20.0\n AUDIO_STD = 20.0\n\n Overlap = int(BLOCK_SIZE/2)\n\n\n\n\n\n ###########################################################################################\n ###########################################################################################\n #Adding constants for the audio.###########################################################\n ###########################################################################################\n ###########################################################################################\n logger = None\n signal = None\n spectoram = None\n audio_queue = None\n last_chunk = None\n predictions = None\n live_audio_feed = None\n model = None\n q = None\n event = None\n\n def __init__(self):\n self.q = queue.Queue(maxsize=self.BLOCK_SIZE)\n self.event = threading.Event()\n\n\n logging.basicConfig(level=logging.DEBUG)\n self.logger = logging.getLogger(__name__)\n\n with open(self.MODEL_LABELS_PATH, 'r') as labels_file:\n self.labels = json.load(labels_file)\n\n\n self.signal = np.zeros((self.AUDIO_DURATION * self.SAMPLING_RATE, 1), dtype='float32')\n self.spectrogram = np.zeros((self.MEL_BANDS, self.AUDIO_DURATION * self.SAMPLING_RATE // self.CHUNK_SIZE), dtype='float32')\n self.audio_queue = collections.deque(maxlen=1000) # Queue for incoming audio blocks\n self.last_chunk = np.zeros((self.CHUNK_SIZE, 1), dtype='float32') # Short term memory for the next step\n\n self.predictions = np.zeros((len(self.labels), self.AUDIO_DURATION * self.SAMPLING_RATE // (self.BLOCK_SIZE * self.PREDICTION_STEP)), dtype='float32')\n self.live_audio_feed = collections.deque(maxlen=1)\n self.model = None\n\n\n\n def get_raspberry_stats(self):\n freq = None\n temp = None\n try:\n with open('/sys/class/thermal/thermal_zone0/temp', 'r') as file:\n temp = int(file.read())\n temp /= 1000.\n temp = np.round(temp, 1)\n temp = '{}\\'C'.format(temp)\n with open('/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq', 'r') as file:\n freq = int(file.read())\n freq /= 1000.\n freq = '{} MHz'.format(int(freq))\n except:\n pass\n\n return temp, freq\n\n def get_predictions(self):\n print(self.predictions)\n\n\n def start(self, pathToAudioFile):\n self.targetsToStore = []\n # Import classifier model\n self.logger.info('Initializing a convolutional neural network model...')\n global model\n\n THEANO_FLAGS = ('device=cpu,'\n 'floatX=float32,'\n 'dnn.conv.algo_bwd_filter=deterministic,'\n 'dnn.conv.algo_bwd_data=deterministic')\n\n os.environ['THEANO_FLAGS'] = THEANO_FLAGS\n os.environ['KERAS_BACKEND'] = 'theano'\n\n import keras\n keras.backend.set_image_dim_ordering('th')\n\n with open(self.MODEL_JSON_PATH, 'r') as file:\n cfg = file.read()\n model = keras.models.model_from_json(cfg)\n\n model.load_weights(self.MODEL_H5_PATH)\n self.logger.debug('Loaded Keras model with weights.')\n\n #Import recorded autio and distribute as chunks.\n for block in sf.blocks(pathToAudioFile, blocksize=self.BLOCK_SIZE, overlap=self.Overlap, dtype='float32', always_2d=True):\n self.audio_queue.append(copy.deepcopy(block))\n print(np.shape(block))\n\n blocks = []\n processing_queue = collections.deque()\n # Process incoming audio blocks\n keepGoing = True\n while keepGoing:\n if(self.audio_queue.__len__() < 1):\n keepGoing = False\n\n while len(self.audio_queue) > 0 and len(blocks) < self.PREDICTION_STEP:\n blocks.append(self.audio_queue.popleft())\n if len(blocks) == self.PREDICTION_STEP:\n new_audio = np.concatenate(blocks)\n\n # Populate audio for live streaming\n self.live_audio_feed.append(new_audio[:, 0].copy())\n\n blocks = []\n processing_queue.append(new_audio)\n\n if len(processing_queue) > self.PROCESSING_DELAY + 1: # +1 for JavaScript streaming delay\n start_time = time.time()\n\n # Populate audio signal\n step_audio = processing_queue.pop()\n n_samples = len(step_audio)\n self.signal[:-n_samples] = self.signal[n_samples:]\n self.signal[-n_samples:] = step_audio[:]\n\n # Populate spectrogram\n new_spec = librosa.feature.melspectrogram(np.concatenate([self.last_chunk, step_audio])[:, 0],\n self.SAMPLING_RATE, n_fft=self.FFT_SIZE,\n hop_length=self.CHUNK_SIZE, n_mels=self.MEL_BANDS)\n with warnings.catch_warnings():\n warnings.simplefilter('ignore') # Ignore log10 zero division\n new_spec = librosa.core.perceptual_weighting(new_spec, self.MEL_FREQS, amin=1e-5,\n ref_power=1e-5, top_db=None)\n new_spec = np.clip(new_spec, 0, 100)\n n_chunks = np.shape(new_spec)[1]\n self.spectrogram[:, :-n_chunks] = self.spectrogram[:, n_chunks:]\n self.spectrogram[:, -n_chunks:] = new_spec\n\n # Classify incoming audio\n self.predictions[:, :-1] = self.predictions[:, 1:]\n offset = self.SEGMENT_LENGTH // 2\n pred = self.classify([\n np.stack([self.spectrogram[:, -(self.SEGMENT_LENGTH + offset):-offset]]),\n np.stack([self.spectrogram[:, -self.SEGMENT_LENGTH:]]),\n ])\n self.predictions[:, -1] = pred\n target = self.labels[np.argmax(pred)]\n self.targetsToStore.append(target)\n # Clean up\n self.last_chunk[:] = step_audio[-self.CHUNK_SIZE:]\n\n end_time = time.time()\n time_spent = int((end_time - start_time) * 1000)\n temp, freq = self.get_raspberry_stats()\n blocks_in_ms = int(self.PREDICTION_STEP * self.BLOCK_SIZE / self.SAMPLING_RATE * 1000)\n msg = '[{}] {}% = {} ms / {} ms ({} blocks) - temp: {} | freq: {} ==> {}'\n timestamp = time.strftime('%H:%M:%S')\n self.logger.debug(msg.format(timestamp, np.round(time_spent / blocks_in_ms * 100, 1),\n time_spent, blocks_in_ms, self.PREDICTION_STEP, temp, freq, target))\n\n time.sleep(0.05)\n\n\n def classify(self, segments):\n X = np.stack(segments)\n X -= self.AUDIO_MEAN\n X /= self.AUDIO_STD\n pred = model.predict(X)\n pred = np.average(pred, axis=0, weights=np.arange(len(pred)) + 1)\n return pred\n\n\n\n #gets the most common occurance of an identity\n def getTarget(self):\n counter = 0\n if(self.targetsToStore.__len__() > 1):\n num = self.targetsToStore[0]\n for i in self.targetsToStore:\n appearance = self.targetsToStore.count(i)\n if(appearance > counter):\n counter = appearance\n num = i\n return num\n else:\n noresponse = \"No known noise was detected!\"\n return noresponse","sub_path":"audio.py","file_name":"audio.py","file_ext":"py","file_size_in_byte":9738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"497303169","text":"\"\"\"\nProject Euler Problem #28\n==========================\n\nStarting with the number 1 and moving to the right in a clockwise\ndirection a 5 by 5 spiral is formed as follows:\n\n 21 22 23 24 25\n 20 7 8 9 10\n 19 6 1 2 11\n 18 5 4 3 12\n 17 16 15 14 13\n\nIt can be verified that the sum of both diagonals is 101.\n\nWhat is the sum of both diagonals in a 1001 by 1001 spiral formed in the\nsame way?\n\"\"\"\n\nfrom math import floor\nfrom pprint import PrettyPrinter\n\ndef fill_grid(size):\n ''' This is ugly as sin. Figure out a cleaner way to do it.'''\n\n total_elements = size**2\n\n middle = floor(size / 2)\n\n grid = [[0]*size for _ in range(size)]\n\n direction_steps = 1\n\n grid[middle][middle] = 1\n curr_element = 2\n\n x_pos, y_pos = middle, middle\n while True:\n for move in [[1,0],[0,1]]:\n for _ in range(direction_steps):\n x_pos += move[0]\n y_pos += move[1]\n\n grid[x_pos][y_pos] = curr_element\n\n if curr_element == total_elements:\n return grid\n else:\n curr_element += 1\n\n for move in [[-1,0],[0,-1]]:\n for _ in range(direction_steps+1):\n x_pos += move[0]\n y_pos += move[1]\n\n grid[x_pos][y_pos] = curr_element\n\n if curr_element == total_elements:\n return grid\n else:\n curr_element += 1\n\n direction_steps += 2\n\n\ndef sum_diagonals(grid):\n\n total = 0\n\n for i in range(len(grid)):\n total += grid[i][i]\n total += grid[len(grid)-1-i][i]\n\n middle = floor(len(grid) / 2)\n total -= grid[middle][middle]\n\n return total\n\n# ------------------------------------------------------\n\nprint(sum_diagonals(fill_grid(1001)))\n","sub_path":"028.py","file_name":"028.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"211398358","text":"import sys, os, ROOT, argparse\nfrom collections import defaultdict\n\nROOT.TH1.SetDefaultSumw2()\nROOT.gROOT.SetBatch(True)\nROOT.gStyle.SetOptStat(\"\")\nROOT.gStyle.SetPaintTextFormat(\"3.2f\")\nROOT.gStyle.SetFrameLineWidth(2)\n\nusage = \"usage: %prog [options]\"\nparser = argparse.ArgumentParser(usage)\nparser.add_argument(\"--inputDir\", dest=\"inputDir\", help=\"Path to input\", default=\"NULL\", type=str) \n\narg = parser.parse_args()\n\nOPTIONSMAP = {\"h_njets_1l_HT300_ge7j_ge1b_Mbl_d1\" : {\"X\" : {\"min\" : 7, \"max\" : 15, \"title\" : \"N_{J} D1\"}},\n \"h_njets_1l_HT300_ge7j_ge1b_Mbl_d2\" : {\"X\" : {\"min\" : 7, \"max\" : 15, \"title\" : \"N_{J} D2\"}},\n \"h_njets_1l_HT300_ge7j_ge1b_Mbl_d3\" : {\"X\" : {\"min\" : 7, \"max\" : 15, \"title\" : \"N_{J} D3\"}},\n \"h_njets_1l_HT300_ge7j_ge1b_Mbl_d4\" : {\"X\" : {\"min\" : 7, \"max\" : 15, \"title\" : \"N_{J} D4\"}},\n \"h_njets_1l_HT300_ge7j_ge1b_Mbl\" : {\"X\" : {\"min\" : 7, \"max\" : 15, \"title\" : \"N_{J}\"}}\n}\n\ndef doOptions(histo, histoName):\n\n is1D = \"TH1\" in histo.ClassName()\n\n for axis, options in OPTIONSMAP[histoName].iteritems():\n\n if axis == \"X\":\n if \"rebin\" in options:\n if is1D: histo.Rebin(options[\"rebin\"])\n else: histo.RebinX(options[\"rebin\"])\n if \"min\" in options and \"max\" in options: histo.GetXaxis().SetRangeUser(options[\"min\"],options[\"max\"])\n if \"title\" in options: histo.GetXaxis().SetTitle(options[\"title\"])\n if axis == \"Y\":\n if \"rebin\" in options:\n if is1D: histo.Rebin(options[\"rebin\"])\n else: histo.RebinY(options[\"rebin\"])\n if \"min\" in options and \"max\" in options: histo.GetYaxis().SetRangeUser(options[\"min\"],options[\"max\"])\n if \"title\" in options: histo.GetYaxis().SetTitle(options[\"title\"])\n if axis == \"Z\":\n if \"min\" in options and \"max\" in options: histo.GetZaxis().SetRangeUser(options[\"min\"],options[\"max\"])\n\ndef prettyHisto(histo,magicFactor=1.0,magicFactor2=1.0):\n histo.GetYaxis().SetLabelSize(magicFactor*0.055); histo.GetYaxis().SetTitleSize(magicFactor*0.08); histo.GetYaxis().SetTitleOffset(0.7/magicFactor)\n histo.GetXaxis().SetLabelSize(magicFactor*0.055); histo.GetXaxis().SetTitleSize(magicFactor*0.08); histo.GetXaxis().SetTitleOffset(0.8/magicFactor2)\n histo.GetZaxis().SetLabelSize(magicFactor*0.055); histo.GetZaxis().SetTitleSize(magicFactor*0.06)\n\ndef fillMap(inRootFile, theMap):\n\n if \".root\" not in inRootFile: return\n histoFile = ROOT.TFile.Open(inRootFile, \"READ\")\n for hkey in histoFile.GetListOfKeys():\n if \"TH\" not in hkey.GetClassName(): continue\n\n if hkey.GetName() == \"EventCounter\" or hkey.GetName().find(\"njets\") == -1: continue\n\n histo = hkey.ReadObj()\n histo.SetDirectory(0)\n\n histo.Sumw2()\n \n theMap.setdefault(hkey.GetName(), histo)\n\nif __name__ == '__main__':\n\n XCANVAS = 2400; YCANVAS = 2400\n\n if arg.inputDir == \"NULL\": quit()\n stub = arg.inputDir.split(\"condor/\")[-1]\n\n inRootFile = arg.inputDir + \"/2017_MC.root\"\n \n outpath = \"./plots/%s/\"%(stub)\n if not os.path.exists(outpath): os.makedirs(outpath)\n\n mapPFAhistos = {}\n\n fillMap(inRootFile, mapPFAhistos)\n\n # Save the final histograms\n\n njetsD1 = mapPFAhistos[\"h_njets_1l_HT300_ge7j_ge1b_Mbl_d1\"]; prettyHisto(njetsD1)\n njetsD2 = mapPFAhistos[\"h_njets_1l_HT300_ge7j_ge1b_Mbl_d2\"]; prettyHisto(njetsD2)\n njetsD3 = mapPFAhistos[\"h_njets_1l_HT300_ge7j_ge1b_Mbl_d3\"]; prettyHisto(njetsD3)\n njetsD4 = mapPFAhistos[\"h_njets_1l_HT300_ge7j_ge1b_Mbl_d4\"]; prettyHisto(njetsD4)\n\n njets = mapPFAhistos[\"h_njets_1l_HT300_ge7j_ge1b_Mbl\"]; prettyHisto(njets)\n\n XMin = 0; XMax = 1\n YMin = 0; YMax = 1\n\n njetsD1.SetTitle(\"\"); njetsD1.Scale(1./njetsD1.Integral()); doOptions(njetsD1, \"h_njets_1l_HT300_ge7j_ge1b_Mbl_d1\")\n njetsD2.SetTitle(\"\"); njetsD2.Scale(1./njetsD2.Integral()); doOptions(njetsD2, \"h_njets_1l_HT300_ge7j_ge1b_Mbl_d2\")\n njetsD3.SetTitle(\"\"); njetsD3.Scale(1./njetsD3.Integral()); doOptions(njetsD3, \"h_njets_1l_HT300_ge7j_ge1b_Mbl_d3\")\n njetsD4.SetTitle(\"\"); njetsD4.Scale(1./njetsD4.Integral()); doOptions(njetsD4, \"h_njets_1l_HT300_ge7j_ge1b_Mbl_d4\")\n njets.SetTitle(\"\"); njets.Scale(1./njets.Integral()); doOptions(njets, \"h_njets_1l_HT300_ge7j_ge1b_Mbl\")\n\n njetsD1.Divide(njets); njetsD1.SetMinimum(0.50); njetsD1.SetMaximum(1.50); njetsD1.GetYaxis().SetNdivisions(308)\n njetsD2.Divide(njets); njetsD2.SetMinimum(0.50); njetsD2.SetMaximum(1.50); njetsD2.GetYaxis().SetNdivisions(308)\n njetsD3.Divide(njets); njetsD3.SetMinimum(0.50); njetsD3.SetMaximum(1.50); njetsD3.GetYaxis().SetNdivisions(308)\n njetsD4.Divide(njets); njetsD4.SetMinimum(0.50); njetsD4.SetMaximum(1.50); njetsD4.GetYaxis().SetNdivisions(308)\n\n njetsD1.SetMarkerColor(ROOT.kBlack); njetsD1.SetLineColor(ROOT.kBlack); njetsD1.SetMarkerSize(4); njetsD1.SetMarkerStyle(20); njetsD1.SetLineWidth(3)\n njetsD2.SetMarkerColor(ROOT.kRed); njetsD2.SetLineColor(ROOT.kRed); njetsD2.SetMarkerSize(4); njetsD2.SetMarkerStyle(20); njetsD2.SetLineWidth(3)\n njetsD3.SetMarkerColor(ROOT.kBlue); njetsD3.SetLineColor(ROOT.kBlue); njetsD3.SetMarkerSize(4); njetsD3.SetMarkerStyle(20); njetsD3.SetLineWidth(3)\n njetsD4.SetMarkerColor(ROOT.kGreen+2); njetsD4.SetLineColor(ROOT.kGreen+2); njetsD4.SetMarkerSize(4); njetsD4.SetMarkerStyle(20); njetsD4.SetLineWidth(3)\n\n mvaBins = [\"D1\", \"D2\", \"D3\", \"D4\"]\n\n for mva in mvaBins:\n\n c1 = ROOT.TCanvas(\"njets%s\"%(mva), \"njets%s\"%(mva), XCANVAS, YCANVAS); \n c1.cd(); ROOT.gPad.SetPad(XMin, YMin, XMax, YMax)\n\n ROOT.gPad.SetGridy(); ROOT.gPad.SetGridx()\n ROOT.gPad.SetTopMargin(0.03)\n ROOT.gPad.SetLeftMargin(0.11)\n ROOT.gPad.SetBottomMargin(0.15)\n ROOT.gPad.SetRightMargin(0.04)\n\n if mva == \"D1\": njetsD1.Draw(\"L\")\n elif mva == \"D2\": njetsD2.Draw(\"L\")\n elif mva == \"D3\": njetsD3.Draw(\"L\")\n elif mva == \"D4\": njetsD4.Draw(\"L\")\n\n c1.SaveAs(\"%s/njets%s_Total_Ratio.pdf\"%(outpath,mva))\n","sub_path":"Analyzer/test/finalNJetsRatioPlots.py","file_name":"finalNJetsRatioPlots.py","file_ext":"py","file_size_in_byte":6092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"226553841","text":"import os\nimport configparser\n\nfrom util.repo_handling.repo_file import repo_file\n\n\nclass GitRepository(object):\n\n worktree = None\n gitdir = None\n conf = None\n\n def __init__(self, path, force=False):\n self.worktree = path\n self.gitdir = os.path.join(path, \".git\")\n\n if not (force or os.path.isdir(self.gitdir)):\n raise Exception(\"Not a Git repository %s\" % path)\n\n # Read configuration file in .git/config\n self.conf = configparser.ConfigParser()\n cf = repo_file(self, \"config\")\n\n if cf and os.path.exists(cf):\n self.conf.read([cf])\n\n elif not force:\n raise Exception(\"Configuration file missing\")\n\n if not force:\n vers = int(self.conf.get(\"core\", \"repositoryformatversion\"))\n if vers != 0:\n raise Exception(\"Unsupported repositoryformatversion %s\" % vers)\n","sub_path":"objects/GitRepository.py","file_name":"GitRepository.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"289978453","text":"#!/usr/bin/env python3\r\n\r\nimport sys\r\n\r\ninput_file = sys.argv[1]\r\nprint(\"Output: {}\".format(sys.argv[1]))\r\nfilereader = open(input_file, 'r')\r\nfor row in filereader:\r\n print(row.strip())\r\nfilereader.close()\r\n","sub_path":"first_script.py","file_name":"first_script.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"555834940","text":"from .models import Question, Answer, Tag, User\nfrom .serializers import QuestionSerializer, AnswerSerializer, UserSerializer, TagSerializer\nfrom rest_framework import status\nfrom rest_framework.permissions import IsAdminUser\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\n\nfrom questions import serializers\n# from .serializers import \n\n@api_view(['GET'])\ndef questionList(request):\n questions = Question.objects.all()\n serializer = QuestionSerializer(questions, many=True)\n return Response(serializer.data)\n\n@api_view(['GET'])\ndef questionDetail(request, pk):\n questions = Question.objects.get(id=pk)\n serializer = QuestionSerializer(questions, many=False)\n return Response(serializer.data)\n\n@api_view(['POST'])\ndef questionCreate(request):#save logged user in request\n serializer = QuestionSerializer(data=request.data)\n \n if serializer.is_valid():\n serializer.save(user=request.user)\n \n return Response(serializer.data)\n\n@api_view(['PUT'])\ndef questionEdit(request, pk):\n question = Question.objects.get(id=pk)\n serializer = QuestionSerializer(instance=question, data=request.data)\n\n if serializer.is_valid():\n serializer.save()\n\n return Response(serializer.data)\n\n@api_view(['DELETE'])\ndef questionDelete(request, pk):\n question = Question.objects.get(id=pk)\n question.delete()\n\n return Response('Your question has been deleted.')\n\n@api_view(['GET'])\ndef answerList(request):\n answers = Answer.objects.all()\n serializer = AnswerSerializer(answers, many=True)\n return Response(serializer.data)\n\n@api_view(['GET'])\ndef answerDetail(request, pk):\n answers = Answer.objects.get(id=pk)\n serializer = AnswerSerializer(answers, many=False)\n return Response(serializer.data)\n\n@api_view(['POST'])\ndef answerCreate(request):\n serializer = AnswerSerializer(data=request.data)\n question=Question.objects.get(id=request.data[\"question\"])\n \n if serializer.is_valid():\n serializer.save(user=request.user, question=question)\n \n return Response(serializer.data)\n\n@api_view(['GET'])\ndef tagList(request):\n tags = Tag.objects.all()\n serializer = TagSerializer(tags, many=True)\n return Response(serializer.data)\n\n@api_view(['GET'])\ndef tagDetail(request, pk):\n tags = Tag.objects.get(id=pk)\n serializer = TagSerializer(tags, many=False)\n return Response(serializer.data)\n\n@api_view(['POST'])\ndef tagCreate(request):\n serializer = TagSerializer(data=request.data)\n \n if serializer.is_valid():\n serializer.save()\n \n return Response(serializer.data)","sub_path":"questions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"100222567","text":"\"\"\"\nModule\n------\nentry.py:\n\nSummary\n-------\nContains routines to facilitate entry of required input data objects, either from manual user input or from\na data file (csv).\n\nNotes\n-----\nMay include database access in the future to save having to create a csv from catalogue after update\n\n\"\"\"\n# Imports included here:\nimport re\n\n# Astropy\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.coordinates.name_resolve import NameResolveError\nfrom astropy.io import ascii\nfrom astropy.table import Table\n\nfrom LCExtract import config\n\n\ndef setFilterUsage():\n # uses global filterSelection\n\n getch = input('Please select filters to display (e.g. griz)....: ')\n # if no entry set default to griz, or check for valid filter combinations\n config.filterSelection = getch\n print()\n\n\ndef setEntryType():\n print('Script will accept file or manual input. Default is manual.')\n while True:\n getch = input(f'Please select file (f) or manual object (m) entry..........: ')\n if getch == '':\n getch = 'm'\n if getch[0].lower() in ('f', 'm'):\n break\n print()\n\n return getch[0].lower()\n\n\ndef setManualEntryType():\n while True:\n getch = input(f'Please select named object (n) or coordinate (c) entry..........: ')\n if getch == '':\n continue\n if getch[0].lower() in ('n', 'c'):\n break\n print()\n\n return getch[0].lower()\n\n\ndef getObjectsCSV():\n # uses global defaultFileName\n error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError)\n while True:\n getch = input(f'Please enter filename, or for default ({config.defaultFileName})...: ')\n getch = config.defaultFileName if getch == '' else getch\n try:\n f = open(getch)\n except error_to_catch:\n print(f'Unable to locate file \"{getch}\". Please try again.')\n else:\n f.close()\n print(f'Using file \"{getch}\".')\n break\n\n data = ascii.read(getch, guess=False, format='csv', header_start=0, data_start=1)\n return data\n\n\ndef getUserObject():\n manualEntryType = setManualEntryType()\n if manualEntryType == 'n': # named object entry\n while True:\n tempName = input('Enter object name....: ')\n try:\n c = SkyCoord.from_name(tempName, parse=True)\n except NameResolveError:\n print('Unable to resolve. Please try again.')\n else:\n print(f'Object {tempName} found in catalog.')\n break\n elif manualEntryType == 'c': # object coordinate entry\n while True:\n print('Enter object coordinates (ICRS frame. Deg assumed unless specified).')\n tempCoordRA = input('RA (e.g. 10.625, 10d37m30s, 0h42m30s, 00 42 30)....: ')\n tempCoordRA += 'd' if not re.findall('[hdms]', tempCoordRA) else ''\n tempCoordDEC = input('DEC (e.g. 41.2, 41d12m00s, +41 12 00)...: ')\n tempCoordDEC += 'd' if not re.findall('[dms]', tempCoordDEC) else ''\n try:\n c = SkyCoord(tempCoordRA, tempCoordDEC)\n except ValueError:\n print('Unable to identify position. Please try again.')\n except u.UnitsError:\n print('Units error occurred. Please try again.')\n else:\n print(f'Object at {c.to_string(\"hmsdms\")} found.')\n tempName = 'Object in ' + c.get_constellation()\n break\n print()\n manual = [{'Name': tempName, # 'Name': 'Sky position: 153.139, 53.117',\n 'RA': c.ra.degree, # 'RA': 153.1393271,\n 'DEC': c.dec.degree, # 'DEC': 53.117343,\n 'Description': f'Position: {c.to_string(\"hmsdms\")} '}] # 'Description': 'Manual input test'\n return manual\n\n\ndef getObjects():\n entryType = setEntryType()\n if entryType == 'f':\n return getObjectsCSV()\n elif entryType == 'm':\n singleObjectData = getUserObject()\n\n tbl = Table(rows=singleObjectData)\n return tbl\n","sub_path":"build/lib/LCExtract/entry.py","file_name":"entry.py","file_ext":"py","file_size_in_byte":4095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"524866899","text":"# vim: set et ts=4 sw=4 fileencoding=utf-8:\n'''\nModule for processing key/value files like vfms.\n'''\n\nimport re\n\nKV_PATTERN = re.compile(r'''((?:[^\\s\"']|\"[^\"]*\"|'[^']*')+)''')\nOB_PATTERN = re.compile(r'''^(\"\\w+[\\w\\s*]+\"|\\w+)$''')\n\n\ndef parse(kvfile):\n '''\n Parse the key/value file.\n\n Returns the key/value data as a dict.\n '''\n ret = {}\n key = None\n val = None\n while True:\n line = kvfile.readline()\n if line:\n line = line.strip()\n if line and not line.startswith('//'):\n if line.startswith('}'):\n return ret\n elif line.startswith('{'):\n val = parse(kvfile)\n ret[key.strip('\"')] = val\n else:\n key = OB_PATTERN.findall(line)\n if key:\n key = key[0]\n else:\n key, val = KV_PATTERN.findall(line)\n ret[key.strip('\"')] = val.strip('\"')\n else:\n return ret\n\n\ndef persist(kvdict, outfile, indent=''):\n '''\n Persist the key/value dict to the file.\n '''\n for key, val in kvdict.items():\n if isinstance(val, dict):\n outfile.write(u'{0}{1}\\n'.format(indent, key))\n outfile.write(u'{0}{{\\n'.format(indent))\n persist(val, outfile, '\\t{0}'.format(indent))\n outfile.write(u'{0}}}\\n'.format(indent))\n else:\n outfile.write(u'{0}\"{1}\" \"{2}\"\\n'.format(indent, key, val))\n","sub_path":"nail/util/kvf.py","file_name":"kvf.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"249974860","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.views import View\nfrom datetime import datetime\n\nfrom .models import *\n\n# Create your views here.\n\ntoday = datetime.today().strftime('%Y-%m-%d')\n\n\ndef index(request):\n Halls = Hall.objects.all()\n status = {}\n\n for Hall in Halls:\n if Hall.reservation_set.filter(date=today):\n status[Hall.id] = 'Busy'\n else:\n status[Hall.id] = 'Free'\n ctx = {\n 'Halls': Halls,\n 'status': status,\n }\n return render(request, 'Book/index.html', ctx)\n\n\ndef Hall(request, id):\n Hall = Hall.objects.get(pk=int(id))\n if Hall:\n reservations = Hall.reservation_set.filter(date__gte=today).order_by('date')\n Halls = Hall.objects.all()\n if Hall.projector == True:\n projector = \"Yes\"\n else:\n projector = \"No\"\n ctx = {\n \"Hall\": Hall,\n \"projector\": projector,\n \"reservations\": reservations,\n \"Halls\": Halls,\n }\n else:\n ctx = {\n \"Hall\": 'Hall Not Available',\n \"projector\": 'NA',\n \"reservations\": 'NA',\n \"Halls\": 'NA',\n }\n return render(request, 'Book/Hall.html', ctx)\n\n\nclass NewHallView(View):\n\n def get(self, request):\n return render(request, 'Book/new_Hall.html')\n\n def post(self, request):\n try:\n name = request.POST.get(\"name\")\n capacity = request.POST.get(\"capacity\")\n projector = request.POST.get(\"projector\")\n proj = True if projector == \"True\" else False\n\n Hall.objects.create(name=name, capacity=capacity, projector=proj)\n return redirect(\"/\")\n\n except Exception as e:\n message = \"Incorrect Data: {}\".format(e)\n ctx = {\n \"message\": message,\n }\n return render(request, 'Book/new_Hall.html', ctx)\n\n\nclass ModifyView(View):\n\n def get(self, request, id):\n Hall = Hall.objects.get(pk=id)\n ctx = {\n \"Hall\": Hall,\n }\n return render(request, 'Book/modify.html', ctx)\n\n def post(self, request, id):\n name = request.POST.get(\"name\")\n capacity = request.POST.get(\"capacity\")\n projector = True if request.POST.get('projector') else False\n Hall = Hall.objects.get(pk=id)\n try:\n Hall.name = name\n Hall.capacity = capacity\n Hall.projector = projector\n Hall.save()\n return redirect(\"/\")\n except Exception as e:\n message = \"Incorrect Data: {}\".format(e)\n ctx = {\n \"message\": message,\n \"Hall\": Hall,\n }\n return render(request, 'Book/modify.html', ctx)\n\n\nclass DeleteView(View):\n\n def get(self, request, id):\n Hall = Hall.objects.get(pk=id)\n ctx = {\n \"Hall\": Hall,\n }\n return render(request, 'Book/delete.html', ctx)\n\n def post(self, request, id):\n action = request.POST.get(\"submit\")\n\n if action == \"Yes\":\n Hall = Hall.objects.get(pk=id)\n Hall.delete()\n return redirect(\"/\")\n\n\nclass ReservationView(View):\n\n def get(self, request, id):\n Hall = Hall.objects.get(pk=id)\n reservations = Hall.reservation_set.filter(date__gte=today).order_by('date')\n ctx = {\n \"Hall\": Hall,\n \"reservations\": reservations,\n }\n return render(request, 'Book/reservation.html', ctx)\n\n def post(self, request, id):\n Hall = Hall.objects.get(pk=id)\n reservations = Hall.reservation_set.filter(date__gte=today).order_by('date')\n try:\n date = request.POST.get(\"date\")\n comment = request.POST.get(\"comment\")\n message = \"\"\n\n if Hall.reservation_set.filter(date=date):\n message = \"This Hall is already occupied for that day\"\n elif date < today:\n message = \"The chosen data can not be in the past\"\n\n if (message == \"This Hall is already occupied for that day\"\n or message == \"The chosen data can not be in the past\"):\n ctx = {\n \"Hall\": Hall,\n \"reservations\": reservations,\n \"message\": message,\n }\n return render(request, 'Book/reservation.html', ctx)\n\n reservation = Reservation.objects.create(date=date, comment=comment)\n reservation.Hall.add(Hall)\n\n except Exception as e:\n message = \"Incorrect Data: {}\".format(e)\n ctx = {\n \"message\": message,\n \"Hall\": Hall,\n \"reservations\": reservations,\n }\n return render(request, 'Book/reservation.html', ctx)\n\n if Hall.projector == True:\n projector = \"TAK\"\n else:\n projector = \"NIE\"\n message = \"\"\"Dziękujemy! Zarezerwowałeś salę: \n {} w dniu: {}\"\"\".format(Hall.name, date)\n ctx = {\n \"Hall\": Hall,\n \"projector\": projector,\n \"reservations\": reservations,\n \"message\": message,\n }\n return render(request, 'Book/Hall.html', ctx)\n\n\nclass SearchView(View):\n\n def get(self, request):\n Hall = request.GET.get(\"Hall\")\n capacity = request.GET.get(\"capacity\")\n date = request.GET.get(\"date\")\n projector = True if request.GET.get('projector') else False\n\n result1 = Hall.objects.exclude(reservation__date=date)\n\n if Hall == \"\":\n result2 = result1\n else:\n result2 = result1.filter(name__icontains=Hall)\n\n if capacity != \"\":\n result3 = result2.filter(capacity__gte=int(capacity))\n else:\n result3 = result2\n\n if projector:\n result4 = result3.filter(projector=projector)\n else:\n result4 = result3\n\n ctx = {\n \"results\": result4,\n \"date\": date,\n }\n return render(request, 'Book/search.html', ctx)\n\n\n\n\n\n","sub_path":"BookConferenceHallApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"491428025","text":"\"\"\"\nQ031 Next Permutation\nMedium\n\nArray;\n\nthis solution passed but it's not in place!\n\nImplement next permutation, which rearranges numbers\ninto the lexicographically next greater permutation of numbers.\n(that means the order in dictionary)\n\nIf such arrangement is not possible, it must rearrange it\nas the lowest possible order (ie, sorted in ascending order).\n\nThe replacement must be in-place and use only constant extra\nmemory.\n\nHere are some examples. Inputs are in the left-hand column\nand its corresponding outputs are in the right-hand column.\n\n1,2,3 → 1,3,2\n3,2,1 → 1,2,3\n1,1,5 → 1,5,1\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n def nextPermutation(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n def swap(i):\n for j in range(i+1, total):\n if nums[i] < nums[j]:\n nums[i], nums[j] = nums[j], nums[i]\n return j\n return False\n\n total = len(nums)\n\n for i in reversed(range(0, total-1)):\n # swap if the previous value is smaller\n # than any of the past values\n # and choose the smallest past value\n if swap(i):\n break\n # sort the numbers after\n nums[i:] = sorted(nums[i:])\n\n\na = [1,1,1]\n\nsol = Solution()\nsol.nextPermutation(a)\nprint(a)","sub_path":"Q031.py","file_name":"Q031.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"20235576","text":"class car:\r\n def __init__(self,manufacture,model,make,transmission,color):\r\n self.manufacture = manufacture\r\n self.model = model\r\n self.make = make\r\n self.transmission = transmission\r\n self.color = color\r\n\r\n def accelerate(self):\r\n print((\"{} {} is moving\").format(self.manufacture,self.model))\r\n\r\n def stop(self):\r\n print((\"{} {} has stopped\").format(self.manufacture,self.model))\r\n\r\nc1 = car(\"Tata\",\"Altroz\",\"2020\",\"Automatic\",\"Midtown Grey\")\r\nc2 = car(\"Mercedes-Benz\",\"GLA\",\"2021\",\"Automatic\",\"Black\")\r\nc3 = car(\"BMW\",\"X1\",\"2021\",\"Automatic\",\"White\")\r\n\r\nc1.accelerate()\r\nc1.stop()\r\n\r\nc2.accelerate()\r\nc2.stop()\r\n\r\nc3.accelerate()\r\nc3.stop()\r\n\r\n\r\n","sub_path":"python/Activity16.py","file_name":"Activity16.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"574591535","text":"import os\nimport csv\n\ncsvpath=os.path.join('Resources','budget_data.csv')\n\nwith open (csvpath, 'r') as csv_file:\n csv_read=csv.reader(csv_file, delimiter=',')\n \n csv_header=next(csv_read)\n \n date=[]\n pl=[]\n plch=[]\n total_pl = 0.0\n total_plch = 0.0\n max_pld=[]\n min_pld=[]\n \n for budget_data in csv_read:\n date.append(budget_data[0])\n pl.append(budget_data[1])\n\n #The total number of months included in the dataset\n total_months = len(date)\n \n #The net total amount of \"Profit/Losses\" over the entire period\n for row in range(total_months):\n total_pl += float(pl[row])\n \n #The changes in \"Profit/Losses\" over the entire period, then find the average of those changes \n for row1 in range(1, (total_months)):\n plch.append(float(pl[row1]) - float(pl[(row1-1)]))\n total_plch += float(plch[(row1-1)])\n #average\n #total_plch += float(plch[row1])\n ave_plch = total_plch / (total_months - 1)\n \n #The greatest increase in profits (date and amount) over the entire period\n #The greatest decrease in losses (date and amount) over the entire period\n max_pl = max(plch)\n min_pl = min(plch)\n\n date1=[]\n for r1 in range(1,len(plch)):\n date1.append(date[r1])\n maxpl_zip = zip(date1, plch)\n\n mz=list(maxpl_zip)\n \n for row2 in range(len(plch)):\n if plch[row2] == max_pl:\n max_pld = mz[row2] \n elif plch[row2] == min_pl:\n min_pld = mz[row2]\n \n \n print(\"-----------------------------\")\n print(\"Financial Analysis\")\n print(\"-----------------------------\")\n print(f\"Total Months: {total_months}\")\n print(f\"Total: ${int(total_pl)}\")\n print(f\"Average Change: ${round(ave_plch,2)}\")\n print(\"Greatest Increase in Profits: \" + str(max_pld[0]) + \" ($\" + str(int(max_pld[1])) + \")\")\n print(\"Greatest Decrease in Profits: \" + str(min_pld[0]) + \" ($\" + str(int(min_pld[1])) + \")\") \n print(\"'''\")\n\n\noutput_path = os.path.join('Financial_Analysis.txt')\nwith open(output_path, 'w', newline='') as fao: \n\n fao.write(\"----------------------------- \\n\")\n fao.write(\"Financial Analysis \\n\")\n fao.write(\"----------------------------- \\n\")\n fao.write(f\"Total Months: {total_months} \\n\")\n fao.write(f\"Total: ${int(total_pl)} \\n\")\n fao.write(f\"Average Change: ${round(ave_plch,2)} \\n\")\n fao.write(\"Greatest Increase in Profits: \" + str(max_pld[0]) + \" ($\" + str(int(max_pld[1])) + \") \\n\")\n fao.write(\"Greatest Decrease in Profits: \" + str(min_pld[0]) + \" ($\" + str(int(min_pld[1])) + \") \\n\")","sub_path":"PyBank/main_otxt.py","file_name":"main_otxt.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"45446032","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, in_planes, planes, stride=1):\n super(BasicBlock, self).__init__()\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion * planes)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.bn2(self.conv2(out))\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, in_planes, planes, stride=1):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(self.expansion * planes)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion * planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion * planes)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = F.relu(self.bn2(self.conv2(out)))\n out = self.bn3(self.conv3(out))\n out += self.shortcut(x)\n out = F.relu(out)\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, num_blocks, strides=[1, 2, 2, 2], plane=64, num_classes=10):\n super(ResNet, self).__init__()\n self.in_planes = plane\n self.in_planes_1 = plane\n\n self.conv1 = nn.Conv2d(3, plane, kernel_size=3, stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(plane)\n self.layer1 = self._make_layer(block, self.in_planes_1 * np.prod(strides[:1]), num_blocks[0], stride=strides[0])\n self.layer2 = self._make_layer(block, self.in_planes_1 * np.prod(strides[:2]), num_blocks[1], stride=strides[1])\n self.layer3 = self._make_layer(block, self.in_planes_1 * np.prod(strides[:3]), num_blocks[2], stride=strides[2])\n self.layer4 = self._make_layer(block, self.in_planes_1 * np.prod(strides[:4]), num_blocks[3], stride=strides[3])\n self.pool = nn.AdaptiveAvgPool2d((1, 1))\n self.linear = nn.Linear(self.in_planes_1 * np.prod(strides[:4]) * block.expansion, num_classes)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1] * (num_blocks - 1)\n layers = []\n for stride in strides:\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = self.pool(out)\n out = self.linear(out.flatten(1))\n return out\n\n\ndef ResNet10(channel=64, num_blocks=[2, 2, 2, 2], strides=[1, 2, 2, 2], num_classes=10, **kwargs):\n return ResNet(BasicBlock, num_blocks, strides, channel, num_classes)\n\n\ndef ResNet18():\n return ResNet(BasicBlock, [2, 2, 2, 2])\n\n\ndef ResNet34():\n return ResNet(BasicBlock, [3, 4, 6, 3])\n\n\ndef ResNet50():\n return ResNet(Bottleneck, [3, 4, 6, 3])\n\n\ndef ResNet101():\n return ResNet(Bottleneck, [3, 4, 23, 3])\n\n\ndef ResNet152():\n return ResNet(Bottleneck, [3, 8, 36, 3])\n\n\ndef test():\n net = ResNet10(16, [1, 1, 1, 1])\n y = net(torch.randn(1, 3, 32, 32))\n print(sum(p.numel() for p in net.parameters() if p.requires_grad))\n print(y.size())\n","sub_path":"models/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"463925463","text":"from ROOT import TFile, gROOT, gStyle, TH1F, TH2F, kBlue, kRed, TCanvas, TLatex, TLegend\nimport os, numpy, copy\nfrom officialStyle import officialStyle\n\n\ngROOT.SetBatch(True)\nofficialStyle(gStyle)\ngStyle.SetPadLeftMargin(0.18)\ngStyle.SetPadBottomMargin(0.15)\n\ndef returnRange(hist):\n \n bin = []\n \n for ibin in range(0, hist.GetNbinsX()+1):\n proj = hist.ProjectionY(\"ProjY_\"+str(ibin), ibin, ibin+1)\n if proj.GetEntries() > 100:\n bin.append(ibin)\n\n return min(bin), max(bin)\n\n\n\ndef LegendSettings(leg):\n leg.SetBorderSize(0)\n leg.SetFillColor(10)\n leg.SetLineColor(0)\n leg.SetFillStyle(0)\n leg.SetTextSize(0.035)\n leg.SetTextFont(42)\n\ncolours = [2, 3, 4, 6, 7, 8]\n\nprocess = 'DY'\n#process = 'VBF'\n\ndirectory = 'sample_20140513'\n\nsamples = []\nif process=='DY':\n samples = ['DY_Standard', 'DY_Timing', 'DY_3DandTiming']\nelif process=='VBF':\n samples = ['VBF_Standard125', 'VBF_Timing125', 'VBF_3DandTiming125']\n\n\nplots = ['tau_iso_neutralPt','tau_iso_neutralPtWeight1','tau_iso_neutralPtWeight2','tau_iso_neutralPtWeight1NQ','tau_iso_neutralPtWeight2NQ']\n\nplotleg = ['#Sigma_{neutral} p_{T} [GeV]', \n '#Sigma_{neutral, weight1} p_{T} [GeV]',\n '#Sigma_{neutral, weight1 NQ} p_{T} [GeV]',\n '#Sigma_{neutral, weight2} p_{T} [GeV]',\n '#Sigma_{neutral, weight2 NQ} p_{T} [GeV]',\n ]\n\nbarrel_endcap = ['all', 'barrel', 'endcap']\n\n\nhist2d_save = [[[i for i in range(len(samples))] for j in range(len(barrel_endcap))] for k in range(len(plots))]\nhist_save = [[[i for i in range(len(samples))] for j in range(len(barrel_endcap))] for k in range(len(plots))]\nf1_save = [[[i for i in range(len(samples))] for j in range(len(barrel_endcap))] for k in range(len(plots))]\n\n\nfor iplot, plot in enumerate(plots):\n for ibe, isbarrel in enumerate(barrel_endcap):\n\n hist = [i for i in range(len(samples))]\n hist2d = [i for i in range(len(samples))]\n f1 = [i for i in range(len(samples))]\n \n cname = 'can_' + plot + '_' + isbarrel\n can = TCanvas(cname, cname)\n\n for ii, sample in enumerate(samples):\n\n tfile = TFile('{dir}/{sample}/TauTreeProducer/TauTreeProducer_tree.root'.format(dir=directory, sample=sample))\n tree = tfile.Get('TauTreeProducer')\n \n hname = 'h_' + sample + '_' + isbarrel + '_' + plot\n hist[ii] = TH2F(hname, hname, 80,0,80, 60,0,60)\n# hist[ii].Sumw2()\n \n if isbarrel=='all':\n tree.Draw(plot + ':tau_iso_sumPUPt >> ' + hname, 'TMath::Abs(parton_pdgId)==15 && tau_decayModeFinding==1')\n elif isbarrel=='barrel':\n tree.Draw(plot + ':tau_iso_sumPUPt >> ' + hname, 'TMath::Abs(parton_pdgId)==15 && tau_decayModeFinding==1 && TMath::Abs(tau_eta) < 1.479')\n else:\n tree.Draw(plot + ':tau_iso_sumPUPt >> ' + hname, 'TMath::Abs(parton_pdgId)==15 && tau_decayModeFinding==1 && TMath::Abs(tau_eta) > 1.479')\n\n\n fitmin, fitmax = returnRange(hist[ii])\n hist2d[ii] = hist[ii].ProfileX()\n hist2d[ii].Fit(\"pol1\",\"\",\"\",fitmin, fitmax)\n f1[ii] = hist2d[ii].GetFunction(\"pol1\");\n \n hist2d[ii].GetXaxis().SetTitle('#Sigma_{PU} p_{T} [GeV]')\n hist2d[ii].GetYaxis().SetTitle(plotleg[iplot])\n hist2d[ii].SetMaximum(20)\n hist2d[ii].SetMinimum(0)\n hist2d[ii].SetMarkerSize(0.1)\n hist2d[ii].SetMarkerColor(colours[ii])\n hist2d[ii].SetLineColor(colours[ii])\n \n tname = process + ', ' + isbarrel\n hist2d[ii].SetTitle(tname)\n\n hist_save[iplot][ibe][ii] = copy.deepcopy(hist[ii])\n hist2d_save[iplot][ibe][ii] = copy.deepcopy(hist2d[ii])\n f1_save[iplot][ibe][ii] = copy.deepcopy(f1[ii])\n\n\n leg = TLegend(0.2,0.75,0.7,0.9)\n LegendSettings(leg)\n\n for ii, sample in enumerate(samples):\n if ii==0:\n hist2d_save[iplot][ibe][ii].Draw()\n else:\n hist2d_save[iplot][ibe][ii].Draw('same')\n \n f1_save[iplot][ibe][ii].SetLineColor(colours[ii])\n f1_save[iplot][ibe][ii].SetLineStyle(2)\n f1_save[iplot][ibe][ii].SetRange(hist2d_save[iplot][ibe][ii].GetXaxis().GetXmin(), hist2d_save[iplot][ibe][ii].GetXaxis().GetXmax())\n f1_save[iplot][ibe][ii].Draw('same')\n\n lname = sample.replace('_', ' ').replace('3DandTiming', '3D & Timing').replace('125','') + ', (' + str(\"{0:.3f}\".format(f1_save[iplot][ibe][ii].GetParameter(1))) + ', ' + str(\"{0:.1f}\".format(round(f1_save[iplot][ibe][ii].GetParameter(0),1))) + ')'\n leg.AddEntry(hist2d_save[iplot][ibe][ii], lname, 'l')\n\n leg.Draw()\n\n sname = 'plot/isolation_' + plot + '_' + isbarrel + '_' + process + '_neutral_vs_puiso.gif'\n can.SaveAs(sname)\n\n\nfile = TFile('root/Myroot_' + process + '.root','recreate')\n\nfor iplot, plot in enumerate(plots):\n for ibe, isbarrel in enumerate(barrel_endcap):\n for ii, sample in enumerate(samples):\n hist_save[iplot][ibe][ii].Write()\n hist2d_save[iplot][ibe][ii].Write()\n\n \nfile.Write()\nfile.Close()\n","sub_path":"AnalysisSpecific/TauIsolation/fitting.py","file_name":"fitting.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"615848333","text":"import pickle\nfrom indra.tools.model_checker import ModelChecker\n#from manual_stmts import stmts as manual_stmts\nfrom assemble_pysb import set_context, add_observables\nimport process_data\nfrom indra.util import write_unicode_csv\nfrom indra.assemblers import PysbAssembler\nimport make_stmts_for_checking as make_stmts\n\nprint(\"Processing data\")\n\ndata = process_data.read_data(process_data.data_file)\ndata_genes = process_data.get_all_gene_names(data)\n\n\nprint('Loading data statements.')\ndata_stmts, data_values = make_stmts.run(dec_thresh=0.5, inc_thresh=1.5)\n\nwith open('korkut_stmts_no_ev.pkl', 'rb') as f:\n print('Loading korkut_model_pysb statements.')\n base_stmts = pickle.load(f)\n\n# Merge the sources of statements\n# stmts = manual_stmts + base_stmts\nstmts = base_stmts\n#stmts = manual_stmts\n\n# Assemble model\npa = PysbAssembler()\npa.add_statements(stmts)\nmodel = pa.make_model()\n\n#with open('korkut_pysb.pkl', 'wb') as f:\n# pickle.dump(pa.model, f)\n\n# Preprocess and assemble the pysb model\n#model = assemble_pysb(combined_stmts, data_genes, '')\n\nmc = ModelChecker(model)\n\n# Iterate over each drug/ab statement subset\nresults = []\nfor drug_name, ab_dict in data_stmts.items():\n for ab, stmt_list in ab_dict.items():\n value = data_values[drug_name][ab]\n # For each subset, check statements; if any of them checks out, we're\n # good and can move on to the next group\n print(\"-- Checking the effect of %s on %s --\" % (drug_name, ab))\n relation = 'positive' if value > 1 else 'negative'\n path_found = 0\n path = ''\n for stmt in stmt_list:\n print(\"Checking: %s\" % stmt)\n result = mc.check_statement(stmt)\n if result:\n print(\"Path found, skipping rest\")\n path_found = 1\n path = str(result)\n break\n else:\n print(\"No path found\")\n\n results.append((drug_name, ab, relation, value, path_found, path))\nwrite_unicode_csv('model_check_results.csv', results)\n","sub_path":"models/phase3_eval/check_pysb_model.py","file_name":"check_pysb_model.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"511838588","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nFixtures for host_network_api\n\"\"\"\n\nimport pytest\n\nimport config as network_api_conf\nimport helper\nfrom art.rhevm_api.tests_lib.high_level import (\n hosts as hl_hosts,\n networks as hl_networks\n)\nfrom art.rhevm_api.tests_lib.low_level import (\n events as ll_events,\n hosts as ll_hosts\n)\nfrom art.unittest_lib import testflow\nimport rhevmtests.networking.config as conf\n\n\n@pytest.fixture(scope=\"class\")\ndef remove_network(request):\n \"\"\"\n Remove network.\n \"\"\"\n nets_to_remove = request.node.cls.nets_to_remove\n assert hl_networks.remove_networks(\n positive=True, networks=nets_to_remove, data_center=conf.DC_0\n )\n\n\n@pytest.fixture(scope=\"class\")\ndef update_host_to_another_cluster(request):\n \"\"\"\n Update host to another cluster.\n \"\"\"\n def fin():\n \"\"\"\n Move host to original cluster.\n \"\"\"\n assert ll_hosts.update_host(\n positive=True, host=conf.HOST_0_NAME, cluster=conf.CL_0\n )\n request.addfinalizer(fin)\n\n assert ll_hosts.update_host(\n positive=True, host=conf.HOST_0_NAME, cluster=network_api_conf.SYNC_CL\n )\n\n\n@pytest.fixture(scope=\"class\")\ndef manage_ip_and_refresh_capabilities(request):\n \"\"\"\n Set temporary IP on interface and refresh capabilities.\n \"\"\"\n host = conf.HOST_0_NAME\n for net, actual_ip, actual_netmask in (\n request.node.cls.manage_ip_list\n ):\n actual_netmask = actual_netmask or \"24\"\n testflow.setup(\n \"Set temporary IP on %s with: IP=%s, Netmask=%s\",\n net, actual_ip, actual_netmask\n )\n helper.manage_host_ip(\n interface=net, ip=actual_ip, netmask=actual_netmask\n )\n last_event = ll_events.get_max_event_id()\n assert ll_hosts.refresh_host_capabilities(\n host=host, start_event_id=last_event\n )\n\n\n@pytest.fixture(scope=\"class\")\ndef reboot_host(request):\n \"\"\"\n Reboot host\n \"\"\"\n host = conf.HOSTS[2]\n vds = conf.VDS_HOSTS[2]\n testflow.setup(\"Reboot host %s\", host)\n assert hl_hosts.deactivate_host_if_up(host=host, host_resource=vds)\n vds.add_power_manager(pm_type=conf.SSH_TYPE)\n vds.get_power_manager().restart()\n for is_connective in (False, True):\n vds.executor().wait_for_connectivity_state(\n positive=is_connective\n )\n\n assert hl_hosts.activate_host_if_not_up(host=host, host_resource=vds)\n","sub_path":"art/tests/rhevmtests/networking/host_network_api/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"270560325","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/8/29 09:05\n# @Author : Maloney\n# @Site : jma@192.168.126.124\n# @File : mnist_loader.py\n# @Software: PyCharm\n\n#### Libraries\n\n# Standard library\n\nimport pickle\n\nimport gzip\n\n# Third-party libraries\n\nimport numpy as np\n\n\ndef load_data():\n f = gzip.open('neural-networks-and-deep-learning/data/mnist.pkl.gz', 'rb')\n training_data, validation_data, test_data = pickle.load(f)\n f.close()\n return (training_data, validation_data, test_data)\n\n\ndef load_data_wrapper():\n tr_d, va_d, te_d = load_data()\n\n training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]\n\n training_results = [vectorized_result(y) for y in tr_d[1]]\n\n training_data = zip(training_inputs, training_results)\n\n validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]\n\n validation_data = zip(validation_inputs, va_d[1])\n\n test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]\n\n test_data = zip(test_inputs, te_d[1])\n\n return (training_data, validation_data, test_data)\n\n\ndef vectorized_result(j):\n e = np.zeros((10, 1))\n\n e[j] = 1.0\n\n return e\n","sub_path":"NetWork/mnist_loader.py","file_name":"mnist_loader.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"259564721","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 3 18:30:01 2019\n\n@author: lenovo\n\"\"\"\n#def palindrome_number(list_a):\n # c=0\nn=input(\"Enter the number\").split(\" \")\n#these are the t\nfor i in n:\n if i == i[::-1]:\n print(i)\nt=n\nrev=0\n#this is define the rewverse\nrem = i % 10\n#it used as the remainder\nrev=rev*10+rem\n#it is find the reverse number\ni=i/10\n#if rev==n\nif rev == i:\n print(\"number is palindrome\")\nelse:\n print(\"number is not palindrome\")","sub_path":"day02/palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"478169671","text":"import os\nimport time\nimport neat\nfrom gym_multi_robot import visualize\nfrom gym_multi_robot.object_serializer import ObjectSerializer\n\n\nclass SingleExperiment:\n \"\"\" This class gives the functions required to run a single experiment.\"\"\"\n\n def __init__(self, learning_config, exp_runner, num_generations, exp_name='', num_trails=1, base_directory=''):\n self.exp_name = exp_name\n self.learning_config = learning_config\n self.exp_runner = exp_runner\n self.num_generations = num_generations\n self.num_trails = num_trails\n self.winner = None # Stores the winner of the last experiment.\n self.stats = None # Stores the stats about the last experiment.\n self.base_directory = base_directory\n\n def eval_genomes(self, genomes, config):\n start_time = time.time()\n\n for genome_id, genome in genomes:\n\n self.process_genome(genome, config)\n # sub rewards.\n\n end_time = time.time()\n time_diff = end_time - start_time\n avg_time = time_diff / len(genomes)\n\n print(\"generation total_runtime: %s seconds, avg_runtime: %s seconds\" % (time_diff, avg_time))\n\n def process_genome(self, genome, config):\n \"\"\" This function processes a genome to finds its fitness and possibly other details. \"\"\"\n genome.fitness = self.exp_runner.run_multiple_trails(genome, config, self.num_trails)\n\n def run(self, name=None):\n \"\"\" Runs the experiment.\n Name parameter can be used to update the name of the experiment.\n \"\"\"\n if name is not None:\n self.exp_name = name\n\n # Create the population, which is the top-level object for a NEAT run.\n p = neat.Population(self.learning_config)\n\n # Add a stdout reporter to show progress in the terminal.\n p.add_reporter(neat.StdOutReporter(True))\n self.stats = neat.StatisticsReporter()\n p.add_reporter(self.stats)\n\n # Run experiments\n try:\n self.winner = p.run(self.eval_genomes, self.num_generations)\n except Exception:\n raise\n finally:\n self.winner = p.best_genome\n\n self.output_stats()\n self.output_winner()\n\n\n def output_winner(self):\n \"\"\"This function outputs the current winner in graph and in pickle file.\"\"\"\n self.init_base_directory()\n\n net_filename = self.base_directory + 'graph_winner' + str(self.exp_name)\n genome_filename = self.base_directory + 'winner' + str(self.exp_name)\n\n if self.exp_runner is not None:\n self.exp_runner.draw(self.winner, self.learning_config, net_filename)\n\n ObjectSerializer.serialize(self.winner, genome_filename)\n\n print(self.winner)\n\n def output_stats(self):\n \"\"\" This function outputs the statistics in figures and in reusable objects.\"\"\"\n self.init_base_directory()\n\n fitness_out_file = self.base_directory + 'avg_fitness_' + str(self.exp_name) + '.svg'\n species_out_file = self.base_directory + 'species_' + str(self.exp_name) + '.svg'\n stats_out_file = self.base_directory + 'stats' + str(self.exp_name)\n\n visualize.visualize_stats(self.stats, fitness_out_file, species_out_file)\n ObjectSerializer.serialize(self.stats, stats_out_file)\n\n def init_base_directory(self):\n \"\"\" This function checks whether the base directory exists and creates it if it doesn't. \"\"\"\n\n if self.base_directory != '' and not os.path.exists(self.base_directory):\n os.makedirs(self.base_directory)\n","sub_path":"examples/experiment_template.py","file_name":"experiment_template.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"650884717","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2010 United States Government as represented by the\n# Administrator of the National Aeronautics and Space Administration.\n# Copyright 2011 Red Hat, Inc.\n# Copyright (c) 2012 Samsung SDS Co., LTD\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom synaps import flags\nfrom synaps.utils import strtime\nfrom synaps import log as logging\nfrom synaps.exception import RpcInvokeException\nimport uuid\n\nimport pika, json\n\nLOG = logging.getLogger(__name__)\nFLAGS = flags.FLAGS\n\nPUT_METRIC_DATA_MSG_ID = 0x0001\nPUT_METRIC_ALARM_MSG_ID = 0x0002\nDISABLE_ALARM_ACTIONS = 0x0003\nENABLE_ALARM_ACTIONS = 0x0004\nDELETE_ALARMS_MSG_ID = 0x0005\nSET_ALARM_STATE_MSG_ID = 0x0006\nCHECK_METRIC_ALARM_MSG_ID = 0x0010 \n\n\nclass RemoteProcedureCall(object):\n def __init__(self):\n self.connect()\n \n def connect(self):\n host = FLAGS.get('rabbit_host')\n port = FLAGS.get('rabbit_port')\n try:\n LOG.info(_(\"connecting to rabbit_host %s %d\") % (host, port))\n\n self.conn = pika.BlockingConnection(\n pika.ConnectionParameters(\n host=FLAGS.get('rabbit_host'),\n port=FLAGS.get('rabbit_port'),\n credentials=pika.PlainCredentials(\n FLAGS.get('rabbit_userid'),\n FLAGS.get('rabbit_password')\n ),\n virtual_host=FLAGS.get('rabbit_virtual_host'),\n )\n )\n \n self.channel = self.conn.channel()\n queue_args = {\"x-ha-policy\" : \"all\" }\n self.channel.queue_declare(queue='metric_queue', durable=True,\n arguments=queue_args)\n except Exception as e:\n raise RpcInvokeException()\n \n def send_msg(self, message_id, body):\n \"\"\"\n \n \n Args:\n message_id: int\n ex) PUT_METRIC_DATA_MSG_ID (0x0001)\n PUT_METRIC_ALARM_MSG_ID (0x0002)\n ...\n body: dict object (will be converted into json format)\n \n \"\"\"\n if type(message_id) is not int:\n raise RpcInvokeException()\n \n if not self.conn.is_open:\n self.connect()\n\n message_uuid = str(uuid.uuid4()) \n body.setdefault('message_id', message_id)\n body.setdefault('message_uuid', message_uuid)\n \n self.channel.basic_publish(\n exchange='', routing_key='metric_queue', body=json.dumps(body),\n properties=pika.BasicProperties(delivery_mode=2)\n )\n \n LOG.info(_(\"send_msg - id(%03d), %s\") % (message_id, message_uuid))\n LOG.debug(_(\"send_msg - body(%s)\") % str(body))\n","sub_path":"synaps-api/synaps/rpc/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"118433031","text":"import time\n\nfrom flask import Flask\nfrom flask_admin import Admin\nfrom flask_admin.contrib.sqla import ModelView\nfrom flask_babelex import Babel\n\nimport config\nfrom model import db\nfrom model.blog import Blog\nfrom model.reply import Reply\nfrom model.user import User\nfrom route import csrf\nfrom route.routes_index import main as index_routes\nfrom route.routes_detail import main as detail_routes\n\n\ndef formatted_time(input):\n \"\"\"\n Jinja2 filter\n :param input: timestamp\n :return: formatted time\n \"\"\"\n\n time_format = r'%Y/%m/%d'\n localtime = time.localtime(int(input))\n formatted = time.strftime(time_format, localtime)\n return formatted\n\n\ndef time_count(input):\n \"\"\"\n Jinja2 filter\n :param input: timestamp\n :return: generated current time minus input and formatted\n \"\"\"\n num = int(time.time())-input\n if num < 60:\n return '{} 秒'.format(num)\n elif 60 < num < 3600:\n return '{} 分钟'.format(num//60)\n elif 3600 < num < 86400:\n return '{} 小时'.format(num//3600)\n else:\n return '{} 天'.format(num//86400)\n\n\ndef current_app():\n \"\"\"\n Flask main enter\n :return: Flask app\n \"\"\"\n app = Flask(__name__)\n\n app.secret_key = config.secret_key\n\n app.config['WTF_CSRF_SECRET_KEY'] = config.csrf_key\n app.config['SQLALCHEMY_DATABASE_URI'] = config.db_url\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n app.add_template_filter(formatted_time)\n app.add_template_filter(time_count)\n\n db.init_app(app)\n csrf.init_app(app)\n\n register_routes(app)\n return app\n\n\ndef register_routes(app):\n \"\"\"\n Register routes and add prefix\n :param app: Flask app\n :return: Flask app\n \"\"\"\n app.register_blueprint(index_routes)\n app.register_blueprint(detail_routes, url_prefix='/blog')\n\n\nif __name__ == '__main__':\n app = current_app()\n\n app.config['TEMPLATE_AUTO_RELOAD'] = True\n app.jinja_env.auto_reload = True\n\n app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n\n # 本地化,admin后台中文\n babel = Babel(app)\n app.config['BABEL_DEFAULT_LOCALE'] = 'zh_CN'\n\n admin = Admin(app, name=u'管理后台', template_mode='bootstrap3')\n admin.add_view(ModelView(User, db.session))\n admin.add_view(ModelView(Blog, db.session))\n admin.add_view(ModelView(Reply, db.session))\n\n config = dict(\n host='localhost',\n port=3000,\n debug=True\n )\n\n app.run(**config)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"60437745","text":"\ndef solve(string,n,z):\n if len(string) == 1 and string[0] == \"+\" :\n print(\"Case #\", z+1, \": \",n , sep = '');\n return n;\n if string[len(string)-1] == \"+\" :\n solve(string[0:len(string)-1],n,z);\n else :\n tempString = [];\n for j in string:\n tempString.append(j);\n for i in range(len(tempString)) :\n if tempString[i] == \"+\" :\n tempString[i] = \"-\";\n else :\n tempString[i] = \"+\";\n string = ''.join(tempString);\n \n solve(string,n+1,z);\n\t\t\ncases = int(input());\n\nfor i in range(cases) :\n string = input();\n if len(string) == 1 :\n \tif string[0] == \"-\" :\n \t\tprint(\"Case #\", i+1, \": 1\", sep = '');\n \telse :\n \t\tprint(\"Case #\", i+1, \": 0\", sep = '')\n \tcontinue;\n #Check if all values are same\n if string == \"-\" * len(string) :\n \tprint(\"Case #\", i+1, \": 1\", sep = '');\n \tcontinue;\n elif string == \"+\" * len(string) :\n \tprint(\"Case #\", i+1, \": 0\", sep = '');\n \tcontinue;\n #Check if all values except last are same\n if string[len(string)-1] == \"-\" and string[0:len(string)-2] == \"+\" * (len(string)-2) :\n \tprint(\"Case #\", i+1, \": 2\", sep = '');\n \tcontinue;\n elif string[len(string)-1] == \"+\" and string[0:len(string)-2] == \"-\" * (len(string)-2) :\n \tprint(\"Case #\", i+1, \": 1\", sep = '');\n \tcontinue;\n solve(string,0,i);\n","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_Marmik_Revenge Of PanCakes.py","file_name":"16_0_2_Marmik_Revenge Of PanCakes.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"425817546","text":"# Import necessary libraries\nimport pandas as pd\nfrom sklearn import model_selection\nfrom model import TitanicModel\nfrom tensorflow import keras\nfrom keras.utils import to_categorical\n\ndef load_and_prep_data(data_path, isTrainingSet):\n\n # Load dataset\n X_train_orig = pd.read_csv(data_path)\n\n # View dataset\n print(X_train_orig.head())\n\n # Separate the Y i.e output from the training dataset only.\n Y_train_orig = None\n if isTrainingSet:\n Y_train_orig = X_train_orig['Survived']\n #print(Y_train_orig.head())\n # Drop unnecessary columns\n dropCols = ['PassengerId', 'Survived', 'Name', 'Ticket', 'Cabin']\n else:\n dropCols = ['PassengerId', 'Name', 'Ticket', 'Cabin']\n X_train = X_train_orig.drop(dropCols, axis=1)\n #print(X_train.head())\n #print(X_train.info())\n\n # Separate numerical and categorical features\n num_feat = X_train.select_dtypes('number').columns.values\n cat_feat = X_train.select_dtypes('object').columns.values\n X_num = X_train[num_feat]\n\n # Take age and category in range 1-3\n X_num.loc[ X_num['Fare'] <= 7.91, 'Fare'] = 0\n X_num.loc[(X_num['Fare'] > 7.91) & (X_num['Fare'] <= 14.454), 'Fare'] = 1\n X_num.loc[(X_num['Fare'] > 14.454) & (X_num['Fare'] <= 31), 'Fare'] = 2\n X_num.loc[ X_num['Fare'] > 31, 'Fare'] = 3\n #X_num['Fare'] = X_num['Fare'].astype(int)\n\n X_num.loc[ X_num['Age'] <= 16, 'Age'] = 0\n X_num.loc[(X_num['Age'] > 16) & (X_num['Age'] <= 32), 'Age'] = 1\n X_num.loc[(X_num['Age'] > 32) & (X_num['Age'] <= 48), 'Age'] = 2\n X_num.loc[(X_num['Age'] > 48) & (X_num['Age'] <= 64), 'Age'] = 3\n X_num.loc[ X_num['Age'] > 64, 'Age'] = 4\n #X_num['Age'] = X_num['Age'].astype(int)\n X_cat = X_train[cat_feat]\n\n # Data Augmentation\n \n\n # Normalize numeric features\n X_num_normalized = (X_num - X_num.mean()) / X_num.std()\n X_num_normalized = X_num_normalized.fillna(X_num_normalized.mean())\n\n #print(X_num_normalized.head())\n\n # Convert categorical features to one hot\n X_cat = pd.get_dummies(X_cat)\n #print(X_cat.head())\n\n # Concatenate X_num and X_concat\n X = pd.concat([X_num, X_cat], axis=1)\n print(X.head())\n\n Y = list()\n # Do the same for outputs Y\n if Y_train_orig is not None:\n Y = Y_train_orig.fillna(0)\n #print(Y.describe())\n\n return X,Y\n\ndef split_training_data(X, Y):\n X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, random_state=0)\n return X_train, X_test, Y_train, Y_test\n\ndef main():\n relPath = 'C:/Users/himan/Documents/GitHub/Deep-Learning-Projects/Titanic - Machine Learning from Disaster/dataset'\n trainDataPath = relPath + '/train.csv'\n testDataPath = relPath + '/test.csv'\n \n print('Preparing Training Data')\n X, Y = load_and_prep_data(trainDataPath, True)\n print('Preparing unseen Test Data')\n X_unseen_test, _ = load_and_prep_data(testDataPath, False)\n\n #Split the train data into train and test data for your cross validation\n X_train, X_test, Y_train, Y_test = split_training_data(X,Y)\n\n model = TitanicModel()\n # Convert Y to one hot labels\n Y_train = to_categorical(Y_train)\n Y_test = to_categorical(Y_test)\n\n # Convert dataframe to numpy array\n X_train = X_train.values\n X_test = X_test.values\n \n print('Shape of training data ' + str(X_train.shape))\n print('Shape of training labels ' + str(Y_train.shape))\n \n # Reshape Y_train and Y_test to (N,1)\n #Y_train = Y_train.values.reshape(len(Y_train), 1)\n #Y_test = Y_test.values.reshape((len(Y_test), 1))\n\n print('Shape of test data ' + str(X_test.shape))\n print('Shape of test labels' + str(Y_test.shape))\n\n # Convert unseen test examples into np array\n X_unseen_test = X_unseen_test.values\n \n # Train the model\n trained_model = model.train_with_keras_model(X_train, Y_train, X_test, Y_test, 100, 512)\n #trained_model = model.train_params(X_train.T, Y_train, X_test.T, Y_test, 0.003, 300, 512, True)\n \n # Evaluation on test data\n #pred = trained_model.predict(X_unseen_test)\n #print(pred)\n\nif __name__ == \"__main__\":\n main()","sub_path":"Titanic - Machine Learning from Disaster/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"37285184","text":"import pandas as pd\nimport math\nimport numpy \n\nfile_to_read = input(\"type the file you want to read here: \")\n\nread = pd.read_csv(file_to_read)\nangle_calced = numpy.arctan2(read[\"Tangent Y\"], read[\"Tangent X\"])\n\ncombined_output = []\nfor index in range(len(read[\"X\"])):\n x_gen = ((read[\"X\"][index]) - (read[\"X\"][0]))\n y_gen = ((read[\"Y\"][index]) - (read[\"Y\"][0]))\n angle_gen = numpy.rad2deg(angle_calced[index])\n\n x_val = numpy.round(x_gen, 3)\n y_val = numpy.round(y_gen, 3)\n angle = numpy.round(angle_gen, 3)\n\n combined_output.append((x_val, y_val, angle))\n\n print(\"new Pose2d(\" + str(x_val) + \"d, \" + str(y_val) + \"d, \" + \"Rotation2d.fromDegrees(\" + str(angle) + \"d\" \")),\")\n\nnumpy.set_printoptions(suppress=True, precision=3)\n# print(\"points relative to 0: \")\n# print(numpy.array(combined_output))\n","sub_path":"scripts/pointgen.py","file_name":"pointgen.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"645055902","text":"# Copyright 2012-2017 The Meson development team\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os.path\n\nfrom .. import mlog\nfrom .. import coredata\nfrom ..mesonlib import version_compare\n\nfrom .c import CCompiler, VisualStudioCCompiler\nfrom .compilers import (\n GCC_MINGW,\n gnu_winlibs,\n msvc_winlibs,\n ClangCompiler,\n GnuCompiler,\n IntelCompiler,\n)\n\nclass CPPCompiler(CCompiler):\n def __init__(self, exelist, version, is_cross, exe_wrap, **kwargs):\n # If a child ObjCPP class has already set it, don't set it ourselves\n if not hasattr(self, 'language'):\n self.language = 'cpp'\n CCompiler.__init__(self, exelist, version, is_cross, exe_wrap, **kwargs)\n\n def get_display_language(self):\n return 'C++'\n\n def get_no_stdinc_args(self):\n return ['-nostdinc++']\n\n def sanity_check(self, work_dir, environment):\n code = 'class breakCCompiler;int main(int argc, char **argv) { return 0; }\\n'\n return self.sanity_check_impl(work_dir, environment, 'sanitycheckcpp.cc', code)\n\n def get_compiler_check_args(self):\n # -fpermissive allows non-conforming code to compile which is necessary\n # for many C++ checks. Particularly, the has_header_symbol check is\n # too strict without this and always fails.\n return super().get_compiler_check_args() + ['-fpermissive']\n\n def has_header_symbol(self, hname, symbol, prefix, env, extra_args=None, dependencies=None):\n # Check if it's a C-like symbol\n if super().has_header_symbol(hname, symbol, prefix, env, extra_args, dependencies):\n return True\n # Check if it's a class or a template\n if extra_args is None:\n extra_args = []\n fargs = {'prefix': prefix, 'header': hname, 'symbol': symbol}\n t = '''{prefix}\n #include <{header}>\n using {symbol};\n int main () {{ return 0; }}'''\n return self.compiles(t.format(**fargs), env, extra_args, dependencies)\n\n\nclass ClangCPPCompiler(ClangCompiler, CPPCompiler):\n def __init__(self, exelist, version, cltype, is_cross, exe_wrapper=None, **kwargs):\n CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrapper, **kwargs)\n ClangCompiler.__init__(self, cltype)\n default_warn_args = ['-Wall', '-Winvalid-pch', '-Wnon-virtual-dtor']\n self.warn_args = {'1': default_warn_args,\n '2': default_warn_args + ['-Wextra'],\n '3': default_warn_args + ['-Wextra', '-Wpedantic']}\n\n def get_options(self):\n return {'cpp_std': coredata.UserComboOption('cpp_std', 'C++ language standard to use',\n ['none', 'c++98', 'c++03', 'c++11', 'c++14', 'c++17', 'c++1z',\n 'gnu++11', 'gnu++14', 'gnu++17', 'gnu++1z'],\n 'none')}\n\n def get_option_compile_args(self, options):\n args = []\n std = options['cpp_std']\n if std.value != 'none':\n args.append('-std=' + std.value)\n return args\n\n def get_option_link_args(self, options):\n return []\n\n\nclass GnuCPPCompiler(GnuCompiler, CPPCompiler):\n def __init__(self, exelist, version, gcc_type, is_cross, exe_wrap, defines, **kwargs):\n CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrap, **kwargs)\n GnuCompiler.__init__(self, gcc_type, defines)\n default_warn_args = ['-Wall', '-Winvalid-pch', '-Wnon-virtual-dtor']\n self.warn_args = {'1': default_warn_args,\n '2': default_warn_args + ['-Wextra'],\n '3': default_warn_args + ['-Wextra', '-Wpedantic']}\n\n def get_options(self):\n opts = {'cpp_std': coredata.UserComboOption('cpp_std', 'C++ language standard to use',\n ['none', 'c++98', 'c++03', 'c++11', 'c++14', 'c++17', 'c++1z',\n 'gnu++03', 'gnu++11', 'gnu++14', 'gnu++17', 'gnu++1z'],\n 'none'),\n 'cpp_debugstl': coredata.UserBooleanOption('cpp_debugstl',\n 'STL debug mode',\n False)}\n if self.gcc_type == GCC_MINGW:\n opts.update({\n 'cpp_winlibs': coredata.UserArrayOption('cpp_winlibs', 'Standard Win libraries to link against',\n gnu_winlibs), })\n return opts\n\n def get_option_compile_args(self, options):\n args = []\n std = options['cpp_std']\n if std.value != 'none':\n args.append('-std=' + std.value)\n if options['cpp_debugstl'].value:\n args.append('-D_GLIBCXX_DEBUG=1')\n return args\n\n def get_option_link_args(self, options):\n if self.gcc_type == GCC_MINGW:\n return options['cpp_winlibs'].value[:]\n return []\n\n def get_pch_use_args(self, pch_dir, header):\n return ['-fpch-preprocess', '-include', os.path.basename(header)]\n\n\nclass IntelCPPCompiler(IntelCompiler, CPPCompiler):\n def __init__(self, exelist, version, icc_type, is_cross, exe_wrap, **kwargs):\n CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrap, **kwargs)\n IntelCompiler.__init__(self, icc_type)\n self.lang_header = 'c++-header'\n default_warn_args = ['-Wall', '-w3', '-diag-disable:remark',\n '-Wpch-messages', '-Wnon-virtual-dtor']\n self.warn_args = {'1': default_warn_args,\n '2': default_warn_args + ['-Wextra'],\n '3': default_warn_args + ['-Wextra', '-Wpedantic']}\n\n def get_options(self):\n c_stds = []\n g_stds = ['gnu++98']\n if version_compare(self.version, '>=15.0.0'):\n c_stds += ['c++11', 'c++14']\n g_stds += ['gnu++11']\n if version_compare(self.version, '>=16.0.0'):\n c_stds += ['c++17']\n if version_compare(self.version, '>=17.0.0'):\n g_stds += ['gnu++14']\n opts = {'cpp_std': coredata.UserComboOption('cpp_std', 'C++ language standard to use',\n ['none'] + c_stds + g_stds,\n 'none'),\n 'cpp_debugstl': coredata.UserBooleanOption('cpp_debugstl',\n 'STL debug mode',\n False)}\n return opts\n\n def get_option_compile_args(self, options):\n args = []\n std = options['cpp_std']\n if std.value != 'none':\n args.append('-std=' + std.value)\n if options['cpp_debugstl'].value:\n args.append('-D_GLIBCXX_DEBUG=1')\n return args\n\n def get_option_link_args(self, options):\n return []\n\n def has_multi_arguments(self, args, env):\n for arg in args:\n if arg.startswith('-Wl,'):\n mlog.warning('''{} looks like a linker argument, but has_argument\nand other similar methods only support checking compiler arguments.\nUsing them to check linker arguments are never supported, and results\nare likely to be wrong regardless of the compiler you are using.\n'''.format(arg))\n return super().has_multi_arguments(args + ['-diag-error', '10006'], env)\n\n\nclass VisualStudioCPPCompiler(VisualStudioCCompiler, CPPCompiler):\n def __init__(self, exelist, version, is_cross, exe_wrap, is_64):\n self.language = 'cpp'\n VisualStudioCCompiler.__init__(self, exelist, version, is_cross, exe_wrap, is_64)\n self.base_options = ['b_pch'] # FIXME add lto, pgo and the like\n\n def get_options(self):\n return {'cpp_eh': coredata.UserComboOption('cpp_eh',\n 'C++ exception handling type.',\n ['none', 'a', 's', 'sc'],\n 'sc'),\n 'cpp_winlibs': coredata.UserArrayOption('cpp_winlibs',\n 'Windows libs to link against.',\n msvc_winlibs)\n }\n\n def get_option_compile_args(self, options):\n args = []\n std = options['cpp_eh']\n if std.value != 'none':\n args.append('/EH' + std.value)\n return args\n\n def get_option_link_args(self, options):\n return options['cpp_winlibs'].value[:]\n\n def get_compiler_check_args(self):\n # Visual Studio C++ compiler doesn't support -fpermissive,\n # so just use the plain C args.\n return super(VisualStudioCCompiler, self).get_compiler_check_args()\n","sub_path":"mesonbuild/compilers/cpp.py","file_name":"cpp.py","file_ext":"py","file_size_in_byte":9436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"71759912","text":"from PIL import Image\nimport os.path, os\n\nimage_ctype= {'png': \"image/png\",\n 'jpg': \"image/jpeg\",\n 'jpeg': \"image/jpeg\"}\n\ndef save_image(dir, sha1, ext, data):\n fname = \"{0}.{1}\".format(sha1, ext)\n fout = open(os.path.join(dir, fname), 'wb')\n fout.write(data)\n fout.close()\n return fname\n\ndef move_image(fr, to):\n os.rename(fr, to)\n\ndef save_thumbnail(in_path, dir, sha1, prefix, max_width=1024, max_height=1024):\n size = (max_width, max_height)\n im = Image.open(in_path)\n im.thumbnail(size, Image.ANTIALIAS)\n fname = \"{0}_{1}.jpg\".format(prefix, sha1)\n im.save(os.path.join(dir, fname), \"JPEG\", quality=95)\n return fname\n\ndef get_image_size(path):\n im = Image.open(path)\n size = im.size\n return size","sub_path":"KPDB/src/imageutil.py","file_name":"imageutil.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"334449693","text":"\"\"\"\nABCD_ML.py\n====================================\nThe main project class.\n\"\"\"\nimport pandas as pd\nimport shutil\nimport os\nimport pickle as pkl\n\nfrom ..helpers.Docstring_Helpers import get_new_docstring\n# from ..helpers.Params_Classes import ML_Params\nfrom ..helpers.CV import CV\n\n\ndef Load(loc, exp_name='default', log_dr='default', existing_log='default',\n verbose='default', notebook='default', random_state='default'):\n '''\n This function is designed to load in a saved previously created\n ABCD_ML object.\n\n See :func:`Save ` for saving an object.\n See :func:`Init ` for the\n rest of changable param descriptions, e.g., log_dr, existing_log, ect...\n\n Parameters\n ----------\n loc : str or Path\n\n A path/str to a saved ABCD_ML object,\n (One saved with :func:`Save `), then that object will be\n loaded. Notably, if any additional params are passed along\n with it, e.g., exp_name, notebook, ect... they will override\n the saved values with the newly passed values.\n If left as 'default', all params will be set to the loaded value,\n though see the warning below.\n\n .. WARNING::\n The exp_name or log_dr may need to be changed, especially\n in the case where the object is being loaded in a new\n location or enviroment from where the original was created,\n as it will by default try to create logs with the saved path\n information as the original.\n\n You can only change exp_name, log_dr, existing_log, verbose,\n notebook and random_state when loading a new object, for the\n remaining params, even if a value is passed, it will not be\n applied. If the user really wishes to change one of these params,\n they can change it manually via self.name_of_param = whatever.\n '''\n\n with open(loc, 'rb') as f:\n ML = pkl.load(f)\n\n if exp_name != 'default':\n ML.exp_name = exp_name\n if log_dr != 'default':\n ML.log_dr = log_dr\n if existing_log != 'default':\n ML.existing_log = existing_log\n if verbose != 'default':\n ML.verbose = verbose\n\n ML._init_logs()\n\n if notebook != 'default':\n ML.notebook = notebook\n if random_state != 'default':\n ML.random_state = random_state\n\n ML._print('ABCD_ML object loaded from save!')\n return ML\n\n\nclass ABCD_ML():\n\n def __init__(self, exp_name='My_ML_Exp', log_dr='', existing_log='append',\n verbose=True, notebook=True,\n use_abcd_subject_ids=False,\n low_memory_mode=False, strat_u_name='_Strat',\n random_state=534, n_jobs=1, dpi=100, mp_context='spawn'):\n '''Main class used within ABCD_ML for interfacing with Data Loading\n and Modeling / Other funcationality.\n\n Parameters\n ----------\n exp_name : str, optional\n The name of this experimental run,\n used explicitly in saving logs, and figures, where the passed\n `exp_name` is used as the name of the log folder.\n If log_dr is not set to None,\n (if not None then saves logs and figures)\n then a folder is created within the log dr\n with the exp_name.\n\n ::\n\n default = 'My_ML_Exp'\n\n log_dr : str, Path or None, optional\n The directory in which to store logs...\n If set to None, then will not save any logs!\n If set to empty str, will save in the current dr.\n\n ::\n\n default = ''\n\n existing_log : {'new', 'append', 'overwrite'}, optional\n This parameter dictates different choices for when\n an a folder with exp_name already exists in the specified\n log_dr.\n\n These choices are:\n\n - 'new'\n If the log folder already exists, then\n just increment `exp_name` until a free name is found,\n and use that as the log folder / `exp_name`.\n\n - 'append'\n If existing_log is 'append' then log entries\n and new figures will be added to the existing folder.\n\n - 'overwrite'\n If existing_log is 'overwrite', then the existing\n log folder with the same exp_name will be cleared\n upon __init__.\n\n ::\n\n default = 'append'\n\n verbose: bool, optional\n If `verbose` is set to True, the ABCD_ML object\n will print output, diagnostic and more general, directly\n to std out. If set to False, no output will be printed, though\n output will still be recorded within the logs assuming log_dr is not None.\n\n ::\n\n default = True\n\n notebook : bool, optional\n If True, then assumes the user is running\n the code in an interactive jupyter notebook. \n In this case, certain features will either be enabled or disabled,\n e.g., type of progress bar.\n\n ::\n\n default = Trues\n\n use_abcd_subject_ids : bool, optional\n Flag to determine the usage of ABCD speficic 'default'\n subject id behavior.\n If set to True, this will convert input NDAR subject ids\n into upper case, with prepended NDAR - type format.\n If set to False, then all input subject names must be entered\n explicitly the same, no preprocessing will be done on them.\n\n ::\n\n default = False\n\n low_memory_mode : bool, optional\n This parameter dictates behavior around loading in data,\n specifically,\n If set to True, individual dataframes self.data, self.covars ect...\n will be deleted from memory as soon as modeling begins.\n This parameter also controls the pandas read_csv behavior,\n which also has a low_memory flag.\n\n ::\n\n default = False\n\n strat_u_name : str, optional\n A unique str identifier to be appended to every loaded\n strat value (to keep them seperate from covars and data).\n\n You should only need to change or ever worry about this in\n the case that one of your input variables happens to have the\n default value of '_Strat' in it...\n\n ::\n\n default = '_Strat'\n\n random_state : int, RandomState instance or None, optional\n The default random state, either as int for a specific seed,\n or if None then the random seed is set by np.random.\n This parameters if set will be the default random_state class-wide,\n so any place random_state is left to default, unless a different\n default is set (e.g. default load value or default ML value) this\n random state will be used.\n\n ::\n\n default = 534\n\n n_jobs : int, optional\n The default number of jobs / processors to use (if avaliable) where\n ever avaliable class-wide across ABCD_ML.\n\n ::\n\n default = 1\n\n dpi : int, optional\n The default dpi in which to save any automatically saved fiugres\n with.\n Where this parameter can also be set to specific values\n for specific plots.\n\n ::\n\n default = 1\n\n mp_context : {None, 'fork', 'spawn'}, optional\n When a hyper-parameter search is launched, there are different\n ways through python that the multi-processing can be launched\n (assuming n_jobs > 1). Occassionally some choices can lead to\n odd errors.\n\n ::\n\n default = 'spawn'\n '''\n # Load logging class params\n self.exp_name = exp_name\n self.log_dr = log_dr\n self.existing_log = existing_log\n self.verbose = verbose\n\n self._init_logs()\n\n self._print('exp_name =', self.exp_name)\n self._print('log_dr =', self.log_dr)\n self._print('existing_log =', self.existing_log)\n self._print('verbose =', self.verbose)\n self._print('exp log dr setup at:', self.exp_log_dr)\n self._print('log file at:', self.log_file)\n\n # Set rest of class params\n self.notebook = notebook\n self.use_abcd_subject_ids = use_abcd_subject_ids\n self.low_memory_mode = low_memory_mode\n self.strat_u_name = strat_u_name\n self.random_state = random_state\n self.n_jobs = n_jobs\n self.dpi = dpi\n self.mp_context = mp_context\n\n self._print('Default params set:')\n self._print('notebook =', self.notebook)\n self._print('use_abcd_subject_ids =', self.use_abcd_subject_ids)\n self._print('low memory mode =', self.low_memory_mode)\n self._print('strat_u_name =', self.strat_u_name)\n self._print('random state =', self.random_state)\n self._print('n_jobs =', self.n_jobs)\n self._print('dpi =', self.dpi)\n self._print('mp_context =', self.mp_context)\n\n # Initialze various variables\n self.name_map, self.exclusions, self.inclusions = {}, set(), set()\n self.data, self.covars = pd.DataFrame(), pd.DataFrame()\n self.targets, self.strat = pd.DataFrame(), pd.DataFrame()\n\n # Dict objects to hold encoders\n self.covars_encoders = {}\n self.targets_encoders = {}\n self.strat_encoders = {}\n\n # Class values to be set later\n self.all_data = None\n self.targets_keys = []\n\n # Stores the gloabl train/test split\n self.train_subjects, self.test_subjects = None, None\n\n # CV by default is just random splits\n self.CV = CV()\n\n # Store default dicts as init empty\n self.default_load_params, self.default_ML_verbosity = {}, {}\n\n # Scores are saved after each eval or test run\n self.eval_scores, self.test_scores = {}, {}\n\n self.subject_id = 'src_subject_id'\n\n self.last_run_name = None\n self.last_subjects_to_use_names = None\n\n self.file_mapping = {}\n self.data_file_keys = []\n\n self._print('ABCD_ML object initialized')\n\n def Save(self, loc, low_memory=False):\n '''This class method is used to save an existing ABCD_ML\n object for further use.\n\n Parameters\n ----------\n loc : str or Path\n The location in which the pickle of the ABCD_ML object\n should be saved! This is the same loc which should be\n passed to :func:`Load ` in order to\n re-load the object.\n\n low_memory : bool, optional\n If this parameter is set to True, then self.data,\n self.targets, self.covars, self.strat will be deleted\n before saving. The assumption for the param to be used is\n that self.all_data has already been created, and therefore\n the individual dataframes with data, covars ect... can safely\n be deleted as the user will not need to work with them directly\n any more.\n\n In addition, self.Model_Pipeline (which contains\n information about the last run Evaluate or Test call) will be\n deleted.\n\n ::\n\n default = False\n '''\n\n if low_memory:\n self.data, self.covars = pd.DataFrame(), pd.DataFrame()\n self.targets, self.strat = pd.DataFrame(), pd.DataFrame()\n\n try:\n del self.Model_Pipeline\n except AttributeError:\n pass\n\n with open(loc, 'wb') as f:\n pkl.dump(self, f)\n\n def _init_logs(self):\n\n if self.log_dr is not None:\n\n if self.log_dr == '':\n self.log_dr = os.getcwd()\n\n # Ensure log_dr exists, if not make it\n os.makedirs(self.log_dr, exist_ok=True)\n\n # Get exp_log_dr name\n self.exp_log_dr = os.path.join(self.log_dr, self.exp_name)\n\n if os.path.isdir(self.exp_log_dr):\n\n if self.existing_log == 'new':\n\n cnt = 1\n while os.path.isdir(self.exp_log_dr +\n '(' + str(cnt) + ')'):\n cnt += 1\n\n self.exp_log_dr += '(' + str(cnt) + ')'\n\n # If overwrite, delete everything, then make new blank\n elif self.existing_log == 'overwrite':\n shutil.rmtree(self.exp_log_dr)\n\n # Make the new dr\n if self.existing_log != 'append':\n os.mkdir(self.exp_log_dr)\n\n # If the dr doesn't already exist, regardless of existing log\n # Just make new dr.\n else:\n os.mkdir(self.exp_log_dr)\n\n # Make the log file if not already made.\n self.log_file = os.path.join(self.exp_log_dr, 'logs.txt')\n\n else:\n self.exp_log_dr = None\n self.log_file = None\n\n def _print(self, *args, **kwargs):\n '''Overriding the print function to allow for\n customizable verbosity within class methods. Will also\n take care of logging behavior.\n\n Parameters\n ----------\n args\n Anything that would be passed to default python print\n '''\n\n dont_print = kwargs.pop('dont_print', False)\n\n if self.verbose and not dont_print:\n print(*args, **kwargs)\n\n if self.log_file is not None:\n log = open(self.log_file, 'a')\n print(*args, **kwargs, file=log)\n log.close()\n\n def _print_nothing(self, *args, **kwargs):\n pass\n\n # Data loader functionality\n from ._Data import (Set_Default_Load_Params,\n _make_load_params,\n _get_data_file_cnt,\n Load_Name_Map,\n Load_Data,\n Load_Data_Files,\n Load_Targets,\n _proc_target,\n _print_loaded_targets,\n Load_Covars,\n _proc_covar,\n Load_Strat,\n _proc_strat,\n Load_Exclusions,\n Load_Inclusions,\n Drop_Data_Cols,\n _drop_data_cols,\n Filter_Data_Cols,\n Filter_Data_Files_Cols,\n Proc_Data_Unique_Cols,\n _proc_data_unique_cols,\n Drop_Data_Duplicates,\n Binarize_Target,\n _proc_threshold,\n Binarize_Covar,\n Get_Overlapping_Subjects,\n Clear_Name_Map,\n Clear_Data,\n Clear_Covars,\n Clear_Targets,\n Clear_Strat,\n Clear_Exclusions,\n Clear_Inclusions,\n Get_Nan_Subjects,\n _get_targets_key,\n _load_datasets,\n _load_user_passed,\n _load_dataset,\n _common_load,\n _load,\n _set_overlap,\n _merge_existing,\n _proc_df,\n _load_set_of_subjects,\n _process_subject_name,\n _drop_na,\n _filter_by_eventname,\n _show_na_info,\n _drop_excluded,\n _drop_included,\n _filter_excluded,\n _filter_included,\n _get_overlapping_subjects,\n Prepare_All_Data,\n _get_cat_keys,\n _set_data_scopes,\n _get_base_targets_names,\n _get_covar_scopes)\n\n # Update loader docstrings\n Load_Name_Map.__doc__ =\\\n get_new_docstring(Set_Default_Load_Params, Load_Name_Map)\n Load_Data.__doc__ =\\\n get_new_docstring(Set_Default_Load_Params, Load_Data)\n Load_Data_Files.__doc__ =\\\n get_new_docstring(Load_Data, Load_Data_Files)\n Load_Targets.__doc__ =\\\n get_new_docstring(Set_Default_Load_Params, Load_Targets)\n Load_Covars.__doc__ =\\\n get_new_docstring(Set_Default_Load_Params, Load_Covars)\n Load_Strat.__doc__ =\\\n get_new_docstring(Set_Default_Load_Params, Load_Strat)\n Filter_Data_Cols.__doc__ =\\\n get_new_docstring(Set_Default_Load_Params, Filter_Data_Cols)\n Proc_Data_Unique_Cols.__doc__ =\\\n get_new_docstring(Set_Default_Load_Params, Proc_Data_Unique_Cols)\n Drop_Data_Duplicates.__doc__ =\\\n get_new_docstring(Set_Default_Load_Params, Drop_Data_Duplicates)\n\n # Validation / CV funcationality\n from ._Validation import (Define_Validation_Strategy,\n Train_Test_Split,\n _add_strat_u_name,\n _get_info_on)\n\n # Machine Learning functionality\n from ._ML import (Set_Default_ML_Verbosity,\n _ML_print,\n Evaluate,\n Test,\n _premodel_check,\n _preproc_model_pipeline,\n _preproc_problem_spec,\n _get_split_vals,\n _get_subjects_to_use,\n _init_model,\n _handle_scores,\n _print_summary_score,\n _add_to_scores,\n _save_results)\n\n # Fill Evaluate and Test's docstring\n # Evaluate.__doc__ = get_new_docstring(Set_Default_ML_Params, Evaluate)\n # Test.__doc__ = get_new_docstring(Evaluate, Test)\n\n from ._Plotting import (_plot,\n _proc_subjects,\n Show_Data_Dist,\n _input_targets,\n _input_covars,\n _input_strat,\n Show_Targets_Dist,\n Show_Covars_Dist,\n Show_Strat_Dist,\n _get_single_df,\n _show_single_dist,\n _get_cat_display_df,\n _show_dist,\n _display_df,\n _get_top_global,\n Plot_Global_Feat_Importances,\n _plot_multiclass_global_feat_importances,\n _plot_global_feat_importances,\n Plot_Local_Feat_Importances,\n _plot_shap_summary)\n\n from ._Tables import (Save_Table,\n _get_single_dfs,\n _get_table_contents,\n _get_group_titles)\n","sub_path":"ABCD_ML/main/ABCD_ML.py","file_name":"ABCD_ML.py","file_ext":"py","file_size_in_byte":19330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"547943538","text":"# The goal of this python script is to create a csv datafile from wgi recap documents\n\n# TODO: Find a way to get information without being so reliant on specific tag identification\n\n\nimport os # For __file__\nimport time # For sleep\nimport requests\nimport re # For regex\nimport pandas as pd\nfrom bs4 import BeautifulSoup # To read html docs\n\ndef parse_recap(link, read_type):\n \"\"\"\n Returns a dataframe containing score information for each ensemble\n \"\"\"\n\n # Conditionally create the soup object from web site or from local file\n x = read_type\n\n if (x == \"LOCAL\"):\n recap_soup = BeautifulSoup(open(link), 'html.parser')\n elif (x == \"WEB\"):\n recap_soup = BeautifulSoup(requests.get(link).text, 'html.parser')\n\n\n # Find div tags with style attributes using regex (this is a very bad way to do this)\n title_smash = []\n for tag in recap_soup.find_all(\"div\", attrs={'style':re.compile(r\".*\")}):\n print(tag.string)\n\n if (tag.string is None):\n title_smash.append(\"\")\n elif (len(tag.string) != 0):\n title_smash.append(tag.string)\n\n event_description = ''.join(title_smash)\n\n # Find each individual table\n recap_soup = recap_soup.find_all(\"table\", style=\"border-bottom: solid 1px #000; margin: 10px auto 0px auto;\")\n\n # Create empty list for all table information\n all_info = []\n\n # Get information for each individual table\n for table in recap_soup:\n\n # Get relevant information from each indivual table\n ensemble_names = [ensemble.text for ensemble in table.find_all(\"td\", \"content topBorder rightBorderDouble\")]\n all_scores = [score.text for score in table.find_all(\"td\", \"content score\")]\n judge_names = [judge.text for judge in table.find_all(\"td\", \"content topBorder rightBorder header subcaptionTotal\")]\n captions = [caption.text for caption in table.find_all(\"td\", \"content rightBorder topBorder header captionTotal\")]\n which_class = [score_class.text for score_class in table.find_all(\"td\", style=\"text-align: center; padding: 2px; font-weight: bold; font-size: 14px;\")]\n num_ensembles = len(ensemble_names)\n\n # Handle weird judge tags\n if (len(judge_names) == 0):\n judge_names = [judge.text for judge in table.find_all(\"td\", \"content topBorder rightBorder header subcaptionTotal \")]\n\n\n # First get the ratio of judges - 1 to captions\n ratio = (len(judge_names) - 1) / (len(captions) - 1)\n\n if ratio == 1:\n check = ((len(judge_names) - 1)*2) + (len(captions) - 1) + 3\n elif ratio == 2:\n check = ((len(judge_names) - 1)*3) + (len(captions) - 1) + 4\n\n print(\"Mod check: \" + str(check))\n\n # Pack everything together\n table_information = (ensemble_names, all_scores, judge_names, captions, num_ensembles, which_class, check)\n\n # Append to master list\n all_info.append(table_information)\n\n\n anthonys_greatest_accomplishment = pd.DataFrame()\n\n # Restructure raw score stream\n # Group raw data stream by number of columns in the table (32 is hardcoded) into separate lists\n for table in all_info:\n i = 1\n master_list = []\n sublist = []\n\n check_width = table[6]\n\n # Group scores by table width (check_width)\n for x in table[1]: # Point to score information\n sublist.append(x)\n\n if (i % check_width == 0):\n master_list.append(sublist)\n i = 1\n sublist = []\n else:\n i = i + 1\n\n df = pd.DataFrame(master_list)\n\n df[\"Ensemble\"] = table[0] # Add ensembles to df\n df[\"Class\"] = table[5][0] # table[5] gives returns a list, access its first element\n df[\"Event_Name\"] = event_description\n\n anthonys_greatest_accomplishment = anthonys_greatest_accomplishment.append(df)\n\n return anthonys_greatest_accomplishment\n\n\n# Recap link for 2018\n# https://www.wgi.org/percussion/2018-perc-scores/\n\n# Recap link for 2017\n# https://www.wgi.org/2017-percussion-scores/\n\n# Recap links for MCGC (lots of years)\n# https://www.mcgc.net/scores\n\n# Recap links for California (lots of years)\n# https://sc-pa.org/\n\n\n# Link used to create the intial version of the recap reader\noriginal_link = \"https://recaps.competitionsuite.com/dcdb1a72-f30b-413a-9311-15b8c600138c.htm\"\n\n# Local versions of original_link\nfile_location = os.path.dirname(__file__) + \"/the_holy_file.html\"\nsecond_file_location = os.path.dirname(__file__) + \"/secondary_recap.html\"\n\n# Different recap from WGI's website\ntest_link = \"https://recaps.competitionsuite.com/c06aa0b9-500e-4ab4-9960-fb0e04e103a1.htm\"\n\n# Recap from MCGC (Michigan Circuit)\nmcgc_link = \"https://recaps.competitionsuite.com/904e9141-55b7-45f9-acc8-778fcf83d208.htm\"\n\n# Recap from SCPA (California Circuit)\ncali_link = \"https://recaps.competitionsuite.com/9dbe02e5-8099-4487-b336-ad0969b9607c.htm\"\n\n\n# Point to a web link\n# goodies = parse_recap(cali_link, \"WEB\")\n\n# Point to a local file\n#goodies = parse_recap(file_location, \"LOCAL\")[1]\n\n# Works fine\n#my_df = parse_recap(file_location, \"LOCAL\")\n#print(my_df)\n\n# Works fine\n#test_df = parse_recap(second_file_location, \"LOCAL\")\n#print(test_df)\n\nonline_df = parse_recap(test_link, \"WEB\")\nprint(online_df)\n\n# Write to csv\nonline_df.to_csv(\"output_9-24-18.csv\")\n","sub_path":"python/Old Stuff/get_recaps/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":5361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"150418495","text":"import hand\nimport calculate\n\ndef check_input(deal):\n\n acceptable_values = list(range(2, 11))\n acceptable_values.extend([\"A\", \"J\", \"Q\", \"K\"])\n acceptable_values = [str(val) for val in acceptable_values]\n acceptable_suits = [\"D\", \"C\", \"S\", \"H\"]\n\n clean_deal = deal.replace(\", \", \",\").replace(\" \", \",\").replace(\",,\", \",\")\n print(f'Your entries: {clean_deal.split(\",\")}')\n print(clean_deal)\n clean_deal = [item for item in clean_deal.split(\",\") if item != \"\"]\n print(clean_deal)\n is_valid = True\n\n for item in clean_deal:\n if \"-\" not in item:\n print(f\"Invalid Format: {item}\")\n is_valid = False\n else:\n if item.split(\"-\")[0] not in acceptable_values:\n print(f\"Invalid Format: {item} (Unknown card value)\")\n is_valid = False\n elif item.split(\"-\")[-1] not in acceptable_suits:\n print(f\"Invalid Format: {item} (Unknown suit)\")\n is_valid = False\n\n return is_valid\n\n\ndef main(arglist):\n\n deal = \",\".join(arglist)\n\n if check_input(deal) != True:\n print(\"Exiting\")\n sys.exit()\n\n player_hand = hand.Hand(deal)\n\n calculate.score_hand(player_hand)\n\n\nif __name__ == \"__main__\":\n import sys\n\n main(sys.argv[1:])\n","sub_path":"cribbage-counsel.py","file_name":"cribbage-counsel.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"460166339","text":"import unittest\nfrom adder import Adder\n\n\nclass TestBob(unittest.TestCase):\n\n def test_create_adder(self):\n adder = Adder()\n\n def test_increment(self):\n adder = Adder()\n self.assertEqual(adder.increment(3), 4)\n\n \nif __name__=='__main__':\n unittest.main(verbosity=3)\n","sub_path":"app/test_adder.py","file_name":"test_adder.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"454497407","text":"\"\"\"\nThis script will rebuild the database from scratch. It should run only once during production\nand many times during development.\n\"\"\"\n\nimport logging\nfrom lib.sqlitestore import DataStore\nfrom lib import my_env\n\n\ndef main():\n cfg = my_env.init_env(\"convert_protege\", __file__)\n ds = DataStore(cfg)\n ds.remove_tables()\n ds.create_tables()\n logging.info('End Application')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Python/build_database.py","file_name":"build_database.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"145909597","text":"import numpy as np\nimport pandas as pd\nimport matplotlib\nmatplotlib.use('pdf')\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n# histograms\n'''\nfilenames = {\n #\"WW\": \"BGHToWW_gru_Yhat.npy\",\n #\"ZZ\": \"BGHToZZ_gru_Yhat.npy\"\n \"WW\": \"WW_N2.npy\",\n \"ZZ\": \"ZZ_N2.npy\"\n #\"Dense\": \"DensetW.npy\",\n #\"GRU\": \"GRUtW.npy\"\n #\"WW\": \"ww_j_pt.npy\",\n #\"ZZ\": \"zz_j_pt.npy\"\n #\"Jeff\": \"jeff_weights_bkg.npy\",\n #\"DAZSLE\": \"dazsle_weights_bkg.npy\"\n #\"WW\": \"ww_j_pt.npy\",\n #\"ZZ Unweighted\": \"zz_j_pt.npy\",\n #\"ZZ Jeff\": \"zz_j_pt.npy\",\n #\"ZZ DAZSLE\": \"zz_j_pt.npy\"\n}\n'''\n\ninf_dir = \"inference/\"\n\nsamples = [\"BGHToWW\", \"BGHToZZ\"]\nnevts = 1200000\n\n# files to use for N2, GRU, etc\nN2 = {\n \"WW\": \"BGHToWW_ss.npy\",\n \"ZZ\": \"BGHToZZ_ss.npy\",\n \"QCD\": \"QCD_ss.npy\"\n}\n\nY = {\n \"WW\": \"BGHToWW_Y_all.npy\",\n \"ZZ\": \"BGHToZZ_Y_all.npy\"\n}\n\nGRU = {\n \"WW\": \"BGHToWW_gru_Yhat_all.npy\",\n \"ZZ\": \"BGHToZZ_gru_Yhat_all.npy\",\n \"QCD\": \"QCD_gru_Yhat_all.npy\"\n}\n\nDNN = {\n \"WW\": \"BGHToWW_dnn_Yhat_all.npy\",\n \"ZZ\": \"BGHToZZ_dnn_Yhat_all.npy\",\n \"QCD\": \"QCD_dnn_Yhat_all.npy\"\n}\n\nj_pt = {\n \"WW\": \"WW_j_pt.npy\",\n \"ZZ\": \"ZZ_j_pt.npy\",\n \"QCD\": \"QCD_j_pt.npy\"\n}\n\nj_msd = {\n \"WW\": \"WW_j_msd.npy\",\n \"ZZ\": \"ZZ_j_msd.npy\",\n \"QCD\": \"QCD_j_msd.npy\"\n}\n\nweights = {\n \"WW\": np.load(\"dazsle_weights_sig.npy\"),\n \"ZZ\": np.load(\"dazsle_weights_bkg.npy\")\n} \n\n\n\nout = PdfPages(\"out.pdf\")\n\ndef make_arrays(filenames):\n arrays = {}\n basedir = \"\"\n for k, v in filenames.iteritems():\n if 'Y' in v: basedir = inf_dir\n try:\n arrays[k] = np.load(basedir+v)[:, :1]\n except:\n arrays[k] = np.load(basedir+v)\n #print type(arrays[k]), arrays[k]\n\n return arrays\n\ndef make_hist(filenames, weight=False, title=\"\", xlabel=\"\", min_=None, max_=None):\n plt.figure(figsize=(6, 6), dpi=100)\n plt.title(title)\n plt.xlabel(xlabel)\n\n arrays = make_arrays(filenames)\n if min_ is None: min_ = min([min(v) for v in arrays.itervalues()])\n if max_ is None: max_ = max([max(v) for v in arrays.itervalues()])\n bins = np.linspace(min_, max_, 100)\n\n for k, v in arrays.iteritems():\n #print k\n #print \"v shape min and max: \", v.shape, '\\n', v.min(), '\\n', v.max()\n if weight:\n w = weights[k]\n #print \"using weights: \", w, len(w)\n n = min(len(w), v.shape[0])\n v = v[:n]\n w = w[:n]\n plt.hist(v, bins=bins, density=True, label=k, histtype='step', weights=w)\n else:\n plt.hist(v[:nevts], bins=bins, density=True, label=k, histtype='step')\n\n \n ''' # plot weighted vs unweighted\n for k, v in arrays.iteritems():\n plt.hist(v, bins=bins, density=True, label='weighted', histtype='step', weights=weights[k])\n plt.hist(v, bins=bins, density=True, label='unweighted', histtype='step')\n '''\n \n plt.legend(loc='upper right')\n \n PdfPages.savefig(out, dpi=100)\n return\n\ndef make_hist_from_arrays(arrays, weight=False, title=\"\", xlabel=\"\", min_=None, max_=None):\n plt.figure(figsize=(6, 6), dpi=100)\n plt.title(title)\n plt.xlabel(xlabel)\n\n if min_ is None: min_ = min([min(v) for v in arrays.itervalues()])\n if max_ is None: max_ = max([max(v) for v in arrays.itervalues()])\n bins = np.linspace(min_, max_, 100)\n\n for k, v in arrays.iteritems():\n #print k\n #print \"v shape min and max: \", v.shape, '\\n', v.min(), '\\n', v.max()\n if weight:\n w = weights[k][:v.shape[0]]\n #print \"using weights: \", w, len(w)\n plt.hist(v, bins=bins, density=True, label=\"Response > {}\".format(k), histtype='step', weights=w)\n else:\n plt.hist(v, bins=bins, density=True, label=\"Response > {}\".format(k), histtype='step')\n \n plt.legend(loc='upper right')\n \n PdfPages.savefig(out, dpi=100)\n return\n\n# roc curve\nfrom sklearn.metrics import roc_curve\n\nys = [np.load(inf_dir+name+\"_Y_all.npy\") for name in samples]\ny = np.concatenate(ys)\ndnn_yhat = np.concatenate([v for v in make_arrays(DNN).itervalues()])\ngru_yhat = np.concatenate([v for v in make_arrays(GRU).itervalues()])\n\ndef make_roc():\n\n plt.figure(figsize=(6, 6), dpi=100)\n plt.title(\"ROC Curve\")\n plt.xlabel(\"False Positive Rate\")\n plt.ylabel(\"True Positive Rate\")\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n\n fpr_dnn, tpr_dnn, _ = roc_curve(y.argmax(axis=1), dnn_yhat[:, :1])\n fpr_gru, tpr_gru, _ = roc_curve(y.argmax(axis=1), gru_yhat[:, :1])\n\n plt.plot([0,1], [0,1], 'k--')\n plt.plot(fpr_dnn, tpr_dnn, label='DNN')\n plt.plot(fpr_gru, tpr_gru, label='GRU')\n\n plt.legend(loc='best')\n PdfPages.savefig(out, dpi=100)\n \n return\n\ndef make_msd_arrays(yhats, k, min_=0, max_=.8, n=5):\n try:\n yhat = yhats[k][:,0]\n except:\n yhat = yhats[k]\n msd = make_arrays(j_msd)[k]\n msds = {}\n for i in np.linspace(min_, max_, n):\n mask = np.where(yhat > i)[0]\n msds[i] = msd[mask]\n return msds\n\n#make_hist(N2, weight=True, title=\"N2\", xlabel=\"N2\")\n#make_hist(DNN, weight=True, title=\"DNN\", xlabel=\"Response\")\n#make_hist(GRU, weight=True, title=\"GRU\", xlabel=\"Response\")\n#make_roc()\n\ndef make_report():\n make_hist(j_pt, weight=False, title=\"j_pt (unweighted)\", xlabel=\"j_pt\")\n make_hist(j_pt, weight=True, title=\"j_pt (weighted)\", xlabel=\"j_pt\")\n make_hist(j_msd, weight=False, title=\"j_msd (unweighted)\", xlabel=\"j_msd\", min_=0, max_=200)\n make_hist(j_msd, weight=True, title=\"j_msd (weighted)\", xlabel=\"j_msd\", min_=0, max_=200)\n\n WW_DNN_j_msds = make_msd_arrays(make_arrays(DNN), \"WW\")\n WW_GRU_j_msds = make_msd_arrays(make_arrays(GRU), \"WW\")\n ZZ_DNN_j_msds = make_msd_arrays(make_arrays(DNN), \"ZZ\")\n ZZ_GRU_j_msds = make_msd_arrays(make_arrays(GRU), \"ZZ\")\n\n make_hist_from_arrays(WW_DNN_j_msds, weight=False, title=\"WW j_msd filtered by DNN Response (Unweighted)\", xlabel=\"j_msd\", min_=0, max_=200)\n make_hist_from_arrays(WW_GRU_j_msds, weight=False, title=\"WW j_msd filtered by GRU Response (Unweighted)\", xlabel=\"j_msd\", min_=0, max_=200)\n make_hist_from_arrays(ZZ_DNN_j_msds, weight=False, title=\"ZZ j_msd filtered by DNN Response (Unweighted)\", xlabel=\"j_msd\", min_=0, max_=200)\n make_hist_from_arrays(ZZ_GRU_j_msds, weight=False, title=\"ZZ j_msd filtered by GRU Response (Unweighted)\", xlabel=\"j_msd\", min_=0, max_=200)\n\n\ndef make_QCD_report():\n make_hist(j_pt, weight=False, title=\"j_pt (unweighted)\", xlabel=\"j_pt\")\n make_hist(j_msd, weight=False, title=\"j_msd (unweighted)\", xlabel=\"j_msd\", min_=0, max_=200)\n\n QCD_DNN_j_msds = make_msd_arrays(make_arrays(DNN), \"QCD\", min_=0.4, max_=0.8, n=5)\n QCD_GRU_j_msds = make_msd_arrays(make_arrays(GRU), \"QCD\", min_=0.4, max_=0.8, n=5)\n\n make_hist_from_arrays(QCD_DNN_j_msds, weight=False, title=\"QCD j_msd filtered by DNN Response (Unweighted)\", xlabel=\"j_msd\", min_=0, max_=200)\n make_hist_from_arrays(QCD_GRU_j_msds, weight=False, title=\"QCD j_msd filtered by GRU Response (Unweighted)\", xlabel=\"j_msd\", min_=0, max_=200)\n\n \n#make_report()\nmake_QCD_report()\n\nout.close()\n\n\n\n\n\n\n\n'''\ndazsle_weights = np.load(basedir+\"dazsle_weights_ordered.npy\")\ni = len(dazsle_weights) - len(arrays[\"ZZ Unweighted\"])\n\nweights = {\n \"WW\": np.ones(len(arrays[\"WW\"])),\n \"ZZ Unweighted\": np.ones(len(arrays[\"ZZ Unweighted\"])),\n \"ZZ Jeff\": np.load(basedir+\"jeff_weights_bkg.npy\"),\n \"ZZ DAZSLE\": dazsle_weights[i:]\n}'''\n","sub_path":"train/dazsle-tagger/mass_sculpt_plots.py","file_name":"mass_sculpt_plots.py","file_ext":"py","file_size_in_byte":7483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"193903942","text":"import zipfile\nimport glob\nimport os.path\n\ndef zipdir(fn, d = \".\"):\n (upper_dir, base_dir) = os.path.split(d)\n os.chdir(upper_dir) \n files = glob.glob(base_dir+\"/*\") \n zippable_files = []\n for f in files:\n if (os.path.isfile(f)): \n zippable_files.append(f) \n zf = zipfile.ZipFile(fn, \"w\", zipfile.ZIP_DEFLATED)\n for fn_to_archive in zippable_files:\n zf.write(fn_to_archive)\n zf.close()\n","sub_path":"Exercises/Archives_Homework/src/zipdir.py","file_name":"zipdir.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"546141199","text":"\n'''Import books.csv into books table.'''\nimport csv\nimport os\nfrom sqlalchemy import create_engine, text\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\n# Set up database connection\nengine = create_engine(os.getenv(\"DATABASE_URL\"), \n connect_args={\"application_name\":\"application.py\"}, \n echo=True)\ndb = scoped_session(sessionmaker(bind=engine))\n\n\ndef main():\n with open(\"books.csv\", \"r\") as books:\n reader = csv.DictReader(books, fieldnames=['isbn', 'title', 'author', 'year'])\n # Skip header\n next(reader)\n # Insert CSV data into table\n statement = text(\"INSERT INTO books(isbn, title, author, year) VALUES(:isbn, :title, :author, :year)\")\n for row in reader:\n row['year'] = int(row['year'])\n db.execute(statement, row)\n db.commit()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"24771513","text":"import pytorch_lightning as pl\nfrom pytorch_lightning import callbacks\nfrom pytorch_lightning.loggers import TensorBoardLogger\nfrom pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint\n\nfrom utils.load_cfg import load_cfg\nfrom utils.prepare_seed import prepare_seed\n\nimport click\n\nfrom agents import *\n\nfrom loaders import *\n\n@click.command()\n@click.option('--config', '-cfg', required=True)\ndef cli(config):\n cfg = load_cfg(config)\n prepare_seed(cfg.exp_cfg.seed)\n agent = eval(cfg.agent)(cfg.agent_cfg)\n loaders = eval(cfg.data_loader.name)(**cfg.data_loader.kwargs)\n checkpoint_callback = ModelCheckpoint(\n dirpath=cfg.checkpoint_dir,\n **cfg.model_checkpoint\n )\n logger = TensorBoardLogger(\n name=cfg.exp_name,\n **cfg.logger\n )\n\n trainer = pl.Trainer(\n callbacks=[checkpoint_callback],\n default_root_dir=cfg.out_dir,\n logger=logger,\n **cfg.trainer\n )\n\n trainer.fit(\n model=agent,\n train_dataloader=loaders.train_loader,\n val_dataloaders=loaders.test_loader\n )\n\nif __name__ == '__main__':\n # cli(['-cfg', 'configs/iwslt15_transformer.yaml'])\n # cli(['-cfg', 'configs/fashion_mnist_mlp.yaml'])\n cli()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"165677772","text":"from queue import Empty\nfrom selenium import webdriver\nfrom datetime import date\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport pyttsx3\nfrom Identify_query import Recognize_voice\n\n\ndef bus_auto(x_var):\n engine = pyttsx3.init()\n import time\n driver = webdriver.Chrome(\"C:\\Final Year Project\\Chrome Driver\\chromedriver.exe\")\n driver.maximize_window()\n url = \"https://www.redbus.in/\"\n driver.get(url)\n time.sleep(1)\n # retrieve data from user data file\n driver.find_element_by_id('src').send_keys(x_var[0])\n time.sleep(3)\n driver.find_element_by_id('dest').send_keys(x_var[1])\n time.sleep(3)\n driver.find_element_by_id('onward_cal').send_keys('0')\n\n def month_to_number(string):\n m = {\n 'jan': 1,\n 'feb': 2,\n 'mar': 3,\n 'apr': 4,\n 'may': 5,\n 'jun': 6,\n 'jul': 7,\n 'aug': 8,\n 'sep': 9,\n 'oct': 10,\n 'nov': 11,\n 'dec': 12\n }\n s = string.strip()[:3].lower()\n\n try:\n out = m[s]\n return out\n except:\n raise ValueError('Not a month')\n\n x = date.today()\n u_mm = x_var[4]\n mm = x.strftime(\"%B\")\n _u_mm = month_to_number(u_mm)\n _mm = month_to_number(mm)\n dd = x_var[3]\n flag = _u_mm - _mm\n r_dd = x_var[7]\n r_mm = x_var[8]\n r_yyyy = x_var[9]\n\n while flag > 0:\n try:\n d = driver.find_element_by_xpath(\n \"//div[@id='rb-calendar_onward_cal']/table/tbody/tr/td[@class='next']\").click()\n flag -= 1\n except:\n raise Empty(\"Please provide valid month\")\n\n driver.find_element_by_xpath(\"//div[@id='rb-calendar_onward_cal']/table/tbody/tr/td[text()=\" + dd + \"]\").click()\n driver.find_element_by_xpath(\"//button[@id='search_btn']\").click()\n time.sleep(10)\n p = driver.find_element_by_xpath(\"//div[text()='View Buses']\")\n if p:\n p.click()\n else:\n p = 0\n\n content = driver.page_source\n soup = BeautifulSoup(content, \"html.parser\")\n info = soup.find_all('div', attrs={'class': 'clearfix row-one'})\n print(len(info))\n name_ = []\n tpe_ = []\n price_ = []\n time_ = []\n for a in info:\n name = a.find('div', attrs={'class': 'travels lh-24 f-bold d-color'})\n name_.append(name.text)\n tpe = a.find('div', attrs={'class': 'bus-type f-12 m-top-16 l-color'})\n tpe_.append(tpe.text)\n price = a.find('div', attrs={'class': 'seat-fare'})\n price_with_text = price.text\n price_without_text = res = [int(i) for i in price_with_text.split() if i.isdigit()]\n price_.append(price_without_text[0])\n time = a.find('div', attrs={'class': 'dp-time f-19 d-color f-bold'})\n time_.append(time.text)\n\n df = pd.DataFrame({'Travels Name': name_, 'Bus Type': tpe_, 'Price': price_, 'Time': time_})\n df.to_csv('products.csv', index=False, encoding='utf-8')\n\n driver.close()\n\n csv_data = pd.read_csv('products.csv')\n all_ele = []\n for row in csv_data.index:\n all_ele.append(csv_data['Price'][row])\n\n all_ele_len = len(all_ele)\n average_price = sum(all_ele) / all_ele_len\n print(average_price)\n\n engine.say(\"Now tell me, Which type of Bus you like to book?\")\n engine.say(\"We have some types, and these are: R T C means Government buses, Shivshahi buses, Shivneri buses, \"\n \"Private buses, or you can book sleeper bus \")\n engine.runAndWait()\n b_type = Recognize_voice()\n engine.say(\"at what time you like to book\")\n engine.runAndWait()\n booking_time = Recognize_voice()\n bad_stm = ['at', 'on', 'in']\n for i in bad_stm:\n booking_time = booking_time.replace(i, '')\n\n # making data frame from csv file\n data = pd.read_csv(\"products.csv\", delimiter=',')\n\n # replacing blank spaces with '_'\n data.columns = [column.replace(\" \", \"_\") for column in data.columns]\n\n def closest(lst, K):\n return lst[min(range(len(lst)), key=lambda i: abs(lst[i] - K))]\n\n # time filter\n\n # find actual price from average price\n K = average_price\n actual_price_close_to_avg_price = closest(all_ele, K)\n print(actual_price_close_to_avg_price)\n\n if 'shivshahi bus' in b_type or 'shivshahi buses' in b_type or 'shivshahi' in b_type:\n # filtering with query method for Shivshahi buses\n # data.query('Bus_Type == \"SHIVSHAHI\"', inplace=True)\n\n ele_having_shivshahi = data[data.Bus_Type == 'SHIVSHAHI']\n minValue = ele_having_shivshahi['Price'].min()\n time_of_that_bus = ele_having_shivshahi.loc[ele_having_shivshahi['Price'] == minValue, 'Time'].iloc[0]\n print(ele_having_shivshahi)\n print(minValue)\n print(time_of_that_bus)\n engine.say(\"I found one bus for you at lowest price, at \" + str(minValue))\n engine.say(\"and Bus time is \" + str(time_of_that_bus))\n engine.runAndWait()\n bus_name_at_user_time = ele_having_shivshahi.loc[ele_having_shivshahi['Time'] == booking_time, 'Travels_Name'].iloc[0]\n print(bus_name_at_user_time)\n","sub_path":"bus_automate.py","file_name":"bus_automate.py","file_ext":"py","file_size_in_byte":5122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"498468183","text":"# -*- coding: utf-8 -*-\nfrom subprocess import check_output\nimport glob\nimport sys\nimport os \nfrom IIIFpres import iiifpapi3\nfrom itertools import cycle\n#folder = sys.argv[1]\nfolder = r\"/Users/univr/Pictures/41\"\nromconv = {1: 'I',\n 2: 'II',\n 3: 'III',\n 4: 'IV',\n 5: 'V',\n 6: 'VI',\n 7: 'VII',\n 8: 'VIII',\n 9: 'IX',\n 10: 'X',\n 11: 'XI',\n 12: 'XII',\n 13: 'XIII',\n 14: 'XIV',\n 15: 'XV',\n 16: 'XVI',\n 17: 'XVII',\n 18: 'XVIII',\n 19: 'XIX'}\n\ntsv_datasetpath = r\"list.tsv\"\nsegnatura = 41\ndef search(segnatura):\n with open(tsv_datasetpath,'r') as f:\n header = True \n for i in f:\n records = i.split(\"\\t\")\n if header:\n h = records\n header = False\n elif records[5] == str(segnatura):\n return dict(zip(h,records))\nrecord = search(segnatura)\nsegnatura = str(segnatura)\niiifpapi3.BASE_URL = \"http://lezioni.meneghetti.univr.it\" \nmanifest = iiifpapi3.Manifest()\nmanifest.set_id(extendbase_url=[\"manifests\" ,segnatura])\nsegn = \"%s (%s)\" %(record[\"numero_del_codice\"],record[\"numerazione_araba\"])\nmanifest.add_label(\"it\",\"Manoscritto: %s\" %segn)\n\nmanifest.add_metadata(label=\"rilegatura_moderna\",value=record[\"rilegatura_moderna\"],language_l=\"it\")\nmanifest.add_metadata(label=\"Collocazione:\",value=record[\"Collocazione\"],language_l=\"it\")\nmanifest.add_metadata(label=\"Segnatura espressa come numero arabo:\",value=record[\"roman_converted\"],language_l=\"it\")\nmanifest.add_metadata(label=\"Segnatura:\",value=record[\"numero_del_codice\"],language_l=\"it\")\nmanifest.add_metadata(label=\"Antica segnatura con numero arabo:\",value=record[\"numerazione_araba\"],language_l=\"it\")\nmanifest.add_metadata(label=\"Titolo secondo don Spagnolo:\",value=record[\"titolo\"],language_l=\"it\")\nmanifest.add_metadata(label=\"Materiale\",value=record[\"materiale\"],language_l=\"it\")\nmanifest.add_metadata(label=\"Numero di fogli\",value=record[\"fogli\"],language_l=\"it\")\n\nif \"-\" in record[\"Spagnolo\"]:\n pagsp = \"pagine %s\" %record[\"Spagnolo\"]\nelse: \n pagsp = \"pagina %s\" %record[\"Spagnolo\"]\n\nmanifest.add_metadata(label=\"Riferimento al catalogo di don Spagnolo\",value=pagsp,language_l=\"it\")\nif record[\"datazione_f\"] != \"\":\n if int(record[\"datazione_f\"][:-2]) - 1 == int(record[\"datazione_i\"][:-2]):\n datazione = \"al %s secolo\" %romconv[int(record[\"datazione_f\"][:-2])]\n else:\n datazione = \"tra i secoli %s e %s\" %(romconv[int(record[\"datazione_f\"][:-2])],romconv[int(record[\"datazione_f\"][:-2])])\nmanifest.add_metadata(label=\"Databile\",value=datazione,language_l=\"it\",language_v=\"it\")\nmanifest.add_metadata(label=\"lingua\",value=record[\"lingua\"],language_l=\"it\")\nif record[\"altezza\"] != \"\" and record[\"ampiezza\"] != \"\":\n dim = \"%s x %s cm\" %(record[\"altezza\"],record[\"ampiezza\"])\n\nmanifest.add_metadata(label=\"Dimensioni\",value=dim,language_l=\"it\")\nmanifest.add_metadata(label=\"Rilegatura:\",value=record[\"rilegatura\"],language_l=\"it\")\nmanifest.add_metadata(label=\"Tipo di rilegatura\",value=record[\"tipo_rilegatura\"],language_l=\"it\")\nmanifest.add_metadata(label=\"Materiale rilegatura\",value=record[\"materiale_rilegatura\"],language_l=\"it\")\n# more complex entry can be mapped directly to a dictionary and inserted using entry arguments\nmanifest.add_summary(f\"Il manoscritto {segn} è databile {datazione} secondo le informazioni riportate nell catalogo di don Spagnolo ({pagsp}). \",language=\"it\")\nmanifest.set_viewingDirection(\"left-to-right\")\nmanifest.add_behavior(\"paged\")\nmanifest.set_navDate(f\"{record['datazione_i']}-01-01T00:00:00Z\")\nmanifest.set_rights(\"http://creativecommons.org/licenses/by/4.0/\")\nmanifest.add_requiredStatement(label=\"Attribution\",value=\"Provided by University of Verona and Biblioteca Capitolare di Verona\",language_l=\"en\",language_v=\"en\")\nprov = manifest.add_provider()\nprov.add_label(\"it\",\"Università di Verona\")\nprov.set_id(\"https://www.univr.it/it/\")\nhomp = prov.add_homepage()\nhomp.set_id(\"https://sites.hss.univr.it/laboratori_integrati/laboratorio-lamedan/\")\nhomp.set_type(\"Text\")\nhomp.add_label(\"en\",\"Laboratorio integrati - LAboratorio di Studi MEdievale e DANteschi\")\nhomp.set_format(\"text/html\")\nlogo = prov.add_logo()\nlogo.set_id(\"https://cdn.univr.it/o/aol-theme/images/logo-univr-colori-80.png\")\nlogo.set_type(\"Image\")\nlogo.set_format(\"image/png\")\n\n\nimages = sorted([image for image in glob.glob(folder+\"/*.jp2\")])\npiatti_e_carte_di_guardia_ant = 4\nfogli = 259\npiatti_e_carte_di_guardia_post = 4\nplabels = ['dorso','piatto anteriore','risguardia anteriore',]\nsidesg1 = cycle(('recto','verso'))\nfor i in range(1,piatti_e_carte_di_guardia_ant+1):\n plabels.append(\"guardia anteriore %i %s\" %(i,next(sidesg1)))\n plabels.append(\"guardia anteriore %i %s\" %(i,next(sidesg1)))\n\nsidesf = cycle(('r','v'))\nfor i in range(1,fogli+1):\n plabels.append(\"%i%s\" %(i,next(sidesf)))\n plabels.append(\"%i%s\" %(i,next(sidesf)))\n\nsidesg2 = cycle(('r','v'))\nfor i in range(1,piatti_e_carte_di_guardia_post+1):\n plabels.append(\"guardia posteriore %i %s\" %(i,next(sidesg2)))\n plabels.append(\"guardia posteriore %i %s\" %(i,next(sidesg2)))\n\npost_elements = ['risguardia posteriore', 'piatto posteriore']\nfor i in post_elements:\n plabels.append(i)\n \nfor idx,d in enumerate(images):\n manloc = \"/manifests/%s\" %segnatura\n image = d\n canvas = manifest.add_canvas_to_items()\n if plabels[idx] in ['dorso','piatto anteriore']:\n canvas.add_behavior(\"paged\")\n canvas.set_id(extendbase_url=[\"manifests\",segnatura,\"canvas\",\"p%s\"%(idx+1)]) # in this case we use the base url\n out = check_output([\"exiftool\", image])\n Metadata = dict((e[:32].strip(),e[33:].strip()) for e in out.decode('utf8').split('\\n'))\n width = Metadata['Image Width']\n height = Metadata['Image Height']\n canvas.set_height(width)\n canvas.set_width(height)\n canvas.add_label(\"it\",plabels[idx])\n annopage = canvas.add_annotationpage_to_items()\n annopage.set_id(extendbase_url=[\"manifests\",segnatura,\"page\",\"p%s\"%(idx+1),\"1\"])\n annotation = annopage.add_annotation_to_items(target=canvas.id)\n annotation.set_id(extendbase_url=[\"manifests\",segnatura,\"annotation\",\"p%s-image\"%str(idx+1).zfill(4)])\n annotation.set_motivation(\"painting\")\n annotation.body.set_id(extendbase_url=[image,\"/full/max/0/default.jpg\"])\n annotation.body.set_type(\"Image\")\n annotation.body.set_format(\"image/jp2\")\n annotation.body.set_width(width)\n annotation.body.set_height(height)\n s = annotation.body.add_service()\n s.set_id(extendbase_url=[image])\n s.set_type(\"ImageService2\")\n s.set_profile(\"level2\")\n \n \nrng = manifest.add_range_to_structures()\nrng.set_id(extendbase_url=\"range/r0\")\nrng.add_label(\"en\",\"Table of Contents\")\nrng2 = iiifpapi3.Range()\nrng2.set_id(extendbase_url=\"range/r1\")\nrng2.add_label(\"en\",\"Introduction\")\nrng2.set_supplementary(\"https://example.org/iiif/book1/annocoll/introTexts\")\nrng2.add_canvas_to_items(\"https://example.org/iiif/book1/canvas/p1\")\nsr = iiifpapi3.SpecificResource()\nsr.set_source(\"https://example.org/iiif/book1/canvas/p2\")\nfs = iiifpapi3.FragmentSelector()\nfs.set_xywh(0,0,750,300)\nsr.set_selector(fs)\nrng2.add_item(sr)\nrng.add_item(rng2)\nannopage3 = iiifpapi3.AnnotationPage()\nannopage3.set_id(\"https://example.org/iiif/book1/page/manifest/1\")\nanno = iiifpapi3.Annotation(manifest.id)\nanno.set_id(\"https://example.org/iiif/book1/page/manifest/a1\")\nanno.set_motivation(\"commenting\")\nanno.body.set_language(\"en\")\nanno.body.set_value(\"I love this manifest!\")\nannopage3.add_item(anno)\nannopage3.set_id(\"https://example.org/iiif/book1/page/manifest/1\") \nmanifest.add_annotation(annopage3)\n\nmanifest.json_save(os.path.join(\"presentationapi\",\"manifests\",\"%s.json\" %segnatura))","sub_path":"examples/Example_Capitolare_server.py","file_name":"Example_Capitolare_server.py","file_ext":"py","file_size_in_byte":7642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"201738479","text":"\"\"\"\n借助http.client,从一台HTTP服务器上通过套接字抓取文件,文件名参数可以是一个完整的目录路径\n也可以通过末尾的?查询参数定制一个CGI脚本,触发一个远程程序,抓取得到的文件数据或远程程序输出可以保存\n到本地文件以便模拟FTP功能,或者使用str.find或者html.parser模块进行解析\n返回的是bytes字符串\n\"\"\"\n\nimport sys, http.client\nshowlines = 6\n\ntry:\n servername, filename = sys.argv[1:] #命令行参数\nexcept:\n servername, filename = \"learning-python.com\", '/index.html' #否则设置默认打开的网页\n\nprint(servername, filename)\nserver = http.client.HTTPConnection(servername) #连接到http站服务器\nserver.putrequest(\"GET\", filename) #发送请求和题头\nserver.putheader(\"Accept\", \"text/html\") #也可以用POST请求\nserver.endheaders() #CGI脚本文件名也可以\nreply = server.getresponse() #读取回复的题头和数据\nif reply.status != 200: #200表示成功,不等于200表示失败\n print(\"Error sending request\", reply.status, reply.reason)\nelse:\n data = reply.readlines() #接收到的数据的文件对象\n reply.close() \n for line in data[:showlines]: #显示前showlines行的数据\n print(line)","sub_path":"C13_http_getfile.py","file_name":"C13_http_getfile.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"402155920","text":"# -*- coding: utf-8 -*-\n'''\nThe behaviors to run the salt minion via ioflo\n'''\n\n# Import python libs\nimport os\nimport logging\nimport sys\nimport types\nimport traceback\nimport multiprocessing\nfrom collections import deque\n\n# Import salt libs\nimport salt.minion\nimport salt.payload\nimport salt.utils\nimport salt.utils.event\nimport salt.daemons.masterapi\nimport salt.utils.schedule\nfrom salt.exceptions import (\n CommandExecutionError, CommandNotFoundError, SaltInvocationError)\nfrom salt.transport.road.raet import yarding\nfrom salt.transport.road.raet import stacking\n\n# Import ioflo libs\nimport ioflo.base.deeding\n\n# Import Third Party Libs\nHAS_PSUTIL = False\ntry:\n import psutil\n HAS_PSUTIL = True\nexcept ImportError:\n pass\n\nHAS_RESOURCE = False\ntry:\n import resource\n HAS_RESOURCE = True\nexcept ImportError:\n pass\nlog = logging.getLogger(__name__)\n\n\nclass RouterMinion(ioflo.base.deeding.Deed): # pylint: disable=W0232\n '''\n Route packaets from raet into minion proessing bins\n '''\n Ioinits = {'opts': '.salt.opts',\n 'udp_stack': '.raet.udp.stack.stack',\n 'uxd_stack': '.salt.uxd.stack.stack',\n 'fun_in': '.salt.net.fun_in',\n }\n\n def postinitio(self):\n '''\n Map opts for convenience\n '''\n self.uxd_stack.value = stacking.StackUxd(\n lanename=self.opts.value['id'],\n yid=0,\n dirpath=self.opts.value['sock_dir'])\n self.fun_in.value = deque()\n\n def action(self):\n '''\n Empty the queues into process management queues\n '''\n # Start on the udp_in:\n # TODO: Route UXD messages\n while self.udp_stack.value.rxMsgs:\n data = self.udp_stack.value.rxMsgs.popleft()\n if data['route']['dst'][2] == 'fun':\n self.fun_in.value.append(data)\n if data['route']['dst'][1] is not None:\n if data['route']['dst'][1] in self.uxd_stack.value.yards:\n self.uxd_stack.value.transmit(data, data['route']['dst'][1])\n self.uxd_stack.value.serviceAll()\n while self.uxd_stack.value.rxMsgs:\n msg = self.uxd_stack.value.rxMsgs.popleft()\n estate = msg['route']['dst'][0]\n if estate is not None:\n if estate != self.opts.value['id']:\n self.udp_stack.value.message(\n msg,\n self.udp_stack.value.eids[estate])\n\n\nclass ModulesLoad(ioflo.base.deeding.Deed): # pylint: disable=W0232\n '''\n Reload the minion modules\n '''\n Ioinits = {'opts_store': '.salt.opts',\n 'grains': '.salt.loader.grains',\n 'modules': '.salt.loader.modules',\n 'returners': '.salt.loader.returners'}\n\n def postinitio(self):\n '''\n Map opts for convenience\n '''\n self.opts = self.opts_store.value\n\n def action(self):\n '''\n Return the functions and the returners loaded up from the loader\n module\n '''\n # if this is a *nix system AND modules_max_memory is set, lets enforce\n # a memory limit on module imports\n # this feature ONLY works on *nix like OSs (resource module doesn't work on windows)\n modules_max_memory = False\n if self.opts.get('modules_max_memory', -1) > 0 and HAS_PSUTIL and HAS_RESOURCE:\n log.debug(\n 'modules_max_memory set, enforcing a maximum of {0}'.format(\n self.opts['modules_max_memory'])\n )\n modules_max_memory = True\n old_mem_limit = resource.getrlimit(resource.RLIMIT_AS)\n rss, vms = psutil.Process(os.getpid()).get_memory_info()\n mem_limit = rss + vms + self.opts['modules_max_memory']\n resource.setrlimit(resource.RLIMIT_AS, (mem_limit, mem_limit))\n elif self.opts.get('modules_max_memory', -1) > 0:\n if not HAS_PSUTIL:\n log.error('Unable to enforce modules_max_memory because psutil is missing')\n if not HAS_RESOURCE:\n log.error('Unable to enforce modules_max_memory because resource is missing')\n\n self.opts['grains'] = salt.loader.grains(self.opts)\n self.grains.value = self.opts['grains']\n self.modules.value = salt.loader.minion_mods(self.opts)\n self.returners.value = salt.loader.returners(self.opts, self.modules.value)\n\n # we're done, reset the limits!\n if modules_max_memory is True:\n resource.setrlimit(resource.RLIMIT_AS, old_mem_limit)\n\n\nclass Schedule(ioflo.base.deeding.Deed): # pylint: disable=W0232\n '''\n Evaluates the scedule\n '''\n Ioinits = {'opts_store': '.salt.opts',\n 'grains': '.salt.grains',\n 'modules': '.salt.loader.modules',\n 'returners': '.salt.loader.returners',\n 'master_ret': '.salt.net.master_out'}\n\n def postinitio(self):\n '''\n Map opts and make the scedule object\n '''\n self.scedule = salt.utils.schedule.Schedule(\n self.opts.value,\n self.modules.value,\n self.returners.value)\n\n def action(self):\n '''\n Eval the schedule\n '''\n self.scedule.eval()\n\n\nclass FunctionNix(ioflo.base.deeding.Deed): # pylint: disable=W0232\n '''\n Execute a function call\n '''\n Ioinits = {'opts_store': '.salt.opts',\n 'grains': '.salt.grains',\n 'modules': '.salt.loader.modules',\n 'returners': '.salt.loader.returners',\n 'fun_ack': '.salt.net.fun_ack',\n 'fun_in': '.salt.net.fun_in',\n 'master_ret': '.salt.net.master_out',\n 'uxd_stack': '.salt.uxd.stack.stack',\n 'executors': '.salt.track.executors'}\n\n def postinitio(self):\n '''\n Map opts for convenience\n '''\n self.opts = self.opts_store.value\n self.matcher = salt.minion.Matcher(\n self.opts,\n self.modules.value)\n self.proc_dir = salt.minion.get_proc_dir(self.opts['cachedir'])\n self.serial = salt.payload.Serial(self.opts)\n self.executors.value = {}\n\n def _return_pub(self, ret):\n '''\n Send the return data back via the uxd socket\n '''\n ret_stack = stacking.StackUxd(\n lanename=self.opts['id'],\n yid=ret['jid'],\n dirpath=self.opts['sock_dir'])\n main_yard = yarding.Yard(\n yid=0,\n prefix=self.opts['id'],\n dirpath=self.opts['sock_dir']\n )\n ret_stack.addRemoteYard(main_yard)\n route = {'src': (self.opts['id'], ret_stack.yard.name, 'jid_ret'),\n 'dst': ('master', None, 'return')}\n msg = {'route': route, 'return': ret}\n ret_stack.transmit(msg, 'yard0')\n ret_stack.serviceAll()\n\n def action(self):\n '''\n Pull the queue for functions to execute\n '''\n if not self.fun_in.value:\n return\n exchange = self.fun_in.value.popleft()\n data = exchange.get('pub')\n # convert top raw strings - take this out once raet is using msgpack\n for key, val in data.items():\n if isinstance(val, basestring):\n data[str(key)] = str(val)\n else:\n data[str(key)] = val\n match = getattr(\n self.matcher,\n '{0}_match'.format(\n data.get('tgt_type', 'glob')\n )\n )(data['tgt'])\n if not match:\n return\n if 'user' in data:\n log.info(\n 'User {0[user]} Executing command {0[fun]} with jid '\n '{0[jid]}'.format(data))\n else:\n log.info(\n 'Executing command {0[fun]} with jid {0[jid]}'.format(data)\n )\n log.debug('Command details {0}'.format(data))\n ex_yard = yarding.Yard(\n yid=data['jid'],\n prefix=self.opts['id'],\n dirpath=self.opts['sock_dir'])\n self.uxd_stack.value.addRemoteYard(ex_yard)\n process = multiprocessing.Process(\n target=self.proc_run,\n kwargs={'exchange': exchange}\n )\n process.start() # Don't join this process! The process daemonizes\n # itself and init will clean it up\n\n def proc_run(self, exchange):\n '''\n Execute the run in a dedicated process\n '''\n data = exchange['pub']\n fn_ = os.path.join(self.proc_dir, data['jid'])\n self.opts['__ex_id'] = data['jid']\n salt.utils.daemonize_if(self.opts)\n sdata = {'pid': os.getpid()}\n sdata.update(data)\n with salt.utils.fopen(fn_, 'w+') as fp_:\n fp_.write(self.serial.dumps(sdata))\n ret = {'success': False}\n function_name = data['fun']\n if function_name in self.modules.value:\n try:\n func = self.modules.value[data['fun']]\n args, kwargs = salt.minion.parse_args_and_kwargs(func, data['arg'], data)\n sys.modules[func.__module__].__context__['retcode'] = 0\n return_data = func(*args, **kwargs)\n if isinstance(return_data, types.GeneratorType):\n ind = 0\n iret = {}\n for single in return_data:\n if isinstance(single, dict) and isinstance(iret, list):\n iret.update(single)\n else:\n if not iret:\n iret = []\n iret.append(single)\n tag = salt.utils.event.tagify(\n [data['jid'], 'prog', self.opts['id'], str(ind)],\n 'job')\n event_data = {'return': single}\n self._fire_master(event_data, tag) # Need to look into this\n ind += 1\n ret['return'] = iret\n else:\n ret['return'] = return_data\n ret['retcode'] = sys.modules[func.__module__].__context__.get(\n 'retcode',\n 0\n )\n ret['success'] = True\n except CommandNotFoundError as exc:\n msg = 'Command required for {0!r} not found'.format(\n function_name\n )\n log.debug(msg, exc_info=True)\n ret['return'] = '{0}: {1}'.format(msg, exc)\n except CommandExecutionError as exc:\n log.error(\n 'A command in {0!r} had a problem: {1}'.format(\n function_name,\n exc\n ),\n exc_info=log.isEnabledFor(logging.DEBUG)\n )\n ret['return'] = 'ERROR: {0}'.format(exc)\n except SaltInvocationError as exc:\n log.error(\n 'Problem executing {0!r}: {1}'.format(\n function_name,\n exc\n ),\n exc_info=log.isEnabledFor(logging.DEBUG)\n )\n ret['return'] = 'ERROR executing {0!r}: {1}'.format(\n function_name, exc\n )\n except TypeError as exc:\n aspec = salt.utils.get_function_argspec(\n self.modules.value[data['fun']]\n )\n msg = ('TypeError encountered executing {0}: {1}. See '\n 'debug log for more info. Possibly a missing '\n 'arguments issue: {2}').format(function_name,\n exc,\n aspec)\n log.warning(msg, exc_info=log.isEnabledFor(logging.DEBUG))\n ret['return'] = msg\n except Exception:\n msg = 'The minion function caused an exception'\n log.warning(msg, exc_info=log.isEnabledFor(logging.DEBUG))\n ret['return'] = '{0}: {1}'.format(msg, traceback.format_exc())\n else:\n ret['return'] = '{0!r} is not available.'.format(function_name)\n\n ret['jid'] = data['jid']\n ret['fun'] = data['fun']\n ret['fun_args'] = data['arg']\n self._return_pub(ret)\n if data['ret']:\n ret['id'] = self.opts['id']\n for returner in set(data['ret'].split(',')):\n try:\n self.returners.value['{0}.returner'.format(\n returner\n )](ret)\n except Exception as exc:\n log.error(\n 'The return failed for job {0} {1}'.format(\n data['jid'],\n exc\n )\n )\n","sub_path":"salt/daemons/flo/minion.py","file_name":"minion.py","file_ext":"py","file_size_in_byte":13192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"186508966","text":"#news contents crawler\n\nimport sqlite3\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\nfrom bs4 import NavigableString\nfrom urllib.parse import urlparse\nfrom urllib.parse import parse_qs\nimport httputil\nimport io\nimport chardet\nimport pprint\n\n\nconn = sqlite3.connect(\"articles.sqlite3\")\n\ncur = conn.cursor()\ncur.execute(\"SELECT * FROM article_title where (is_downloaded = 0 or is_downloaded is null)\")\n\nnext = True\nfor row in cur.fetchall():\n aid = None\n oid = None\n\n news_url = row[1]\n url_qry = None\n if '?' in row[1] :\n url_qry = parse_qs(row[1].split('?')[1])\n else :\n #parse_qs로 파싱이 안되는 경우\n try:\n params_str = str(row[1]).split('?')[1].split(\"&\")\n except IndexError as e:\n params_str = [str(row[1]).split('/')[-1] ]\n\n if not url_qry is None:\n if not url_qry.get('oid') == None:\n oid = url_qry.get('oid')[0]\n aid = url_qry.get('aid')[0]\n\n news_site = None\n dir_postfix = None\n #네이버 뉴스 링크가 아닌 경우\n if aid == None or oid == None :\n o = urlparse(row[1])\n if o.hostname == 'www.gjdream.com' :\n # 광주드림 뉴스\n news_site = \"gjdream\"\n #http://www.gjdream.com/v2/news/view.html?news_type=201&uid=480802\n dir_postfix=\"gjdream_\" + url_qry.get('news_type')[0] + \"_\" + url_qry.get('uid')[0] + \".news\"\n elif o.hostname == 'news1.kr':\n #뉴스1\n news_site = \"news1\"\n # http://news1.kr/articles/?3023732\n dir_postfix = \"news1_\" + params_str[0] + \".news\"\n elif o.hostname == 'view.asiae.co.kr' or o.hostname == 'www.asiae.co.kr' :\n #아시아경제\n news_site = \"asiae\"\n #http://view.asiae.co.kr/news/view.htm?idxno=2017061813385889015\n #http://www.asiae.co.kr/uhtml/read.jsp?idxno=181892&ion=S1N53&ion2=S2N213\n dir_postfix = news_site + \"_\" + url_qry.get('idxno')[0] + \".news\"\n\n elif o.hostname == 'news.heraldcorp.com':\n # 헤럴드경제\n news_site = \"heraldcorp\"\n # http://news.heraldcorp.com/village/view.php?ud=201706141855012313875_12\n dir_postfix = \"heraldcorp_\" + url_qry.get('ud')[0] + \".news\"\n elif o.hostname == 'www.mt.co.kr':\n # 머니투데이\n news_site = \"mt\"\n # http://www.mt.co.kr/view/mtview.php?type=1&no=2017060815500512576&outlink=1\n dir_postfix = news_site + \"_\" + url_qry.get('no')[0] + \".news\"\n\n elif o.hostname == 'www.newsis.com':\n # 뉴시스\n news_site = \"newsis\"\n # http://www.newsis.com/view/?id=NISX20170615_0000013759&cID=10812&pID=10800\n dir_postfix = news_site + \"_\" + url_qry.get('id')[0] + \".news\"\n\n elif o.hostname == 'www.edaily.co.kr':\n # 이데일리\n news_site = \"edaily\"\n # http://www.edaily.co.kr/news/newspath.asp?newsid=04391926615962048\n if not url_qry.get('newsid') == None :\n dir_postfix = news_site + \"_\" + url_qry.get('newsid')[0] + \".news\"\n #http://www.edaily.co.kr/news/related_article.edy?uid=1175703&mcd=01\n elif not url_qry.get('uid') == None:\n dir_postfix = news_site + \"_\"+ url_qry.get('uid')[0] +\"_\" + url_qry.get('mcd')[0] + \".news\"\n\n elif o.hostname == 'news.mk.co.kr':\n # 매경\n news_site = \"mk\"\n # http://news.mk.co.kr/newsRead.php?&year=2017&no=357698\n dir_postfix = news_site + \"_\" + url_qry.get('year')[0] + \"_\" + url_qry.get('no')[0] + \".news\"\n\n elif o.hostname == 'www.fnnews.com':\n # 파이낸셜뉴스\n news_site = \"fnnews\"\n # http://www.fnnews.com/news/201705312021291702\n dir_postfix = news_site + \"_\" + params_str[0] + \".news\"\n\n elif o.hostname == 'www.hankyung.com':\n # 한국경제\n news_site = \"hankyung\"\n # http://www.hankyung.com/news/app/newsview.php?aid=2017053129361\n dir_postfix = news_site + \"_\" + url_qry.get('aid')[0] + \".news\"\n\n elif o.hostname == 'www.newspim.com':\n # newspim\n news_site = \"newspim\"\n # http://www.newspim.com/sub_view.php?cate1=3&cate2=6&news_id=100534\n if not url_qry is None and not url_qry.get('cate1') is None :\n dir_postfix = news_site + \"_\" + url_qry.get('cate1')[0] +\"_\" + url_qry.get('cate2')[0] + \"_\" + url_qry.get('news_id')[0] + \".news\"\n news_url = \"http://www.newspim.com/news/view/\" + url_qry.get('news_id')[0]\n elif not url_qry is None:\n dir_postfix = news_site + \"_\" + url_qry.get('newsId')[0] + \".news\"\n news_url = \"http://www.newspim.com/news/view/\" + url_qry.get('newsId')[0]\n else:\n # http://www.newspim.com/news/view/20151211000469 형태이므로 url을 수정하지 않는다.\n dir_postfix = news_site + \"_\" + news_url.split('/')[-1] + \".news\"\n\n\n\n\n\n\n elif o.hostname == 'www.etoday.co.kr':\n # etoday\n news_site = \"etoday\"\n # http://www.etoday.co.kr/news/section/newsview.php?TM=news&SM=0404&idxno=308376\n # http://www.etoday.co.kr/news/section/newsview.php?idxno=637504\n if url_qry.get('TM') is None:\n dir_postfix = news_site + \"_\" + url_qry.get('idxno')[0] + \".news\"\n else:\n dir_postfix = news_site + \"_\" + url_qry.get('TM')[0] +\"_\" + url_qry.get('SM')[0] + \"_\" + url_qry.get('idxno')[0] + \".news\"\n\n\n elif o.hostname == 'app.yonhapnews.co.kr':\n # 연합뉴스\n news_site = \"yonhapnews\"\n # http://app.yonhapnews.co.kr/YNA/Basic/SNS/r.aspx?c=AKR20170606076600002&did=1195m\n dir_postfix = news_site + \"_\" + url_qry.get('c')[0] + \".news\"\n\n elif o.hostname == 'biz.chosun.com':\n # 비즈조선\n news_site = \"biz.chosun\"\n # http://biz.chosun.com/site/data/html_dir/2011/07/14/2011071401906.html\n dir_postfix = news_site + \"_\" + row[1].split('html_dir/')[1][:-5].replace('/','_') + \".news\"\n\n elif o.hostname == 'www.ajunews.com':\n # 아주경제\n news_site = \"ajunews\"\n # http://www.ajunews.com/view/20170618121755955\n if not url_qry is None :\n dir_postfix = news_site + \"_\" + url_qry.get(\"newsId\")[0] + \".news\"\n else:\n dir_postfix = news_site + \"_\" + row[1].split('/')[-1] + \".news\"\n\n elif o.hostname == 'www.thebell.co.kr':\n # 더벨\n news_site = \"thebell\"\n # http://www.thebell.co.kr/front/free/contents/article_view.asp?key=201309060100009530000521\n dir_postfix = news_site + \"_\" + url_qry.get(\"key\")[0] + \".news\"\n\n elif o.hostname == 'www.seoulfn.com':\n # 서울파이낸스\n news_site = \"seoulfn\"\n # http://www.seoulfn.com/news/articleView.html?idxno=39351&ion=section4\n dir_postfix = news_site + \"_\" + url_qry.get(\"idxno\")[0] + \".news\"\n\n elif o.hostname == 'www.segye.com':\n # 세계일보\n news_site = \"segye\"\n # http://www.segye.com/Service5/ShellView.asp?TreeID=1052&PCode=0007&DataID=200603011617000176\n dir_postfix = news_site + \"_\" + url_qry.get(\"idxno\")[0] + \".news\"\n\n\n else :\n print(\"Unknown news site. FATAL ERROR ===> %s\" % row[1])\n # 예외는 패스한다.\n continue\n exit(-1)\n else :\n news_site = \"naver\"\n dir_postfix = oid + \"_\" + aid + \".news\"\n\n\n # 파일을 다운로드 합시다!\n print(\"Try downloading %s\" %( dir_postfix ))\n\n # 파일을 다 읽고나서 존재여부를 체크하는것보다 로컬에서 먼저 검색하고나서 체크하는 것이 효율적인듯 하다.\n for root, dirs, files in os.walk(\"articles\"):\n for file in files:\n if str(file) == dir_postfix:\n if os.stat(str(os.path.join(root, file))).st_size > 0 : #파일 사이즈가 0보다 크면\n print(\"File is alread exists : %s \" % str(os.path.join(root, file)))\n print(\"SKIP\")\n qry = \"UPDATE article_title set is_downloaded = 1 where id = %d ;\" % row[0]\n cur.execute(qry)\n conn.commit()\n continue\n\n try:\n res = requests.get(news_url)\n except requests.exceptions.TooManyRedirects as e:\n res = None\n except requests.exceptions.ConnectionError as ce:\n print(\"Connection aborted. : %s\" % news_url)\n continue\n\n\n return_val = 1\n\n if news_site == \"naver\":\n if res.url.startswith('http://sports') : # 스포츠뉴스는 거른다.\n return_val = 2\n else:\n bs = BeautifulSoup(res.text, 'lxml')\n\n if len(bs.select(\"h2.end_tit\")) > 0 :\n # 연예면 기사의 경우 형식이 조금 다르다\n title = bs.select(\"h2.end_tit\")[0].text\n base_dtm = bs.select(\"div#content > div.end_ct > div > div.article_info > span > em\")[0].text.replace('.', '-')\n contents = bs.select(\"div#articeBody\")[0].text\n elif len(bs.select(\"#main_content > div > div > h1.error_title\")) > 0 :\n #news not found\n return_val= 3\n else :\n title = bs.select(\"h3#articleTitle\")[0].text\n base_dtm = bs.select(\"div.sponsor > span.t11\")[0].text\n contents = bs.select(\"div#articleBodyContents\")[0].text\n\n elif news_site == \"gjdream\":\n text = res.text.encode('latin-1').decode('cp949')\n bs = BeautifulSoup(text, 'html.parser')\n title = bs.select(\"table > tr > td > font\")[0].text\n base_dtm = bs.select(\"table > tr > td.f5\")[1].text.split(' : ')[1].strip()\n contents = \"\"\n\n for elmnt in bs.select(\"div#content\")[0].contents:\n if type(elmnt) == NavigableString:\n if str(elmnt).strip() != '':\n contents += str(elmnt).strip() + \"\\n\"\n\n elif news_site == \"news1\":\n bs = BeautifulSoup(res.text, 'html.parser')\n try:\n title = bs.select(\"div.title > h2\")[0].text\n lst_base_dtm = bs.select(\"div.info\")[0].contents[-1].strip().split(' ')[0:2]\n base_dtm = lst_base_dtm[0] + \" \" + lst_base_dtm[1]\n contents = \"\"\n\n for elmnt in bs.select(\"div#articles_detail\")[0].contents:\n if type(elmnt) == NavigableString:\n if str(elmnt).strip() != '':\n contents += str(elmnt).strip() + \"\\n\"\n except IndexError as e :\n if not \"http404\" in bs.select(\"img#img\")[0].attrs[\"src\"]:\n #page not found\n continue\n\n\n elif news_site == 'asiae':\n if res.text.startswith('\n next_url = bs.contents[0].text.split('\"')[1]\n res = requests.get(next_url)\n text = res.text.encode('latin-1').decode('cp949')\n bs = BeautifulSoup(text, 'html.parser')\n title = bs.select(\"div#article > h1\")[0].text\n try:\n base_dtm = bs.select(\"span.date\")[0].text.replace('.','-')\n except IndexError as e2:\n base_dtm = bs.select(\"span.num\")[0].text[2:].replace('.','-')\n contents = bs.select(\"div#textBody\")[0].text\n\n\n elif news_site == 'newsis':\n text = res.text\n bs = BeautifulSoup(text, 'html.parser')\n try:\n title = bs.select(\"div.article_tbx > h1\")[0].text\n\n base_dtm = bs.select(\"div.date\")[0].text[3:]\n contents = bs.select(\"div.article_bx > div.view_text > div#textBody\")[0].text\n except IndexError as e :\n if \"GISA FILE NOT EXISTS\" in bs.select(\"p.mgt18\")[0].text:\n #기사가 삭제됨\n print(\"Article was deleted.\")\n continue\n\n elif news_site == 'edaily':\n text = res.text.encode('latin-1').decode('cp949')\n bs = BeautifulSoup(text, 'html.parser')\n if bs.select('div#viewarea > h4'):\n title = bs.select(\"div#viewarea > h4\")[0].text\n\n base_dtm = bs.select(\"div#viewarea > div.pr > p.newsdate\")[0].text.split('|')[1].replace('.','-').strip()\n contents = bs.select(\"span#viewcontent_inner\")[0].text.encode('utf-8','ignore').decode('utf-8') #깨진문자가 있다면 이과정에서 무시된다.\n elif len(bs.select(\"div.left > p > a > img\")) > 0:\n # 사진 기사\n \"\"\"\"\"\"\n return_val =2\n elif len(bs.select('h4.newstitle')) > 0 :\n title = bs.select(\"h4.newstitle\")[0].text\n\n base_dtm = bs.select(\"p.newsdate\")[0].text.split('|')[1].replace('.','-').strip()\n contents = bs.select(\"span#viewcontent_inner\")[0].text\n\n\n elif news_site == 'mk':\n text = res.text.encode('latin-1').decode('cp949')\n bs = BeautifulSoup(text, 'html.parser')\n title = bs.select(\"div#top_header > div > div > h1\")[0].text\n\n base_dtm = bs.select(\"div#top_header > div > div > div.news_title_author > ul > li.lasttime\")[0].text.split(' :')[1].strip().replace('.','-')\n contents = bs.select(\"div#article_body\")[0].text\n\n elif news_site == 'fnnews':# finanncial news\n text = res.text\n bs = BeautifulSoup(text, 'html.parser')\n title = bs.select(\"div#container > div > div.article_head > h1\")[0].text\n\n base_dtm = bs.select(\"div#container > div > div.article_head > div > em\")[1].text.split(' : ')[1].replace('.','-')\n contents = bs.select(\"div#article_content > div\")[0].text\n\n elif news_site == 'hankyung':# 한국경제\n # 얘네는 응답이 chunked reponse로 온다.\n # 이경우\n # [byte수]\\r\\n\n # 데이터\n # \\r\\n[byte수]\\r\\n\n # 데이터\n # 반복...\n # \\r\\n0\\r\\n\\r\\n\n\n type = None\n if res.text.startswith(' div.artlcle_top > h2.tit')[0].text\n\n base_dtm = bs.select('div#container > div.wrap_container > div > div.info_article > div.date > span')[0].text[3:]\n contents = bs.select('div#newsView')[0].text\n\n elif type == 'hei':\n title = bs.select('div#container > section > h1')[0].text\n base_dtm = bs.select('div#container > section > div > div.atc-info > span')[0].text[3:]\n\n contents = bs.select('article#newsView')[0].text\n elif type == 'plus':\n title = bs.select('section#container > section.service_cnt > article > article > header > h2')[0].text\n base_dtm = bs.select('section#container > section.service_cnt > article > article > p.info > span')[1].text\n\n contents = bs.select('div.articleContent')[0].text\n\n elif news_site == 'newspim':# newspim\n if not res is None :\n text = res.text\n\n if '/anda/view' in text:\n return_val = 2 # no need to download, premium news\n elif \"document.location.href='/';\" in text:\n return_val = 2 # article is not exists\n else :\n bs = BeautifulSoup(text, 'html.parser')\n title = bs.select(\"div.bodynews_title > h1\")[0].text\n\n base_dtm = bs.select(\"div.bodynews_title > ul > li.writetime\")[0].text.split(' : ')[1].replace('년','-').replace('월','-').replace('일','')\n contents = bs.select(\"div#news_contents\")[0].text\n else:\n # 404 not found\n return_val = 3\n\n elif news_site == 'etoday':# etoday\n text = res.text\n if '��스가 존재하지 않습니다' in text:\n return_val = 3\n else:\n try:\n bs = BeautifulSoup(text, 'lxml')\n title = bs.select(\"#article_title\")[0].text\n\n base_dtm = bs.select(\"#ViewHeader > div.byline > em\")[0].text.split(' : ')[1]\n if len(bs.select(\"#newsContent\")) > 0 :\n contents = bs.select(\"#newsContent\")[0].text.strip()\n else:\n contents = bs.select(\"#block_body > div > div > div.cont_left_article\")[0].text.strip()\n except:\n # 일단 패스\n continue\n\n elif news_site == 'yonhapnews':#yonhapnews\n if '/photos/' in res.url: #사진 기사일경우 스크랩하지 않는다.\n return_val = 2\n else:\n text = res.content.decode()\n bs = BeautifulSoup(text, 'html.parser')\n title = bs.select(\"#articleWrap > h1\")[0].text\n\n base_dtm = bs.select(\"div.share-info > span > em\")[0].text.replace('/','-')\n contents = bs.select(\"#articleWrap > div.article\")[0].text\n\n elif news_site == 'biz.chosun':# biz chosun\n if res.text.startswith('\n next_url = res.text.split('url=')[1][:-3]\n res = requests.get(next_url)\n text =res.content.decode()\n bs = BeautifulSoup(text, 'html.parser')\n title = bs.select(\"#title_text\")[0].text\n\n base_dtm = bs.select(\"span.date_text\")[0].text.split(' : ')[1].strip().replace('.','-')\n contents = bs.select(\"#par\")[0].text\n\n else :\n text =res.content.decode()\n bs = BeautifulSoup(text, 'html.parser')\n\n if bs.select('head > title')[0].text == '404 Not Found':\n return_val = 3\n\n else:\n title = bs.select(\"#title_text\")[0].text\n base_dtm = bs.select(\"#date_text\")[0].text.split(' : ')[1].strip().replace('.','-')\n contents = bs.select(\"#article_2011\")[0].text\n\n elif news_site == 'ajunews': # ajunews\n text = res.text\n bs = BeautifulSoup(text, 'html.parser')\n\n if len(bs.select('body > div > div.etc-body > div.etc-url-error-desc > div')) > 0 :\n # 페이지를 찾을 수 없음\n return_val = 3\n else:\n try:\n title = bs.select(\"div.ma680-0001-head-block > h2\")[0].text.strip()\n base_dtm = bs.select(\"li.regi_date.cus\")[0].text.split(' : ')[1]\n if len(bs.select(\"#articleBody > div\")) > 0 :\n contents = bs.select(\"#articleBody > div\")[0].text.strip()\n elif len(bs.select(\"#articleBody\")) > 0 :\n contents = bs.select(\"#articleBody\")[0].text.strip()\n except :\n continue\n\n elif news_site == 'thebell':\n # http://www.thebell.co.kr/front/free/contents/news/article_view.asp?svccode=&page=1&sort=thebell_check_time&key=201309060100009530000521\n next_url = 'http://www.thebell.co.kr/front/free/contents/news/article_view.asp?svccode=&page=1&sort=thebell_check_time&key=' + url_qry.get('key')[0]\n res = requests.get(next_url)\n\n text = res.text\n bs = BeautifulSoup(text, 'html.parser')\n if len( bs.select(\"#article_main > span > b\")) > 0 and '유료' in bs.select(\"#article_main > span > b\")[0].text:\n return_val = 3 # no need to downlaod\n else:\n title = bs.select(\"li.title > h1\")[0].text.strip()\n base_dtm = bs.select(\"div.title_bar > ul > li.left\")[0].text.split('공개 ')[-1]\n contents = bs.select(\"#article_main\")[0].text.strip()\n\n elif news_site == 'seoulfn':\n # http://www.seoulfn.com/news/articleView.html?idxno=39351&ion=section4\n text = res.text.encode('latin-1').decode('cp949')\n bs = BeautifulSoup(text, 'html.parser')\n if len(bs.select(\"td > b\"))>0 and bs.select(\"td > b\")[0].text.startswith('존재하지') :\n return_val = 3\n elif len(bs.select(\"div.phtit\")) > 0 :\n #photo news\n return_val = 2\n else:\n title = bs.select(\"#font_title\")[0].text.strip()\n base_dtm = bs.select(\"#font_date > span\")[0].text.strip()[:20].replace(' ',' ')#space 아님\n contents = bs.select(\"#CmAdContent\")[0].text.strip()\n\n\n else:\n print(\"Unknown news site. FATAL ERROR\")\n exit(-1)\n\n if return_val == 1:\n sub_dir = base_dtm[0:4]\n if not os.path.isdir(\"articles/\" + sub_dir):\n os.mkdir(\"articles/\" + sub_dir)\n dest_file = \"articles/\" + sub_dir + \"/\" + dir_postfix\n\n if not os.path.isfile(dest_file) or ( os.path.isfile(dest_file) and os.stat(dest_file).st_size == 0 ):\n f = open(dest_file,'w',encoding=\"utf-8\")\n f.write(title+\"\\n\"+ base_dtm+\"\\n\"+ contents)\n f.close()\n\n # is_downloaeded\n # 0: not downloaded\n # 1: downloaeded\n # 2: not need to download\n # 3: 404 not found\n qry = \"UPDATE article_title set is_downloaded = %d where id = %d ;\" % (return_val, row[0])\n cur.execute(qry)\n conn.commit()\n else:\n # is_downloaeded\n # 0: not downloaded\n # 1: downloaeded\n # 2: not need to download\n # 3: 404 not found\n qry = \"UPDATE article_title set is_downloaded = %d where id = %d ;\" % (return_val, row[0])\n cur.execute(qry)\n conn.commit()\n\n\n\n\n\n\n\n","sub_path":"2_ncc.py","file_name":"2_ncc.py","file_ext":"py","file_size_in_byte":24192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"60165319","text":"from datetime import datetime\n\nfrom django.conf import settings\nfrom django.core.files.storage import default_storage\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import generics, status\nfrom rest_framework.decorators import action, detail_route, permission_classes,list_route\nfrom rest_framework.generics import GenericAPIView\nfrom rest_framework.mixins import UpdateModelMixin\nfrom rest_framework.pagination import LimitOffsetPagination\nfrom rest_framework.parsers import FormParser, JSONParser, MultiPartParser\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ModelViewSet\n\nfrom mrelife.commons.common_fnc import CommonFuntion\nfrom mrelife.events.models import Event, EventModelHouse\nfrom mrelife.modelhouses.models import (\n ModelHouse,\n ModelHouseMedia,\n ModelHouseOutletStore,\n ModelHouseTag,\n ModelHouseUser,\n OrderModelHouse\n)\nfrom mrelife.modelhouses.serializers import (\n ModelHouseNestedSerializer,\n ModelHouseSerializer,\n OrderModelHouseSerializer,\n OrderModelHouseStatusSerializer\n)\nfrom mrelife.outletstores.models import OutletStore\nfrom mrelife.tags.models import Tag\nfrom mrelife.utils.groups import GroupUser, IsAdmin, IsStore, IsSub\nfrom mrelife.utils.model_house_permission import ModelHousePermission\nfrom mrelife.utils.order_model_house_permission import OrderMHUserListPermission, OrderMHViewadminPermission\nfrom mrelife.utils.querys import get_or_none\nfrom mrelife.utils.relifeenum import MessageCode\n\n\nclass ModelHouseViewSet(ModelViewSet):\n queryset = ModelHouse.objects.all()\n serializer_class = ModelHouseSerializer\n permission_classes = (IsAuthenticated, ModelHousePermission,)\n parser_class = (FormParser, MultiPartParser, JSONParser)\n pagination_class = LimitOffsetPagination\n\n def create(self, request, *args, **kwargs):\n \"\"\"\n POST:\n store: int\n events: []\n tags: []\n medias: []\n \"\"\"\n request.data['create_user'] = request.user.id\n obj = super(ModelHouseViewSet, self).create(request, *args, **kwargs)\n house = ModelHouse.objects.get(pk=obj.data['id'])\n if not (IsStore(request.user) or IsSub(request.user)):\n try:\n store = OutletStore.objects.get(pk=int(request.data.get('store')))\n except Exception:\n store = None\n else:\n store = request.user.store\n ModelHouseUser.objects.create(user_id=request.user.id, model_house=house)\n\n if store is None:\n house.delete()\n return Response({\n 'status': False,\n 'messageCode': 'MH001',\n 'messageParams': {},\n 'data': {}\n }, status=status.HTTP_404_NOT_FOUND)\n\n events = request.data.get('events')\n if events is not None:\n for event in events:\n try:\n EventModelHouse.objects.create(event_id=event, model_house=house)\n except Exception:\n pass\n\n tags = request.data.get('tags')\n if tags is not None:\n for tag_name in tags:\n if not (tag_name == '' or tag_name is None):\n tag, created = Tag.objects.get_or_create(name=tag_name)\n ModelHouseTag.objects.create(tag=tag, model_house=house)\n\n ModelHouseOutletStore.objects.create(outlet_store=store, model_house=house)\n\n medias = request.data.getlist('medias')\n count = 0\n for media in medias:\n if count < 5:\n file = default_storage.save(media.name, media)\n ModelHouseMedia.objects.create(model_house=house, url=settings.MEDIA_URL + file)\n count += 1\n return obj\n\n def retrieve(self, request, *args, **kwargs):\n self.serializer_class = ModelHouseNestedSerializer\n return super(ModelHouseViewSet, self).retrieve(request, *args, **kwargs)\n\n def update(self, request, *args, **kwargs):\n obj = super(ModelHouseViewSet, self).update(request, *args, **kwargs)\n return obj\n\n @detail_route(methods=['post'])\n def add_event(self, request, *args, **kwargs):\n \"\"\"\n POST:\n events: []\n \"\"\"\n house = ModelHouse.objects.get(pk=kwargs['pk'])\n events = request.data.get('events')\n if events is not None:\n for event in events:\n try:\n if not house.events.filter(event_id=event).exists():\n EventModelHouse.objects.create(event_id=event, model_house=house)\n except Exception:\n pass\n return super(ModelHouseViewSet, self).retrieve(request, *args, **kwargs)\n\n @detail_route(methods=['post'])\n def remove_event(self, request, *args, **kwargs):\n \"\"\"\n POST:\n events: []\n \"\"\"\n house = ModelHouse.objects.get(pk=kwargs['pk'])\n events = request.data.get('events')\n if events is not None:\n for event in events:\n try:\n _event = EventModelHouse.objects.filter(event_id=event, model_house=house)\n _event.delete()\n except Exception:\n pass\n return super(ModelHouseViewSet, self).retrieve(request, *args, **kwargs)\n\n @detail_route(methods=['post'])\n def add_tag(self, request, *args, **kwargs):\n \"\"\"\n POST:\n tags: []\n \"\"\"\n house = ModelHouse.objects.get(pk=kwargs['pk'])\n tags = request.data.get('tags')\n if tags is not None:\n for tag_name in tags:\n if not (tag_name == '' or tag_name is None):\n tag, created = Tag.objects.get_or_create(name=tag_name)\n if created or not house.tags.filter(tag=tag).exists():\n ModelHouseTag.objects.create(tag=tag, model_house=house)\n return super(ModelHouseViewSet, self).retrieve(request, *args, **kwargs)\n\n @detail_route(methods=['post'])\n def remove_tag(self, request, *args, **kwargs):\n \"\"\"\n POST:\n tags: []\n \"\"\"\n house = ModelHouse.objects.get(pk=kwargs['pk'])\n tags = request.data.get('tags')\n if tags is not None:\n for tag in tags:\n try:\n _tag = ModelHouseTag.objects.filter(tag_id=tag, model_house=house)\n _tag.delete()\n except Exception:\n pass\n return super(ModelHouseViewSet, self).retrieve(request, *args, **kwargs)\n\n @detail_route(methods=['post'])\n def add_media(self, request, *args, **kwargs):\n \"\"\"\n POST:\n medias: []\n \"\"\"\n house = ModelHouse.objects.get(pk=kwargs['pk'])\n medias = request.data.getlist('medias')\n count = 0\n for media in medias:\n if count < 5:\n file = default_storage.save(media.name, media)\n ModelHouseMedia.objects.create(model_house=house, url=settings.MEDIA_URL + file)\n count += 1\n return super(ModelHouseViewSet, self).retrieve(request, *args, **kwargs)\n\n @detail_route(methods=['post'])\n def remove_media(self, request, *args, **kwargs):\n \"\"\"\n POST:\n medias: []\n \"\"\"\n house = ModelHouse.objects.get(pk=kwargs['pk'])\n medias = request.data.get('medias')\n if medias is not None:\n for media in medias:\n try:\n _media = ModelHouseMedia.objects.get(pk=media)\n _media.delete()\n except Exception:\n pass\n return super(ModelHouseViewSet, self).retrieve(request, *args, **kwargs)\n\n @detail_route(methods=['post'])\n def add_user(self, request, *args, **kwargs):\n \"\"\"\n GET:\n POST:\n \"\"\"\n house = ModelHouse.objects.get(pk=kwargs['pk'])\n users = request.data.get('users')\n if users is not None:\n for user in users:\n try:\n if not house.users.filter(user_id=user).exists():\n ModelHouseUser.objects.create(user_id=request.user.id, model_house=house)\n except Exception:\n pass\n return super(ModelHouseViewSet, self).retrieve(request, *args, **kwargs)\n\n @detail_route(methods=['post'])\n def remove_user(self, request, *args, **kwargs):\n \"\"\"\n POST:\n users: [int]\n \"\"\"\n house = ModelHouse.objects.get(pk=kwargs['pk'])\n users = request.data.get('users')\n if users is not None:\n for user in users:\n try:\n _user = ModelHouseUser.objects.filter(user_id=user, model_house=house)\n _user.delete()\n except Exception:\n pass\n return super(ModelHouseViewSet, self).retrieve(request, *args, **kwargs)\n\n\nclass OrderModelHouseViewSet(ModelViewSet):\n queryset = OrderModelHouse.objects.all().filter(is_active=1)\n serializer_class = OrderModelHouseSerializer\n pagination_class = LimitOffsetPagination\n permission_classes = (IsAuthenticated, OrderMHViewadminPermission,)\n\n \n def list(self, request):\n self.queryset = OrderModelHouse.objects.filter(is_active=1)\n return super(OrderModelHouseViewSet, self).list(request)\n \n\n \n def retrieve(self, request, pk=None):\n try:\n queryset = OrderModelHouse.objects.all().filter(is_active=1)\n orderModelObject = get_object_or_404(queryset, pk=pk)\n serializer = OrderModelHouseSerializer(orderModelObject)\n return Response(CommonFuntion.resultResponse(True, serializer.data, MessageCode.OMH002.value, \"\"), status=status.HTTP_200_OK)\n except Exception as e:\n return Response(CommonFuntion.resultResponse(False, \"\", MessageCode.OMH003.value, \"\"), status=status.HTTP_404_NOT_FOUND)\n\n \n def create(self, request):\n request.data['create_user_id'] = request.user.id\n serializer = OrderModelHouseSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save(is_active=settings.IS_ACTIVE, created=datetime.now(), updated=datetime.now())\n return Response(CommonFuntion.resultResponse(True, serializer.data, MessageCode.OMH004.value, \"\"), status=status.HTTP_201_CREATED)\n return Response(CommonFuntion.resultResponse(False, \"\", MessageCode.OMH005.value, serializer.errors), status=status.HTTP_400_BAD_REQUEST)\n\n \n def update(self, request, pk=None):\n try:\n request.data['create_user_id'] = request.user.id\n queryset = OrderModelHouse.objects.all().filter(is_active=1)\n orderModelObject = get_object_or_404(queryset, pk=pk)\n serializer = OrderModelHouseSerializer(orderModelObject, data=request.data)\n if serializer.is_valid():\n serializer.save(is_active=settings.IS_ACTIVE, created=datetime.now(), updated=datetime.now())\n return Response(CommonFuntion.resultResponse(True, serializer.data, MessageCode.OMH006.value, \"\"), status=status.HTTP_200_OK)\n return Response(CommonFuntion.resultResponse(False, \"\", MessageCode.OMH007.value, serializer.errors), status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n return Response(CommonFuntion.resultResponse(False, \"\", MessageCode.OMH007.value, \"\"), status=status.HTTP_404_NOT_FOUND)\n\n \n def destroy(self, request, pk=None):\n try:\n queryset = OrderModelHouse.objects.all().filter(is_active=1)\n orderModelObject = get_object_or_404(queryset, pk=pk)\n data = {\"is_active\": settings.IS_INACTIVE}\n serializer = OrderModelHouseSerializer(orderModelObject, data=data, partial=True)\n if serializer.is_valid():\n serializer.save(updated=datetime.now())\n return Response(CommonFuntion.resultResponse(True, serializer.data, MessageCode.OMH008.value, \"\"), status=status.HTTP_200_NO_CONTENT)\n return Response(CommonFuntion.resultResponse(False, \"\", MessageCode.OMH009.value, serializer.errors), status=status.HTTP_404_BAD_REQUEST)\n except Exception as e:\n return Response(CommonFuntion.resultResponse(False, \"\", MessageCode.OMH007.value, \"\"), status=status.HTTP_404_NOT_FOUND)\n\n @list_route(methods=['get']) \n def selfGetlistBooking(self, request, pk=None):\n queryset = OrderModelHouse.objects.all().filter(is_active=1).filter(create_user_id=request.user.id)\n return super(OrderModelHouseViewSet, self).list(request)\nclass updateStatus(GenericAPIView, UpdateModelMixin):\n queryset = OrderModelHouse.objects.all()\n serializer_class = OrderModelHouseStatusSerializer\n permission_classes = (IsAuthenticated,)\n\n def put(self, request, pk=None, *args, **kwargs):\n try:\n request.data['create_user_id'] = request.user.id\n queryset = OrderModelHouse.objects.all().filter(is_active=1)\n orderModelObject = get_object_or_404(queryset, pk=pk)\n serializer = OrderModelHouseSerializer(orderModelObject, data=request.data, partial=True)\n if serializer.is_valid():\n serializer.save(is_active=settings.IS_ACTIVE, created=datetime.now(), updated=datetime.now())\n return Response(CommonFuntion.resultResponse(True, serializer.data, MessageCode.OMH006.value, \"\"), status=status.HTTP_200_OK)\n return Response(CommonFuntion.resultResponse(False, \"\", MessageCode.OMH007.value, serializer.errors), status=status.HTTP_400_BAD_REQUEST)\n except Exception as e:\n return Response(CommonFuntion.resultResponse(False, \"\", MessageCode.OMH007.value, \"\"), status=status.HTTP_404_NOT_FOUND)\n","sub_path":"service/mrelife/modelhouses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"650382547","text":"from nmtpytorch.layers.transformers.cross_modal_encoder import CrossModalEncoder\nfrom nmtpytorch.models import SimultaneousTFNMT\n\n\nclass EncoderCrossMMSimultaneousTFNMT(SimultaneousTFNMT):\n\n def __init__(self, opts):\n super().__init__(opts)\n assert not self.opts.model['enc_bidirectional'], \\\n 'Bidirectional TF encoder is not currently supported for simultaneous MT.'\n\n def set_defaults(self):\n super().set_defaults()\n self.defaults.update({\n # Decoding/training simultaneous NMT args\n 'enc_fusion': 'sum', # The encoder fusion type.Can be: 'sum' or 'gate'. Default 'sum'.\n 'enc_fusion_lnorm': True, # Whether to apply layer normalization after fusing the encoder.\n 'mm_attn_heads': 8, # The number of multimodal attention heads.\n 'enc_fusion_dropout': 0.0, # The amount of dropout after the fusion.\n })\n\n def _create_image_encoder(self):\n return CrossModalEncoder(\n input_size=self.opts.model['aux_dim'],\n proj_dim=self.opts.model['aux_proj_dim'],\n proj_activ=self.opts.model['aux_proj_activ'],\n layer_norm=self.opts.model['aux_lnorm'],\n l2_norm=self.opts.model['aux_l2norm'],\n dropout=self.opts.model['aux_dropout'],\n feat_mode=self.opts.model['feat_mode'],\n model_dim=self.opts.model['model_dim'],\n mm_attn_heads=self.opts.model['mm_attn_heads'],\n attn_dropout=self.opts.model['attn_dropout'],\n fusion=self.opts.model['enc_fusion'],\n fusion_lnorm=self.opts.model['enc_fusion_lnorm'],\n fusion_dropout=self.opts.model['enc_fusion_dropout'],\n boxes_dim=self.opts.model['img_boxes_dim']\n )\n\n def get_attention_weights(self):\n return {'encoder_src': self.encoders['src'].get_attention_weights(),\n 'encoder_img': self.encoders['image'].get_attention_weights(),\n 'decoder': self.dec.get_attention_weights()}\n\n def cache_enc_states(self, batch, **kwargs):\n \"\"\"\n Caches the encoder hidden states, by first computing the textual hidden states, and then combining them with the\n visual encoder using the cross modal encoder.\n :param batch: The batch.\n :param kwargs: Any additional args.\n \"\"\"\n enc_txt = self.encoders['src'](batch['src'])\n _ = self.encoders['image'](batch['image'], enc_txt=enc_txt)\n\n def get_enc_state_dict(self, up_to=int(1e6)):\n \"\"\"\n Get the encoder states. In the cross modal case retrive the ones from the cross modal image encoder, as they\n also contain the textual encoder hidden states.\n :param up_to: The amount of timesteps to return.\n :return: The encoder states up to a certain timestep.\n \"\"\"\n return {'src': self.encoders['image'].get_states(up_to=up_to)}\n","sub_path":"nmtpytorch/models/snmt_tf_enc_cmm.py","file_name":"snmt_tf_enc_cmm.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"5219389","text":"# -*- coding: utf-8 -*\r\nfrom util import validate_date_str\r\nimport tornado.web\r\nfrom datetime import datetime, timedelta\r\nimport json\r\n\r\nclass UpdateBalanceHandler(tornado.web.RequestHandler):\r\n @property\r\n def logger(self):\r\n return self.application.logger\r\n\r\n @property\r\n def mysql_db(self):\r\n return self.application.mysql_db\r\n\r\n @property\r\n def redis_client(self):\r\n return self.application.redis_client\r\n\r\n def stats_curday_balance(self, uid, start_tme, end_time):\r\n data = {\"order_balance\": None, \"cancel_balance\": None, \"updateTime\": None}\r\n\r\n sql = \"select sum(ticketPrices),updateTime from order_ticket where uid='%s' \\\r\n and status=1 and updateTime>='%s' and updateTime<'%s'\" % (uid, start_tme, end_time)\r\n qs, err = self.mysql_db.execute_query_sql(sql)\r\n if err is not None:\r\n return data, err\r\n\r\n self.logger.info(\"order balance: %s\" % str(qs))\r\n if qs is None or len(qs) == 0:\r\n return data, None\r\n\r\n data[\"order_balance\"] = qs[0][0]\r\n data[\"updateTime\"] = qs[0][1].strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\n sql = \"select sum(ticketPrices),updateTime from order_cancel where uid='%s' \\\r\n and cancelStatus=1 and updateTime>='%s' and updateTime<'%s'\" % (uid, start_tme, end_time)\r\n qs, err = self.mysql_db.execute_query_sql(sql)\r\n if err is not None:\r\n return data, err\r\n\r\n self.logger.info(\"cancel balance: %s\" % str(qs))\r\n if qs is None or len(qs) == 0:\r\n return data, None\r\n\r\n data[\"cancel_balance\"] = qs[0][0]\r\n data[\"updateTime\"] = qs[0][1].strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\n return data, None\r\n\r\n def cmp_update_time(self, update_time, start_time, end_time):\r\n s_time = datetime.strptime(update_time.strftime(\"%Y-%m-%d\"), \"%Y-%m-%d\")\r\n stime = datetime.strptime(start_time.split(\" \")[0], \"%Y-%m-%d\")\r\n etime = datetime.strptime(end_time.split(\" \")[0], \"%Y-%m-%d\")\r\n\r\n self.logger.info(\"s_time:%s stime: %s etime:%s\" % (s_time, stime, etime))\r\n if s_time >= stime or s_time >= etime:\r\n return True\r\n return False\r\n\r\n def valid_reqeust_time(self, start_time, end_time):\r\n if validate_date_str(start_time, \"%Y-%m-%d %H:%M:%S\") == False or \\\r\n validate_date_str(end_time, \"%Y-%m-%d %H:%M:%S\") == False:\r\n return True\r\n\r\n c1 = datetime.strptime(start_time, \"%Y-%m-%d %H:%M:%S\")\r\n c2 = datetime.strptime(end_time, \"%Y-%m-%d %H:%M:%S\")\r\n\r\n self.logger.info(\"c1:%s c2:%s\" % (c1, c2))\r\n if c1 + timedelta(days=1) < c2 or c1 > c2:\r\n return True\r\n return False\r\n\r\n def get(self):\r\n self.logger.info(\"%s%s?%s\" % (self.request.host, self.request.path, self.request.query))\r\n\r\n uid = self.get_argument(\"uid\", default=None, strip=True)\r\n start_time = self.get_argument(\"start_time\", default=None, strip=True)\r\n end_time = self.get_argument(\"end_time\", default=None, strip=True)\r\n\r\n self.set_header(\"Content-Type\", \"application/json;charset=UTF-8\")\r\n if uid is None or start_time is None or end_time is None:\r\n self.write({\"errcode\": -1, \"errmsg\": r\"时间参数错误\", \"data\": {}})\r\n self.finish()\r\n return\r\n\r\n if self.valid_reqeust_time(start_time, end_time):\r\n self.logger.error(r\"时间参数越界\")\r\n self.write({\"errcode\": -1, \"errmsg\": r\"时间参数越界\", \"data\": {}})\r\n self.finish()\r\n return\r\n\r\n sql = \"select totalBalance,updateTime from account_balance where uid='%s' order by updateTime desc limit 1\" % uid\r\n qs, err = self.mysql_db.execute_query_sql(sql)\r\n if err is not None:\r\n self.write({\"errcode\": -1, \"errmsg\": str(err), \"data\": {}})\r\n self.finish()\r\n return\r\n\r\n if qs is None or len(qs) == 0:\r\n self.write({\"errcode\": -1, \"errmsg\": r\"非法uid\", \"data\": {}})\r\n self.finish()\r\n return\r\n\r\n total_balance = qs[0][0]\r\n update_time = qs[0][1]\r\n\r\n self.logger.info(\"total balance: %s update_time:%s\" % (total_balance, update_time))\r\n if self.cmp_update_time(update_time, start_time ,end_time) == True:\r\n self.logger.info(r\"己经更新过余额\")\r\n self.write({\"errcode\": 0, \"errmsg\": r\"己经更新过余额\", \"data\": {}})\r\n self.finish()\r\n return\r\n\r\n data, err = self.stats_curday_balance(uid, start_time, end_time)\r\n if err is not None:\r\n self.logger.info(err)\r\n self.write({\"errcode\": -1, \"errmsg\": str(err), \"data\": {}})\r\n self.finish()\r\n return\r\n\r\n self.logger.info(\"query balance: %s\" % json.dumps(data))\r\n if data[\"order_balance\"] is None and data[\"cancel_balance\"] is None:\r\n self.logger.info(\"%s-%s无交易余额\" % (start_tme, end_time))\r\n self.write({\"errcode\": 0, \"errmsg\": \"%s-%s无交易余额\" % (start_tme, end_time), \"data\": {}})\r\n self.finish()\r\n return\r\n\r\n trans_balance = 0.0\r\n if data[\"order_balance\"] is not None:\r\n trans_balance = float(data[\"order_balance\"])\r\n\r\n if data[\"cancel_balance\"] is not None:\r\n trans_balance = trans_balance - float(data[\"cancel_balance\"])\r\n\r\n balance = total_balance - trans_balance\r\n self.logger.info(\"total_balance: %f trans_balance: %f balance: %f\" % (total_balance, trans_balance, balance))\r\n hdata = {\r\n \"totalBalance\": balance,\r\n \"lastTransMoney\": trans_balance,\r\n \"uid\": uid,\r\n \"updateTime\": datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\r\n \"statsTime\": data[\"updateTime\"],\r\n \"operator\": 1\r\n }\r\n\r\n self.logger.info(\"hdata: %s\" % json.dumps(hdata))\r\n\r\n if self.redis_client.hset(\"ticket-uid\", uid, balance) == False:\r\n self.logger.info(r\"更新交易余额失败\")\r\n self.write({\"errcode\": -1, \"errmsg\": r\"更新交易余额失败\", \"data\": hdata})\r\n self.finish()\r\n return\r\n\r\n if self.redis_client.set(\"ticket_balance_uid_%s\" % uid, balance) is None:\r\n self.logger.info(r\"更新缓存余额失败\")\r\n self.write({\"errcode\": -1, \"errmsg\": r\"更新缓存余额失败\", \"data\": hdata})\r\n self.finish()\r\n return\r\n\r\n if self.mysql_db.insert(\"account_balance\", hdata) is not None:\r\n self.logger.info(r\"更新余额失败\")\r\n self.write({\"errcode\": -1, \"errmsg\": r\"更新余额失败\", \"data\": hdata})\r\n self.finish()\r\n return\r\n\r\n if balance < 0.0:\r\n self.logger.info(r\"余额不足\")\r\n self.write({\"errcode\": 0, \"errmsg\": r\"余额不足\", \"data\": hdata})\r\n else:\r\n self.logger.info(r\"交易正常\")\r\n self.write({\"errcode\": 0, \"errmsg\": r\"交易正常\", \"data\": hdata})\r\n self.finish()\r\n\r\n self.logger.info(\"=====================end\")\r\n","sub_path":"3rd_party/nginx.bak/home/work/ticket_server/admin_update_balance.py","file_name":"admin_update_balance.py","file_ext":"py","file_size_in_byte":7202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"573994953","text":"import re\n\nimport lxml\nfrom selenium import webdriver\n\nlink_url = \"https://www.baidu.com/bh/dict/ydxx_8158835209873076610?tab=%E6%A6%82%E8%BF%B0&title=%E8%82%9D%E7%99%8C&contentid=ydxx_8158835209873076610&query=%E8%82%9D%E7%99%8C&sf_ref=dict_home&from=dicta\"\n\ndriver = webdriver.Chrome()\ndriver.maximize_window()\ndriver.get(link_url)\n\n# 获取页面源代码\nhtml_source = driver.page_source\n# 重点\nhtml = lxml.html.fromstring(html_source)\n# 获取标签下所有文本\nitems = html.xpath(\"//div[@id='y_prodsingle']//text()\")\n# 正则 匹配以下内容 \\s+ 首空格 \\s+$ 尾空格 \\n 换行\npattern = re.compile(\"^\\s+|\\s+$|\\n\")\n\nclause_text = \"\"\nfor item in items:\n # 将匹配到的内容用空替换,即去除匹配的内容,只留下文本\n line = re.sub(pattern, \"\", item)\n if len(line) > 0:\n clause_text += line + \"\\n\"\n#\n#\nprint(clause_text)","sub_path":"爬虫/selenium爬虫.py","file_name":"selenium爬虫.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"57358318","text":"# https://towardsdatascience.com/15-things-you-should-know-about-dictionaries-in-python-44c55e75405c\n''' 1. What is a Python dictionary?\nA dictionary is an unordered and mutable Python container that stores mappings of unique keys to values. Dictionaries are written with curly brackets ({}), including key-value pairs separated by commas (,). A colon (:) separates each key from its value.\nThree dictionaries are shown below, containing the population of the 5 largest German cities, list of products, and student’s grades.\n'''\n# dictionary containing the population of the 5 largest german cities\npopulation = {'Berlin': 3748148, 'Hamburg': 1822445, 'Munich': 1471508, 'Cologne': 1085664, 'Frankfurt': 753056 }\n\n# dictionary containing a list of products' prices\nproducts = {'table': 120, 'chair': 40, 'lamp': 14, 'bed': 250, 'mattress': 100}\n\n# dictionary containing students grades\ngrades = {'Alba': 9.5, 'Eduardo': 10, 'Normando': 3.5, 'Helena': 6.5, 'Claudia': 7.5}\n\n'''\n2. Create a dictionary with dict() constructor\nDictionaries can also be created with the built-in function dict(**kwarg). This function takes an arbitrary number of keywords arguments (arguments preceded by an identifier kwarg=value) as input, returning None.\nWe can also create a dictionary using another dictionary in combination with keyword arguments (dict(mapping, **kwarg)) as follows:\nAlternatively, we can construct a dictionary using an iterable (e.g. list of tuples). Each tuple must contain two objects. The first object becomes the key and the second becomes the value of the dictionary.\n'''\n# create a dictionary with dict() function using keyword arguments # Notice the input was not given in the format of dictionary.. the dict constructor will transform it dictionary format.\n# dictionary - ages of students\nstudents_ages = dict(Amanda=27, Teresa=38, Paula=17, Mario=40)\n\n# create a dictionary with dict() function using another dictionary and keyword arguments\n# dictionary - ages of students\nstudents_ages = dict({'Amanda':27,'Teresa':38},Paula=18,Mario=40) #Notice the single quotes not given as providing the input to constructor(**kwargs). refer to args&kwargs.py for more details\nprint(students_ages)\n\n# create a dictionary with dict() function using an iterable (list of tuples). # [] inside dict should be given or else we get error(dict expected at most 1 arguments, got 4) as dict is considering every tuple as a different argument and it expects only one argument.\n# dictionary - ages of students\nstudents_ages = dict([('Amanda', 27), ('Teresa', 38), ('Paula', 17), ('Mario', 40)])\nprint(students_ages)\n\n#Lastly, we can create a dictionary using two lists. First, we have to build an iterator of tuples using zip(*iterables) function. Then, we employ the dict([iterable, **kwarg]) function to construct the dictionary, as we did previously.\nstudents = ['Amanda', 'Teresa', 'Paula', 'Mario']\nages = [27, 38, 17, 40]\ns = dict(zip(students,ages))\n\n'''\n#Access values in a dictionary\n#To access dictionary values, we cannot use a numeric index (as we do with lists or tuples), since the dictionaries are unordered containers. Instead, we enclose the key using square brackets([]). If we try to access a value using an undefined key, a KeyError is raised.\n#To avoid getting an exception with undefined keys, we can use the method dict.get(key[, default]). This method returns the value for key if key is in the dictionary, else returns default. If default is not provided, it returns None (but never raises an exception).\n'''\n# access population\npopulation['Munich']\n# 1471508\n\n# # access a value using a numeric index\n# population[1]\n# # KeyError\n\n# # access population of Stuttgart\n# population['Stuttgart']\n# # KeyError\n\n# access population of Stuttgart using .get() method without default value\nprint(population.get('Munich'))\n# 1471508\n\n# access population of Stuttgart using .get() method without default value\nprint(population.get('Stuttgart'))\n# None\n\n# access population of Stuttgart using .get() method with default value\nprint(population.get('Stuttgart', 'Not found'))\n# Not found\n\n#Inserting elements\n#To insert an element in a dictionary, we can use square brackets as follows:\nproducts['pillow'] = 10\nprint(products)\n\n#To insert multiple items at once, we can use dict.update([]). This method updates key-value pairs from other,overwriting existing keys.\n## add shelf and sofa to the products dictionary using another dictionary object\nproducts.update({'shelf':70,'sofa':300})\nprint(products)\n\n## add three new items to the grades dictionary using keyword arguments\ngrades.update(Violeta=5.5, Marco=6.5, Paola=8)\nprint(grades)\n\n## add two cities to the population dictionary using a list of tuples\npopulation.update([('Stuttgart', 632743),('Dusseldorf', 617280)])\nprint(population)\n#As shown above, the .update() method accepts as an argument not only another dictionary, but also a list of tuples or keyword arguments. This method modifies the dictionary in-place, returning None.\n\n\n##5. Change elements in a dictionary\n#We can change the value of an item by accessing the key using square brackets ([]). To modify multiple values at once, we can use the .update() method, since this function overwrites existing keys.\n# Subsequently, we increase the price of a sofa 100 units, and we modify the grades of two students.\nprint(products)\nproducts['sofa'] = 400\n\nprint(products)\n#{'table': 120, 'chair': 40, 'lamp': 14, 'bed': 250, 'mattress': 100, 'pillow': 10, 'shelf': 70, 'sofa': 400}\n\n# modify the grades of two students\ngrades.update({'Normando':2.5,'Violetta':6})\nprint(grades)\n\n#6. Remove elements in a dictionary\n#To remove an element in a dictionary, we can use either the del dict[key] keyword or the dict.pop(key[, default]) method.\n#The del dict[key] keyword removes the given element from the dictionary, raising a KeyError if key does not exists.\nprint(population)\n#{'Berlin': 3748148, 'Hamburg': 1822445, 'Munich': 1471508, 'Cologne': 1085664, 'Frankfurt': 753056, 'Stuttgart': 632743,\n# 'Dusseldorf': 617280}\n# del population['Ingolstadt'] #KeyError: 'Ingolstadt'\n\n# key exists\n# the element dusseldorf is removed\ndel population['Dusseldorf']\n\n# key exists - the item is removed and the value returned\npopulation.pop('Stuttgart')\n# 632743 - returned value\n\n#If key exists in the dictionary, the dict.pop(key[, default]) method removes the item with the given key from the dictionary and returns its value. On the contrary, if key does not exist in the dictionary, the method returns the default value. If no default value is provided and key does not exist, the .pop() method will raise an exception (KeyError).\n\nprint(population)\n#{'Berlin': 3748148, 'Hamburg': 1822445, 'Munich': 1471508, 'Cologne': 1085664, 'Frankfurt': 753056}\n\n# key does not exists but default value is provided\npopulation.pop('Ingolstadt', 'Value not found')\n# 'Value not found' - returned value\n\n# # key does not exists and default value is NOT provided\n# population.pop('Garching')\n# # KeyError\n\n'''\n##7. Check if a key exists\n# To check whether a key exists in a dictionary, we have to use a membership operator. Membership operators are used to test whether a value is found in a sequence (e.g. strings, lists, tuples, sets, or dictionaries). There are two membership operators, as explained below.\n# in → Evaluates to true if the object on the left side is included in the object on the right side.\n# not in → Evaluates to true if the object on the left side is not included in the object on the right side.\n'''\nprint('Berlin' in population)\nprint('Ingolstadt' not in population)\n#As shown above, membership operators (in and not in) can be used to check whether a key exists in a dictionary, but they can also be used with other sequences in the following manner.\n\n# membership operators - in / not in\n#strings\nprint('a' in 'Amanda')\n\n#lists\nprint(3 in [1,2,3,4])\n\n#Tuples\nprint(s not in (1,2))\n\n#sets\nprint('Valencia' in {'Barcelona', 'Valencia', 'Madrid','Berlin'})\n\n#8. Copy a dictionary\n#To copy a dictionary, we can simply use the dict.copy() method. This method returns a shallow copy of the dictionary. We have to be careful with shallow copies, since if your dictionary contains another container-objects like lists, tuples, or sets, they will be referenced again and not duplicated.\n\n# dictionary with students heights\nstudents = {'Marco': 173, 'Luis': 184, 'Andrea': 168}\n\n# create a shallow copy\nstudents_2 = students.copy()\n\n# modify the height of luis in the shallow copy\nstudents_2['Luis'] = 180\n\n# the modification in students_2 is not observed in students since 180 is an int\nprint(students)\n# {'Marco': 173, 'Luis': 184, 'Andrea': 168}\n\nprint(students_2)\n# {'Marco': 173, 'Luis': 180, 'Andrea': 168}\n\n\n# dictionary with students heights and weights\nstudents_weights = {'Marco': [173, 70], 'Luis': [184, 80], 'Andrea': [168, 57]}\n\n# create a shallow copy\nstudents_weights_2 = students_weights.copy()\n\n# modify the height of luis in the shallow copy\nstudents_weights_2['Luis'][0] = 180\n# the modification in students_weights_2 is observed in students_weights\n# since the list containing the weight and height is referenced and not duplicated\nprint(students_weights)\n# {'Marco': [173, 70], 'Luis': [180, 80], 'Andrea': [168, 57]}\n\n# solution --> create a deepcopy of the dictionary\n\n#To avoid this problem, we can create a deep copy using copy.deepcopy(x) function (defined in the copy module) as follows:\n\nimport copy\nstudents_weights_2 = copy.deepcopy(students_weights)\nstudents_weights_2[0] = 174\n# the modification in students_weights_2 is NOT observed in students_weights\n# since we are working with a deep copy\n\nprint(students_weights)\n# {'Marco': [173, 70], 'Luis': [184, 80], 'Andrea': [168, 57]}\n\nprint(students_weights_2)\n# {'Marco': [173, 70], 'Luis': [180, 80], 'Andrea': [168, 57]}\n\n'''\n##The difference between shallow copies and deep copies is only relevant when the dictionary contains other objects like lists, since those objects will be referenced instead of duplicated (shallow copy). To create a fully independent clone of the original dictionary, we have to make a deep copy.\n\n#It is important to bear in mind that the = operator does not make a copy of the dictionary. It is just another name to refer to the same dictionary, meaning any modification to the new dictionary is reflected in the original one.\n'''\n\n# dictionary with calories in fruits\nfruits = {'Orange': 50, 'Apple': 65, 'Avocado': 160, 'Pear': 75}\n\n# copy the dictionary using = operators\nfruits_2 = fruits\n\n# modify fruits_2 (delete one item)\nfruits_2.pop('Orange')\n\n# the modification is reflected in fruits\nprint(fruits)\n# {'Apple': 65, 'Avocado': 160, 'Pear': 75}\n\n#9. Determine the length of the dictionary\n#To determine how many key-value pairs the dictionary contains, we can use the len() function. This function returns the number of items of an object. The input of the function can be a dictionary, but also another type of sequence such as a string, list, tuple, or set.\n\nprint(population)\nprint(len(population))\n\n#10. Loop through a dictionary\n#Iterating through keys\n#To iterate over the keys, we can use the dictionary directly in a for loop as follows:\n\n# iterate through keys\nfor city in population:\n print(city)\n\n#Alternatively, we can use the dict.keys() method. This method returns a view object, containing the keys of the dictionary.\nfor city in population.keys():\n print(city)\n'''\n#Iterating through values\n#If you just need to work with the values of a dictionary, then you can use the dict.values() method in a for loop. This method returns a view object that contains the values of the dictionary.\n'''\n#We can compute how many people live in the 5 largest German cities using dict.values() method as follows:\n\ninhabitants=0\nfor number in population.values():\n inhabitants += number\nprint(inhabitants)\n\n'''\n#Iterating through items\n#When you’re working with dictionaries, it’s likely that you need to use the keys and the values. To loop through both, you can use the dict.items() method. This method returns a view object, containing key-value pairs as a list of tuples.\n#We can determine the student with the lowest test score using the dict.items() method in combination with a for loop as follows:\n'''\n\n# students grades dictionary\nprint(grades)\n# {'Alba': 9.5, 'Eduardo': 10, 'Normando': 2.5, 'Helena': 6.5, 'Claudia': 7.5, 'Violeta': 6, 'Marco': 6.5, 'Paola': 8}\n\n# dict.items() - dictionary view object containing key-value pairs as a list of tuples\ngrades.items()\n# dict_items([('Alba', 9.5), ('Eduardo', 10), ('Normando', 2.5), ('Helena', 6.5), ('Claudia', 7.5),\n# ('Violeta', 6), ('Marco', 6.5), ('Paola', 8)])\n\n# determine student with the lowest test score\nmin_grade = 10\nmin_student = ''\nfor student, grade in grades.items():\n if grade < min_grade:\n min_student = student\n min_grade = grade\n\nprint(\"LOwest test score\",min_student)\n# Normando\n\n'''\n#11. Dictionary comprehensions\nPython for-loops are very handy in dealing with repetitive programming tasks; however, there is another alternative to achieve the same results in a more efficient way: dictionary comprehensions.\nDictionary comprehensions allow the creation of a dictionary using an elegant and simple syntax: {key: value for vars in iterable}. In addition, they are faster than traditional for-loops.\nWe can filter the products with a price lower than 100 euros using both a traditional for-loop and a dictionary comprehension. '''\n\n# list of prices\nprint(products)\n# {'table': 120, 'chair': 40, 'lamp': 14, 'bed': 250, 'mattress': 100, 'pillow': 10, 'shelf': 70, 'sofa': 400}\n\n##########################\n###traditional for loop###\n##########################\n\n# empty dictionary\nproducts_low = {}\n\n# select only the items with a price lower than 100\nfor product, value in products.items():\n if value < 100:\n products_low.update({product: value})\n\nprint(products_low)\n# {'chair': 40, 'lamp': 14, 'pillow': 10, 'shelf': 70}\n\n\n##############################\n###dictionary comprehension###\n##############################\n\n# select only the items with a price lower than 100\nproducts_low = {product: value for product, value in products.items() if value < 100}\n\nprint(products_low)\n# {'chair': 40, 'lamp': 14, 'pillow': 10, 'shelf': 70}\n#As we can observe, dictionary comprehensions provide the same results as traditional for-loops in a more elegant way.\n\n'''\n12. Nested dictionaries\nNested dictionaries are dictionaries that contain other dictionaries. We can create a nested dictionary in the same way we create a normal dictionary using curly brackets ({}).\nThe following nested dictionary contains information about 5 famous works of art. As we can observe, the values of the dictionary are other dictionaries as well.\n'''\n# nested dictionary containing information about famous works of art\nworks_of_art = {'The_Starry_Night': {'author': 'Van Gogh', 'year': 1889, 'style': 'post-impressionist'},\n 'The_Birth_of_Venus': {'author': 'Sandro Botticelli', 'year': 1480, 'style': 'renaissance'},\n 'Guernica': {'author': 'Pablo Picasso', 'year': 1937, 'style': 'cubist'},\n 'American_Gothic': {'author': 'Grant Wood', 'year': 1930, 'style': 'regionalism'},\n 'The_Kiss': {'author': 'Gustav Klimt', 'year': 1908, 'style': 'art nouveau'}}\nprint(works_of_art)\n#To access elements in a nested dictionary, we specify the keys using multiple square brackets ([]).\n# access elements in a nested dictionary\nworks_of_art['Guernica']['author']\n# 'Pablo Picasso'\n\nworks_of_art['American_Gothic']['style']\n# 'regionalism'\n\n#13. Alternative containers : OrderedDict, defaultdict, and Counter\n'''\nThe collections module provides alternative container datatypes to built-in Python containers. Three dictionary subclasses contained in the collections module that are pretty handy when working with Python are: (1)OrderedDict, (2)defaultdict, and (3)Counter.\nOrderedDict\nOrderedDict consists of a dictionary that remembers the order in which its contents are added. In Python 3.6+ dictionaries are also insertion ordered, meaning they remember the order of items inserted. However, to guarantee element order across other Python versions, we have to use OrderedDict containers.\n'''\n\nimport collections\n\n# create an OrderedDict of chemical elements\ndictionary = collections.OrderedDict({'hydrogen': 1, 'helium': 2, 'carbon': 6, 'oxygen': 8})\n\n# type OrderedDict\nprint(type(dictionary))\n# \n\n# dictionary keys --> .keys() method\nprint(dictionary.keys())\n# odict_keys(['hydrogen', 'helium', 'carbon', 'oxygen'])\n\n# dictionary values --> .values() method\nprint(dictionary.values())\n# odict_values([1, 2, 6, 8])\n\n# insert a new element\ndictionary['nitrogen'] = 7\n\n# nitrogen last position since it is the last element added\nprint(dictionary)\n# OrderedDict([('hydrogen', 1), ('helium', 2), ('carbon', 6), ('oxygen', 8), ('nitrogen', 7)])\n#As shown above, OrderedDict accepts dictionary methods and functions. Moreover, elements can be inserted, changed, or deleted in the same way as with normal dictionaries.\n\nimport collections\n\n# create an OrderedDict of chemical elements\ndictionary = collections.OrderedDict({'hydrogen': 1, 'helium': 2, 'carbon': 6, 'oxygen': 8})\n\n# type OrderedDict\nprint(type(dictionary))\n# \n\n# dictionary keys --> .keys() method\nprint(dictionary.keys())\n# odict_keys(['hydrogen', 'helium', 'carbon', 'oxygen'])\n\n# dictionary values --> .values() method\nprint(dictionary.values())\n# odict_values([1, 2, 6, 8])\n\n# insert a new element\ndictionary['nitrogen'] = 7\n\n# nitrogen last position since it is the last element added\nprint(dictionary)\n# OrderedDict([('hydrogen', 1), ('helium', 2), ('carbon', 6), ('oxygen', 8), ('nitrogen', 7)])\n\n#As shown above, OrderedDict accepts dictionary methods and functions. Moreover, elements can be inserted, changed, or deleted in the same way as with normal dictionaries.\n\n#defaultdict\n#Defaultdicts are a dictionary subclass that assign a default value when a key is missing (it has not been set yet). They never raise a KeyError, if we try to access an item that is not available in the dictionary, instead a new entry is created.\n#Defaultdicts take a function as an argument, and initialize the missing key with the value returned by the function. In the example below, the keys are initialized with different values, depending on the function employed as first argument.\n\n\nimport collections\nimport numpy as np\n\n# missing key initialized with a 0\ndefault_1 = collections.defaultdict(int)\n\ndefault_1['missing_entry']\nprint(default_1)\n# defaultdict(, {'missing_entry': 0})\n\n# missing key initialized with an empty list\ndefault_2 = collections.defaultdict(list, {'a': 1, 'b': 2})\n\ndefault_2['missing_entry']\nprint(default_2)\n# defaultdict(, {'a': 1, 'b': 2, 'missing_entry': []})\n\n# missing key initialized with a string\ndefault_3 = collections.defaultdict(lambda : 'Not given', a=1, b=2)\n\ndefault_3['missing_entry']\nprint(default_3)\n# defaultdict( at 0x000001DEF6ADF730>, {'a': 1, 'b': 2, 'missing_entry': 'Not given'})\n\n# missing key initialized with a numpy array\ndefault_4 = collections.defaultdict(lambda: np.zeros(2))\n\ndefault_4['missing_entry']\nprint(default_4)\n# defaultdict( at 0x000001DEF6ADF950>, {'missing_entry': array([0., 0.])})\n#As we can observe, we can pass a dictionary or keywords as second argument (optional) to initialize the defaultdict container.\n\n\n#Counter\n#A Counter is a dictionary subclass for counting hastable objects. The function returns a Counter object, where elements are stored as keys and their counts are stored as values. Using this function, we can easily count the elements of a list, as shown below.\n\nletters = ['a','b','c','a','b','e','d']\n\ncounter = collections.Counter(letters)\nprint(counter)\nprint(counter.most_common(3))\n#As shown above, we can easily obtain the most frequent elements with the .most_common([n]) method. This method returns a list of the n most common elements and their counts.\n\n#14. Create a Pandas DataFrame from a dictionary.\n#A Pandas DataFrame is a two-dimensional tabular data where each row represents an observation and each column a variable. A Pandas DataFrame can be created using the pandas.DataFrame constructor. This function accepts as input various python containers (e.g. lists, dictionaries, or numpy arrays). However, in this article, we explain only the ways to create a DataFrame that involve the use of dictionaries.\n#Create a DataFrame from a dictionary\n#We can create a DataFrame from a dictionary, where the keys represent column names, and the values represent column data in the following manner:\n\nimport pandas as pd\n\n# create a Pandas DataFrame from a dictionary - keys (column name) - value (column data)\ndf = pd.DataFrame({'name': ['Mario', 'Violeta', 'Paula'],\n 'age': [22, 27, 19],\n 'grades': [9, 8.5, 7]})\nprint(df)\n#As we can observe, the default index is just the row number (an integer index beginning at 0). We can modify these indexes by passing the index list to the DataFrame constructor.\n\ndf_index = pd.DataFrame({'name': ['Mario', 'Violeta', 'Paula'],\n 'age': [22, 27, 19],\n 'grades': [9, 8.5, 7]}, index=['student_1','student_2','student_3'])\n\nprint(df_index)\n\n#Create a DataFrame from a list of dictionaries\n#A list of dictionaries can also be used to create a DataFrame, where the keys represent column names. As before, we can change indexes by passing the index list to the DataFrame function.\n# create a Pandas DataFrame from a list of dictionaries - keys(column name) - with custom indexes\ndf_2 = pd.DataFrame([{'name': 'Mario', 'age': 22, 'grades':9},\n {'name': 'Violeta', 'age': 27, 'grades':8.5},\n {'name': 'Paula', 'age': 19, 'grades':7}], index=['student_1', 'student_2', 'student_3'])\n\nprint(df_2)","sub_path":"towardsdatascience_dictionaries.py","file_name":"towardsdatascience_dictionaries.py","file_ext":"py","file_size_in_byte":22027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"580697267","text":"#!/usr/bin/env python\n\nimport BaseHTTPServer\nimport logging\nimport optparse\nimport sys\n\nimport pages\n\nclass TibstatsHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n\n def do_GET(self):\n self.process_request()\n\n def do_POST(self):\n self.process_request()\n\n def do_HEAD(self):\n self.send_error(418, \"Short and stout\")\n\n def process_request(self):\n pages.handle_http_request(self)\n\n # maybe want to hook the internal request logging mechanism?\n #def log_message(self, format, *posargs):\n # logging.info(format, *posargs)\n\ndef main():\n parser = optparse.OptionParser()\n parser.add_option(\"-p\", \"--port\", type=\"int\", default=17091)\n opts, args = parser.parse_args()\n logging.basicConfig(level=logging.DEBUG)\n server_class = BaseHTTPServer.HTTPServer\n handler_class = TibstatsHTTPRequestHandler\n server_address = (\"\", opts.port)\n logging.info(\"Starting server on %s\", server_address)\n httpd = server_class(server_address, handler_class)\n httpd.serve_forever()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"projects/tibstat/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"440862144","text":"import numpy as np\n\nN = 4\nM = 5\n\nA = np.random.randint(low=-9, high=10, size=(N, M))\nprint(\"Матрица:\\r\\n{}\\n\".format(A))\n\nSum = A.sum()\nprint(\"Сумма элементов всей матрицы: \" + str(Sum) + \"\\n\")\nSum_column = A.sum(axis=1)\nX = []\nfor i in range(0, N):\n n = Sum_column[i] / Sum\n X.append(n)\nX = np.array(X)[: , np.newaxis]\nA = np.hstack((A, X))\n\nprint(A)\n","sub_path":"2 часть курсовой/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"377571934","text":"#Вторая программа\n\nfrom matplotlib import pyplot\nfrom openpyxl import load_workbook\n\ndef getvalue(x):\n return x.value\n\nwb = load_workbook('data_analysis_lab.xlsx')\n\nlict = wb['Data']\n\nyears = list(map(getvalue, lict['A'][1:]))\nrelative_temp = list(map(getvalue, lict['C'][1:]))\nactivity = list(map(getvalue, lict['D'][1:]))\n\npyplot.plot(years, relative_temp, label=\"Относительная температура\")\npyplot.plot(years, activity, label=\"Солнечная активность\")\n\npyplot.xlabel('Год')\npyplot.ylabel('Температура/Солнечная активность')\npyplot.legend(loc='best')\n\npyplot.show()","sub_path":"Lab1.2/SecondLab.py","file_name":"SecondLab.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"171196177","text":"class TreeNode(object):\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n def rightSideView(self, root):\n if not root:\n return []\n queue = []\n queue.append(root)\n result = []\n\n while queue:\n size = len(queue)\n for i in range(size):\n node = queue[0]\n queue = queue[1:]\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n result.append(node.val)\n\n return result","sub_path":"2021-02-02_DFS-BFS/199_BinaryTreeRightSideView.py","file_name":"199_BinaryTreeRightSideView.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"102472638","text":"#!/usr/bin/python3\n\"\"\"Conn module\"\"\"\nimport MySQLdb\nfrom sys import argv\n\nif __name__ == '__main__':\n myU = argv[1]\n myP = argv[2]\n myDB = argv[3]\n sName = argv[4]\n myH = \"localhost\"\n db = MySQLdb.connect(host=myH, port=3306, user=myU, passwd=myP, db=myDB)\n cur = db.cursor()\n myQ = \"SELECT c.name FROM cities AS c, states AS s \"\n myQ += \"WHERE s.name = %s AND s.id = c.state_id ORDER BY c.id;\"\n cur.execute(myQ, (sName,))\n result = cur.fetchall()\n if (len(result) is not 0):\n for row in result:\n for col in row:\n if (result.index(row) is len(result) - 1):\n print(col)\n else:\n print(col, end=', ')\n else:\n print()\n cur.close()\n db.close()\n","sub_path":"0x0F-python-object_relational_mapping/5-filter_cities.py","file_name":"5-filter_cities.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"465565935","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param {TreeNode} root\n # @return {string[]}\n def binaryTreePaths(self, root):\n \n if root is None: return []\n \n def allBinaryTreePaths(currPath, pathSets, currNode):\n if currNode.left is None and currNode.right is None:\n pathSets.append(currPath)\n else:\n if currNode.left:\n allBinaryTreePaths(currPath + '->' + str(currNode.left.val), pathSets, currNode.left)\n if currNode.right:\n allBinaryTreePaths(currPath + '->' + str(currNode.right.val), pathSets, currNode.right)\n \n pathSets = []\n allBinaryTreePaths(str(root.val), pathSets, root)\n return pathSets","sub_path":"257-Binary-Tree-Paths/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"316298554","text":"import unittest\nimport config\nimport os\nimport time\nfrom LoginMain import UserLogin\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\n\n\nclass DocumentUpload(unittest.TestCase):\n def setUp(self):\n self.login = UserLogin().__int__()\n self.login.signin.click()\n start_translate = WebDriverWait(self.login.driver, 20) \\\n .until(lambda driver: driver.find_element_by_id(\"start-translate\"))\n start_translate.click()\n self.source_lang = self.login.driver.find_element_by_id(\"source-lang\")\n self.target_lang = self.login.driver.find_element_by_id(\"target-lang\")\n self.upload = self.login.driver.find_element_by_id(\"upload\")\n self.back = self.login.driver.find_element_by_id(\"back\")\n self.file_upload = self.login.driver.find_element_by_xpath(\"//input[@type='file']\")\n time.sleep(3)\n\n def test1_upload_document(self):\n try:\n driver = self.login.driver\n self.source_lang.click()\n source_english = WebDriverWait(driver, 20).until(lambda d: d.find_element_by_id(\"English\"))\n source_english.click()\n self.target_lang.click()\n target_hindi = WebDriverWait(driver, 20).until(lambda d: d.find_element_by_id(\"Hindi\"))\n target_hindi.click()\n time.sleep(2)\n self.file_upload.send_keys(\"/home/roshan/Downloads/2c6d61e3-3a84-4f37-814e-d20f2073a05f.pdf\")\n time.sleep(5)\n self.upload.click()\n result = WebDriverWait(driver, 20).until(lambda d: d.current_url == config.view_document_url)\n time.sleep(5)\n if result:\n print(\n f'=HYPERLINK(\"{config.hyperlink_pretext}{os.path.basename(__file__)}\";\"test1_upload_document\"),PASSED')\n except Exception:\n print(\n f'=HYPERLINK(\"{config.hyperlink_pretext}{os.path.basename(__file__)}\";\"test1_upload_document\"),FAILED')\n finally:\n driver.quit()\n\n def test2_click_on_back_button(self):\n try:\n driver = self.login.driver\n self.back.click()\n result = WebDriverWait(driver, 20).until(lambda d: d.current_url == config.view_document_url)\n time.sleep(5)\n if result:\n print(\n f'=HYPERLINK(\"{config.hyperlink_pretext}{os.path.basename(__file__)}\";\"test2_click_on_back_button\"),PASSED')\n except Exception:\n print(\n f'=HYPERLINK(\"{config.hyperlink_pretext}{os.path.basename(__file__)}\";\"test2_click_on_back_button\"),FAILED')\n finally:\n driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/DocumentUpload.py","file_name":"DocumentUpload.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"574538046","text":"from flask import Flask, jsonify, request, send_file, send_from_directory, flash, render_template, url_for, redirect\nfrom flask_restful import Api\n\nfrom flask_login import LoginManager, login_user, logout_user, login_required, current_user\n\nfrom db import db\nfrom blacklist import BLACKLIST\nfrom resources.user import User, UserLogin\nfrom resources.wordpress import Wordpress, WordpressList\nfrom resources.wordpressCust import WordpressCust, WordpressListCust\nfrom resources.store import Store, StoreList\nfrom resources.accessiDb import Db, DbList\nfrom resources.cPanel import Cpanel, CpanelList\nfrom resources.ftp import Ftp, FtpList\nfrom resources.plugin import Plugin, PluginList\nfrom models.user import UserModel\n\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\napp.config['PROPAGATE_EXCEPTIONS'] = True\n# enable blacklist feature\n# allow blacklisting for access and refresh tokens\n\napp.secret_key = 'jose' # could do app.config['JWT_SECRET_KEY'] if we prefer\n# Configure application to store JWTs in cookies. Whenever you make\n# a request to a protected endpoint, you will need to send in the\n# access or refresh JWT via a cookie.\n\napi = Api(app)\nlogin_manager = LoginManager(app)\ndb.init_app(app)\n\n\n@app.before_first_request\ndef create_tables():\n db.create_all()\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return UserModel.query.get(int(user_id))\n\n\napi.add_resource(Store, '/store/')\napi.add_resource(StoreList, '/stores')\n# wordpress\napi.add_resource(Wordpress, '/wordpress/')\napi.add_resource(WordpressList, '/wordpress')\n# wordpress User\napi.add_resource(WordpressCust, '/wordpress-cust/')\napi.add_resource(WordpressListCust, '/wordpress-cust')\n# database\napi.add_resource(Db, '/db/')\napi.add_resource(DbList, '/db')\n# cPanel\napi.add_resource(Cpanel, '/cpanel/')\napi.add_resource(CpanelList, '/cpanel')\n# ftp\napi.add_resource(Ftp, '/ftp/')\napi.add_resource(FtpList, '/ftp')\n# plugin\napi.add_resource(Plugin, '/plugin/')\napi.add_resource(PluginList, '/plugin')\n\n\n# api.add_resource(UserRegister, '/register')\napi.add_resource(User, '/user/')\napi.add_resource(UserLogin, '/api/login')\n\n\n#------------------Login Form---------------#\n\n\n@app.route('/')\n@login_required\ndef finder():\n return render_template('build/index.html')\n\n\n@app.route('/')\ndef login():\n return render_template('build/index.html')\n\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return 'Log out effettuato '\n\n\nif __name__ == '__main__':\n\n login_manager.init_app(app)\n\n app.run(port=5000, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"251899494","text":"# Tome como referencia los formatos del video del curso \"Ejemplo - Gráfica de ciudades colombianas\". \n\n#Escriba un programa de Python que:\n\n#1. Tenga una función que se llama lee_datos que tiene como primer\n#argumento la cadena de caracteres que representa el nombre del\n#archivo con las coordenadas (con el mismo formato del video) y como\n#segundo argumento la cadena de caracteres que representa el nombre\n#del archivo con los nombres de las ciudades. La función debe devolver\n#dos arrays de numpy, el primer array corresponde a las coordenadas y\n#el segundo a los nombres de las ciudades. \n\n#2. Tenga una función que se llama genera_recorrido. Esta función\n#tiene como argumento de entrada un array con nombres de ciudades. La\n#función genera una lista aleatoria de n+1 enteros donde el primer y\n#último elemento es el número 0. n es la longitud del array del nombre\n#de ciudades. Los demás elementos de la lista deben incluir, en\n#desorden, los números del 1 al n-1. En este lista el entero n va a\n#representar a la ciudad n-esima en el array de entrada. Esta lista de\n#enteros va a representar entonces un recorrido que empieza y termina\n#en la primera ciudad de la lista y pasa por todas las ciudades. La\n#función debe devolver la lista de n+1 enteros. \n\n#3. Tenga una función que se llama calcula_distancia. Esta función\n#toma como primer argumento de entrada un array de coordenadas de\n#ciudades, como segundo argumento un entero a, como tercer argumento\n#un entero b. Los enteros representan las filas del array de\n#coordenadas. La función deben calcular la distancia entre las dos\n#ciudades representadas por los dos enteros a y b, dadas las\n#coordenadas de entrada. La función debe devolver el valor de la\n#distancia. Calcule esta distancia asumiendo que la Tierra es una\n#esfera perfecta de radio 6400 km y que la medición se hace sobre el\n#arco de longitud mínima sobre esa\n#esfera https://www.johndcook.com/lat_long_details.html \n\n#4. Tenga una función que se llama calcula_distancia_total. Esta\n#función toma como primer argumento de entrada un array de coordenadas\n#de ciudades y como segundo argumento una lista con al menos dos\n#enteros. Los enteros representan las filas del array de\n#coordenadas. La función debe calcular la distancia total del\n#recorrido representado por la lista de enteros de entrada. La función\n#debe devolver la distancia total. \n\n#5. Tenga una función que se llama encuentra_recorrido. La\n#función toma como primer argumento el nombre del archivo con\n#coordenadas de ciudades y como segundo argumento el nombre del\n#archivo con los nombres de las ciudades. La función utiliza las\n#funciones de los cuatro puntos anteriores para generar 100 recorridos\n#diferentes por las ciudades de los archivos de entrada. De esos 100\n#recorridos encuentra el recorrido de menor longitud total y lo\n#grafica en un plano Longitud-Latitud donde cada ciudad está\n#representada por un punto y su nombre. Los pares de ciudades que\n#están conectadas en el recorrido se representan por una línea recta\n#en el plano Longitud-Latitud. La gráfica debe guardarse como\n#\"recorrido_mas_corto.png\". La función devuelve None. \n\n#Pueden usar la función shuffle de numpy\n#(https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.shuffle.html) \n#Solamente son permitidas las funciones y métodos que aparezcan en los\n#videos vistos hasta ahora en el curso. \n\n#El programa debe estar en un archivo llamado\n#\"ApellidoNombre_Ejercicio04.py\" donde Apellido y Nombre debe\n#reemplazarlos con su apellido y nombre. El archivo solamente debe\n#incluir los imports necesarios y las funciónes pedida. Suba ese\n#archivo como respuesta a esta actividad. \n\n#Al ejecutar \"python ApellidoNombre_Ejercicio04.py\" no se\n#debe producir ningún error, nada se debe imprimir en pantalla y\n#ningún archivo debe ser creado por el programa. \n\n#Para calificar el ejercicios vamos a llamar la función\n#encuentra_recorrido con dos nombres de archivos y contenidos\n#diferentes a los del video. Esos archivos contienen los datos de al\n#menos cuatro ciudades. \n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef lee_datos(archivo_coordenadas, archivo_nombres):\n coordenadas = np.loadtxt(archivo_coordenadas, delimiter=\",\")\n nombres = np.loadtxt(archivo_nombres, dtype=\"str\")\n return coordenadas, nombres\n\ndef genera_recorrido(nombres):\n n = len(nombres)\n r = np.arange(n-1)+1\n np.random.shuffle(r)\n r = [0] + list(r) + [0]\n return r\n\ndef calcula_distancia(coordenadas, a, b):\n latitud = coordenadas[:,0]\n longitud = coordenadas[:,1]\n\n phi = 90.0 - latitud\n theta = longitud\n theta[longitud<0] = 360.0 + longitud[longitud<0]\n\n phi = phi * np.pi/180.0\n theta = theta * np.pi/180.0\n\n psi = np.sin(phi[a])*np.sin(phi[b]) * np.cos(theta[a]-theta[b])\n psi = psi + np.cos(phi[a]) * np.cos(phi[b])\n psi = np.arccos(psi)\n rho = 6400.0\n return rho*psi\n\ndef calcula_distancia_total(coordenadas, recorrido):\n d = 0\n for i in range(len(recorrido)-1):\n d += calcula_distancia(coordenadas, recorrido[i], recorrido[i+1])\n return d\n\ndef encuentra_recorrido(archivo_coordenadas, archivo_nombres):\n coordenadas, nombres = lee_datos(archivo_coordenadas, archivo_nombres)\n\n d_min = 1E10\n r_min = []\n for i in range(100):\n r = genera_recorrido(nombres)\n d = calcula_distancia_total(coordenadas, r)\n if d < d_min:\n d_min = d\n r_min = r.copy()\n\n plt.figure()\n n_ciudades = len(nombres)\n for i in range(n_ciudades):\n plt.text(coordenadas[i,1], coordenadas[i,0], nombres[i])\n\n plt.scatter(coordenadas[r_min,1], coordenadas[r_min,0])\n plt.plot(coordenadas[r_min,1], coordenadas[r_min,0])\n\n plt.xlabel(\"Longitud [grados]\")\n plt.ylabel(\"Latitud [grados]\")\n plt.axis('equal')\n plt.savefig(\"recorrido_mas_corto.png\")\n\n return None\n\n","sub_path":"soluciones/ejercicio_04.py","file_name":"ejercicio_04.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"461057084","text":"from collections import OrderedDict\n\ndef main():\n f = open('21-input.txt', 'r')\n lines = f.read().split('\\n')[:-1]\n f.close()\n\n foods = []\n allergens = []\n for line in lines:\n foods.append((line.split(' (')[0].split(' '), line.split('contains ')[1][:-1].split(', ')))\n allergens.extend(line.split('contains ')[1][:-1].split(', '))\n \n allergens = remove_duplicates(allergens)\n\n possibles = {}\n for allergen in allergens:\n allergen_foods = []\n ingredients = []\n for food in foods:\n if allergen in food[1]:\n allergen_foods.append(food[0])\n ingredients.extend(food[0])\n ingredients = remove_duplicates(ingredients)\n \n matching = []\n for ingredient in ingredients:\n failed = False\n for allergen_food in allergen_foods:\n if ingredient not in allergen_food:\n failed = True\n break\n if not failed:\n matching.append(ingredient)\n \n possibles[allergen] = matching\n\n finals = {}\n while len(finals) < len(possibles):\n for allergen, ingredients in possibles.items():\n if len(ingredients) == 1:\n finals[allergen] = ingredients[0]\n for key in possibles.keys():\n if key == allergen:\n continue\n if ingredients[0] in possibles[key]:\n possibles[key].remove(ingredients[0])\n\n bad = []\n ordered_finals = OrderedDict(sorted(finals.items()))\n for key, value in ordered_finals.items():\n bad.append(value)\n result = ','.join(bad)\n\n print('Result:', result)\n\ndef remove_duplicates(_list):\n temp = []\n for i in _list:\n if i not in temp:\n temp.append(i)\n return temp\n\nif __name__ == '__main__':\n main()\n\n# Result: \n","sub_path":"Day 21/21-2.py","file_name":"21-2.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"645004712","text":"# -*- coding: utf-8 -*-\n\"\"\"Tests for the `provider` module.\"\"\"\n\nfrom unittest.mock import patch\n\nfrom certificate_validator.provider import (\n Provider, Request, RequestResourceProperties, RequestType, Response,\n Status\n)\n\nfrom .base import (\n BaseTestCase, ProviderBaseTestCase, RequestBaseTestCase,\n ResponseBaseTestCase\n)\n\n\nclass RequestTypeTestCase(BaseTestCase):\n def setUp(self):\n super(RequestTypeTestCase, self).setUp()\n\n def test_class(self):\n self.assertEqual('Create', RequestType.CREATE.value)\n self.assertEqual('Update', RequestType.UPDATE.value)\n self.assertEqual('Delete', RequestType.DELETE.value)\n\n\nclass StatusTestCase(BaseTestCase):\n def setUp(self):\n super(StatusTestCase, self).setUp()\n\n def test_class(self):\n self.assertEqual('SUCCESS', Status.SUCCESS.value)\n self.assertEqual('FAILED', Status.FAILED.value)\n\n\nclass RequestTestCase(RequestBaseTestCase):\n def setUp(self):\n super(RequestTestCase, self).setUp()\n\n def test_init(self):\n kwargs = {'a': 1, 'b': 2, 'c': 3}\n r = Request(**kwargs)\n self.assertEqual(1, r.a)\n self.assertEqual(2, r.b)\n self.assertEqual(3, r.c)\n self.assertEqual(Request.DEFAULT_REGION, r.region)\n\n def test_request_type(self):\n self.assertEqual('request_type', self.request.request_type)\n\n def test_service_token(self):\n self.assertEqual('service_token', self.request.service_token)\n\n def test_response_url(self):\n self.assertEqual('response_url', self.request.response_url)\n\n def test_stack_id(self):\n self.assertEqual('stack_id', self.request.stack_id)\n\n def test_request_id(self):\n self.assertEqual('request_id', self.request.request_id)\n\n def test_resource_type(self):\n self.assertEqual('resource_type', self.request.resource_type)\n\n def test_logical_resource_id(self):\n self.assertEqual(\n 'logical_resource_id', self.request.logical_resource_id\n )\n\n def test_physical_resource_id(self):\n self.assertEqual(\n 'physical_resource_id', self.request.physical_resource_id\n )\n kwargs = {}\n r = Request(**kwargs)\n self.assertEqual('', r.physical_resource_id)\n\n def test_resource_properties(self):\n self.assertEqual(\n 'service_token', self.request.resource_properties.service_token\n )\n\n def test_resource_properties_none(self):\n r = Request(ResourceProperties=None)\n properties = r.resource_properties\n self.assertIsInstance(properties, RequestResourceProperties)\n # TODO\n\n def test_old_resource_properties(self):\n self.assertEqual(\n 'service_token', self.request.old_resource_properties.service_token\n )\n\n def test_old_resource_properties_none(self):\n r = Request(OldResourceProperties=None)\n properties = r.old_resource_properties\n self.assertIsInstance(properties, RequestResourceProperties)\n # TODO\n\n def test_sans(self):\n kwargs = {\n 'ResourceProperties': {\n 'SubjectAlternativeNames': ['www.certificate-validator.com']\n }\n }\n r = Request(**kwargs)\n self.assertEqual(['www.certificate-validator.com'],\n r.resource_properties.sans)\n\n def test_old_sans(self):\n kwargs = {\n 'OldResourceProperties': {\n 'SubjectAlternativeNames': ['www.certificate-validator.com']\n }\n }\n r = Request(**kwargs)\n properties = r.resource_properties\n old_properties = r.old_resource_properties\n self.assertEqual([], properties.sans)\n self.assertEqual(['www.certificate-validator.com'],\n old_properties.sans)\n\n def test_sans_with_empty_only(self):\n self.assertEqual([], self.request.resource_properties.sans)\n for case in [None, [''], [None], ['', None], [None, '']]:\n kwargs = {'ResourceProperties': {'SubjectAlternativeNames': case}}\n r = Request(**kwargs)\n properties = r.resource_properties\n self.assertEqual([], properties.sans,\n \"Failed test. input %s, expected %s, got %s\" %\n (case, [], properties.sans))\n\n def test_sans_with_mixed(self):\n for case in [['', 'www.certificate-validator.com'],\n [None, 'www.certificate-validator.com'],\n ['www.certificate-validator.com', None],\n ['', 'www.certificate-validator.com', None],\n [None, '', 'www.certificate-validator.com']]:\n kwargs = {'ResourceProperties': {'SubjectAlternativeNames': case}}\n r = Request(**kwargs)\n properties = r.resource_properties\n sans = properties.sans\n self.assertEqual(['www.certificate-validator.com'], sans,\n \"Failed test. input %s, expected %s, got %s\" %\n (case, ['www.certificate-validator.com'], sans))\n\n def test_region_default(self):\n self.assertEqual(Request.DEFAULT_REGION, self.request.region)\n\n def test_region_caching(self):\n region = self.request.region\n self.mock_logger.warning.assert_called_with(\n \"Failed to parse stack ARN(%s) to get region - defaulting to %s\",\n 'stack_id', Request.DEFAULT_REGION\n )\n self.mock_logger.reset_mock()\n region2 = self.request.region\n self.mock_logger.warning.assert_not_called()\n self.assertIs(region, region2)\n self.assertEqual(Request.DEFAULT_REGION, self.request.region)\n\n def test_region_from_arn(self):\n for region in ['us-west-1', 'us-east-1', 'us-west-2', 'ap-south-1']:\n kwargs = {\n \"StackId\":\n \"arn:aws:cloudformation:{}:{}:stack/stackname/guid\".format(\n region, '123456789012'\n )\n }\n r = Request(**kwargs)\n actual = r.region\n self.assertEqual(\n region, actual, \"Expected %s, got %s\" % (region, actual)\n )\n\n\nclass ResponseTestCase(ResponseBaseTestCase):\n def setUp(self):\n super(ResponseTestCase, self).setUp()\n\n def test_init(self):\n kwargs = {'a': 1, 'b': 2, 'c': 3}\n r = Response(**kwargs)\n self.assertEqual(1, r.a)\n self.assertEqual(2, r.b)\n self.assertEqual(3, r.c)\n r = Response(\n request_id='request_id',\n stack_id='stack_id',\n logical_resource_id='logical_resource_id'\n )\n self.assertEqual('request_id', r.request_id)\n self.assertEqual('stack_id', r.stack_id)\n self.assertEqual('logical_resource_id', r.logical_resource_id)\n self.assertEqual('', r.physical_resource_id)\n r = Response(\n request_id='request_id',\n stack_id='stack_id',\n logical_resource_id='logical_resource_id',\n physical_resource_id='physical_resource_id'\n )\n self.assertEqual('request_id', r.request_id)\n self.assertEqual('stack_id', r.stack_id)\n self.assertEqual('logical_resource_id', r.logical_resource_id)\n self.assertEqual('physical_resource_id', r.physical_resource_id)\n\n def test_status(self):\n self.assertEqual('status', self.response.status)\n\n def test_reason(self):\n self.assertEqual('reason', self.response.reason)\n\n def test_stack_id(self):\n self.assertEqual('stack_id', self.response.stack_id)\n\n def test_request_id(self):\n self.assertEqual('request_id', self.response.request_id)\n\n def test_logical_resource_id(self):\n self.assertEqual(\n 'logical_resource_id', self.response.logical_resource_id\n )\n\n def test_physical_resource_id(self):\n self.assertEqual(\n 'physical_resource_id', self.response.physical_resource_id\n )\n\n def test_no_echo(self):\n self.assertEqual(True, self.response.no_echo)\n\n def test_data(self):\n self.assertEqual({'a': 1, 'b': 2, 'c': 3}, self.response.data)\n\n def test_set_status(self):\n self.response.set_status(True)\n self.assertEqual('SUCCESS', self.response.status)\n self.response.set_status(False)\n self.assertEqual('FAILED', self.response.status)\n\n def test_set_reason(self):\n self.response.set_reason('')\n self.assertEqual('', self.response.reason)\n\n def test_set_physical_resource_id(self):\n self.response.set_physical_resource_id('1337')\n self.assertEqual('1337', self.response.physical_resource_id)\n\n def test_set_data(self):\n self.response.set_data({'a': 1, 'b': 2, 'c': 3})\n self.assertEqual({'a': 1, 'b': 2, 'c': 3}, self.response.data)\n kwargs = {}\n r = Response(**kwargs)\n r.set_data({'a': 1, 'b': 2, 'c': 3})\n self.assertEqual({'a': 1, 'b': 2, 'c': 3}, r.data)\n\n def test_dict(self):\n self.kwargs = self.response.dict()\n\n\nclass ProviderTestCase(ProviderBaseTestCase):\n def setUp(self):\n super(ProviderTestCase, self).setUp()\n\n def test_init(self):\n self.assertEqual(self.provider.request, self.request)\n self.assertEqual(self.provider.response, self.response)\n\n def test_set_response(self):\n r = Response()\n self.provider._set_response(r)\n self.assertEqual(r, self.provider.response)\n\n def test_create(self):\n with self.assertRaises(NotImplementedError):\n self.provider.create()\n\n def test_update(self):\n with self.assertRaises(NotImplementedError):\n self.provider.update()\n\n def test_delete(self):\n with self.assertRaises(NotImplementedError):\n self.provider.delete()\n\n def test_handler_create(self):\n self.mock_create = patch.object(Provider, 'create').start()\n self.mock_send_response = patch.object(Provider,\n 'send_response').start()\n self.request_kwargs['RequestType'] = 'Create'\n request = Request(**self.request_kwargs)\n provider = Provider(request, self.response)\n provider.handler()\n self.mock_create.assert_called_once()\n self.mock_send_response.assert_called_once()\n\n def test_handler_update(self):\n self.mock_update = patch.object(Provider, 'update').start()\n self.mock_send_response = patch.object(Provider,\n 'send_response').start()\n self.request_kwargs['RequestType'] = 'Update'\n request = Request(**self.request_kwargs)\n provider = Provider(request, self.response)\n provider.handler()\n self.mock_update.assert_called_once()\n self.mock_send_response.assert_called_once()\n\n def test_handler_delete(self):\n self.mock_delete = patch.object(Provider, 'delete').start()\n self.mock_send_response = patch.object(Provider,\n 'send_response').start()\n self.request_kwargs['RequestType'] = 'Delete'\n request = Request(**self.request_kwargs)\n provider = Provider(request, self.response)\n provider.handler()\n self.mock_delete.assert_called_once()\n self.mock_send_response.assert_called_once()\n\n def test_handler_unknown(self):\n self.mock_send_response = patch.object(Provider,\n 'send_response').start()\n self.request_kwargs['RequestType'] = 'Unknown'\n request = Request(**self.request_kwargs)\n provider = Provider(request, self.response)\n provider.handler()\n self.assertEqual('FAILED', self.provider.response.status)\n self.assertEqual(\n 'Unknown RequestType: Must be one of: Create, Update, or Delete.',\n self.provider.response.reason\n )\n self.mock_send_response.assert_called_once()\n\n def test_send_response(self):\n self.provider.send_response()\n self.mock_requests.put.assert_called_with(\n 'response_url',\n json=self.provider.response.dict(),\n headers={'Content-Type': ''}\n )\n","sub_path":"certificate_validator/tests/test_provider.py","file_name":"test_provider.py","file_ext":"py","file_size_in_byte":12291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"497804475","text":"from torch.autograd import Variable\nimport numpy as np\nimport os\nimport sys\ncurrent_dir = os.path.dirname(os.path.abspath(\"__file__\"))\nsys.path.append( str(current_dir) + '/../../../' )\n\nfrom setting_param import prediction_num_of_node_max_new as max_new\nfrom setting_param import prediction_num_of_node_min_new as min_new\nfrom setting_param import prediction_num_of_node_max_lost as max_lost\nfrom setting_param import prediction_num_of_node_min_lost as min_lost\n\ndef inference(dataloader, net, criterion, opt, OutputDir, node_type):\n net.eval()\n for i, (sample_idx, input_new, input_lost, label_new, label_lost) in enumerate(dataloader, 0):\n\n if opt.cuda:\n input_new = input_new.cuda()\n input_lost = input_lost.cuda()\n label_new = label_new.cuda()\n label_lost = label_lost.cuda()\n\n if node_type == \"new\":\n input = Variable(input_new).double()\n target = Variable(label_new).double()\n max_ = max_new\n min_ = min_new\n elif node_type == \"lost\":\n input = Variable(input_lost).double()\n target = Variable(label_lost).double()\n max_ = max_lost\n min_ = min_lost\n\n output = net(input)\n\n # 予測結果とラベルを保存\n os.makedirs(OutputDir + \"/output\", exist_ok=True)\n for batch in range(opt.batchSize):\n np.save(OutputDir + \"/output/pred\" + str(sample_idx.numpy()[batch]), output.detach().numpy()[batch] * (max_ - min_) + min_)\n np.save(OutputDir + \"/output/true\" + str(sample_idx.numpy()[batch]), target[batch].numpy() * (max_ - min_) + min_)\n","sub_path":"Model/prediction_num_of_node/LSTM/utils/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"327047118","text":"from collections import deque\r\n#import sympy.geometry as g\r\nimport Geometry as geo\r\n\r\nMAX_MONSTER_SPEED = 21\r\nMIN_MONSTER_SPEED = 21\r\n\r\n\r\nclass MonsterWay: # todo normal point now tuple with pairs x y\r\n def __init__(self):\r\n self.way = ((1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1),\r\n (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (18, 2), (18, 3), (18, 4),\r\n (18, 5), (18, 6), (18, 7), (18, 8), (18, 9), (18, 10), (17, 10), (16, 10), (15, 10), (14, 10),\r\n (13, 10), (12, 10), (11, 10), (10, 10), (9, 10), (8, 10), (7, 10), (6, 10), (5, 9), (4, 8),\r\n (3, 8), (2, 8), (1, 8), (0, 8), (0, 9), (0, 10), (0, 11), (0, 12), (0, 13), (0, 14), (0, 15),\r\n (0, 16), (0, 17), (1, 18), (2, 20), (2, 21), (3, 22), (4, 23), (5, 24), (6, 25), (7, 26), (8, 27),\r\n (9, 28), (10, 29), (11, 30), (12, 31), (13, 32), (14, 33), (15, 34), (16, 35), (17, 35), (18, 35),\r\n (19, 35), (20, 35), (21, 35), (22, 35), (23, 35), (24, 35), (25, 35), (25, 35), (26, 35),\r\n (27, 35), (28, 35), (29, 35), (30, 35), (31, 35), (32, 35), (33, 35), (34, 35), (35, 35), (36, 35),\r\n (37, 35), (38, 35), (39, 35), (40, 35), (41, 35), (42, 35), (42, 35), (43, 35), (44, 35), (45, 35),\r\n (46, 35), (47, 35), (48, 35), (49, 35), (50, 35), (51, 34), (52, 33), (53, 32), (54, 31), (55, 30),\r\n (56, 29), (57, 28), (58, 27), (59, 26), (60, 25), (61, 25)\r\n )\r\n self.lobby = 2\r\n self.city = len(self.way) - 2\r\n\r\n def in_lobby(self, index):\r\n return index < self.lobby\r\n\r\n def in_city(self, index):\r\n return index > self.city\r\n\r\n def x(self, index):\r\n return self.way[index][0] # todo this safety with processing\r\n\r\n def y(self, index):\r\n return self.way[index][1]\r\n\r\n\r\nclass MonsterWave:\r\n def __init__(self, world, monster_amount, monster_time_interval):\r\n self.monster_way = MonsterWay()\r\n self.monsters_lobby = deque(Monster(world, self, -5, -5) for _ in range(0, monster_amount))\r\n self.monster_time_interval = monster_time_interval\r\n self.monsters_on_map = [] # deque()\r\n self.world = world\r\n self.alive = True\r\n\r\n self.health_on_map = 0\r\n self.monster_wave_health = len(self.monsters_lobby) * 20 + self.health_on_map\r\n\r\n def add_on_map(self):\r\n if self.monsters_lobby and self.world.draw_system.draw_tick % self.monster_time_interval == 0:\r\n self.monsters_on_map.append(self.monsters_lobby.popleft())\r\n\r\n def refresh_on_map(self):\r\n for monster in self.monsters_on_map:\r\n if not monster.alive:\r\n if monster.monster_loot:\r\n self.world.player.monsters_loots.append(monster.monster_loot)\r\n monster.monster_loot = None\r\n self.monsters_on_map.remove(monster)\r\n monster.refresh()\r\n self.health_on_map += max(int(monster.health), 0)\r\n self.monster_wave_health = len(self.monsters_lobby) * 20 + self.health_on_map\r\n self.health_on_map = 0\r\n self.world.player.wave_health = self.monster_wave_health\r\n\r\n def refresh(self):\r\n self.add_on_map()\r\n self.refresh_on_map()\r\n if not (self.monsters_lobby or self.monsters_on_map):\r\n self.alive = False\r\n\r\n\r\nclass MonsterArmor:\r\n def __init__(self, monster, monster_armor):\r\n self.froze = monster_armor[\"Froze\"]\r\n self.fire = monster_armor[\"Fire\"]\r\n self.poison = monster_armor[\"Poison\"]\r\n self.electricity = monster_armor[\"Electricity\"]\r\n self.physical = monster_armor[\"Physical\"]\r\n self.monster = monster\r\n\r\n\r\nclass MonsterLoot:\r\n def __init__(self, monster):\r\n self.monster = monster\r\n self.money = 10\r\n self.citizen_annihilation = 1\r\n self.experience = 5\r\n self.in_city = False\r\n self.available = True\r\n\r\n\r\nclass MonsterEffects:\r\n def __init__(self, monster):\r\n self.froze = 0\r\n self.fire = 0\r\n self.poison = 0\r\n self.electricity = 0\r\n self.slowing = 5\r\n self.direction = 1\r\n self.towers_attacks = []\r\n self.damage = 0\r\n self.monster = monster\r\n\r\n def _effects_collecting(self):\r\n for tower_attack in self.towers_attacks:\r\n electricity = tower_attack.electricity_attack - self.monster.armor.electricity\r\n poison = tower_attack.poison_attack - self.monster.armor.poison\r\n fire = tower_attack.fire_attack - self.monster.armor.fire\r\n froze = tower_attack.froze_attack - self.monster.armor.fire\r\n damage = tower_attack.physical_attack - self.monster.armor.physical\r\n self.slowing += tower_attack.slowing_change\r\n self.direction = tower_attack.direction_change\r\n self.electricity += max(electricity, 0)\r\n self.poison += max(poison, 0)\r\n self.froze += max(froze, 0)\r\n self.fire += max(fire, 0)\r\n self.damage += max(damage, 0)\r\n self.towers_attacks = []\r\n\r\n def _effects_calculation(self):\r\n effcoff = {\"electricity\": self.electricity, \"froze\": self.froze, \"poison\": self.poison, \"fire\": self.fire}\r\n elecoff = {\"electricity\": 0, \"froze\": 0.33, \"poison\": -0.17, \"fire\": -0.13}\r\n fircoff = {\"electricity\": 0.46, \"froze\": -1, \"poison\": 0.08, \"fire\": 0}\r\n frocoff = {\"electricity\": 0.193, \"froze\": 0, \"poison\": 0, \"fire\": -1}\r\n poicoff = {\"electricity\": -0.17, \"froze\": -0.37, \"poison\": 0, \"fire\": -0.3}\r\n slocoff = {\"electricity\": -0.33, \"froze\": 0.83, \"poison\": 0, \"fire\": -0.43}\r\n dmgcoff = {\"electricity\": 0.76, \"froze\": 0.56, \"poison\": 0.86, \"fire\": 0.63}\r\n electricity = sum(map(lambda x, y: x * y, effcoff.values(), elecoff.values()))\r\n fire = sum(map(lambda x, y: x * y, effcoff.values(), fircoff.values()))\r\n froze = sum(map(lambda x, y: x * y, effcoff.values(), frocoff.values()))\r\n poison = sum(map(lambda x, y: x * y, effcoff.values(), poicoff.values()))\r\n slowing = sum(map(lambda x, y: x * y, effcoff.values(), slocoff.values()))\r\n self.slowing += slowing\r\n self.electricity = max(self.electricity + electricity, 0)\r\n self.poison = max(self.poison + poison, 0)\r\n self.froze = max(self.froze + froze, 0)\r\n self.fire = max(self.fire + fire, 0)\r\n effcoff = {\"electricity\": self.electricity, \"froze\": self.froze, \"poison\": self.poison, \"fire\": self.fire}\r\n damage = sum(map(lambda x, y: x * y, effcoff.values(), dmgcoff.values()))\r\n self.damage += damage\r\n\r\n def _tick_effects_update(self):\r\n self.damage = 0\r\n self.poison *= 0.88\r\n self.froze *= 0.67\r\n self.fire *= 0.44\r\n self.electricity *= 0.2\r\n self.slowing *= 0.76\r\n if self.monster.world.draw_system.draw_tick % 200 == 0:\r\n self.direction = 1\r\n else:\r\n self.direction = self.direction\r\n\r\n def refresh_effects(self):\r\n self._effects_collecting()\r\n self._effects_calculation()\r\n self.monster.health -= self.damage\r\n\r\n self.monster.speed_now = self.monster.speed_base - int(self.slowing + 0.5) # TODO make armotization for this\r\n self._tick_effects_update()\r\n\r\n\r\nclass Monster:\r\n def __init__(self, world, wave, x, y):\r\n self.world = world\r\n self.wave = wave\r\n self.x = x\r\n self.y = y\r\n self.width = 2\r\n self.height = 2\r\n self.polygon = self._init_polygon()\r\n self._speed_base = None\r\n self._speed_now = None\r\n self.speed_base = 5\r\n self.speed_now = self._speed_base\r\n self.health = 20\r\n self.monster_loot = MonsterLoot(self)\r\n self.lived_ticks = 0\r\n self.alive = True\r\n self.armor = MonsterArmor(self, {\"Froze\": 0, \"Fire\": 0, \"Poison\": 0, \"Electricity\": 0, \"Physical\": 0})\r\n self.texture = \"M\"\r\n self.effects = MonsterEffects(self)\r\n self.type = \"all\"\r\n self.ai_points = 0\r\n self.way_position = 0\r\n self.monster_way = wave.monster_way\r\n self.step = 1\r\n # in future it resizing objects configure\r\n\r\n @property\r\n def speed_base(self):\r\n return self._speed_base\r\n\r\n @speed_base.setter\r\n def speed_base(self, speed_base):\r\n self._speed_base = max(-MIN_MONSTER_SPEED, min(speed_base, MAX_MONSTER_SPEED - 1))\r\n\r\n @property\r\n def speed_now(self):\r\n return self._speed_now\r\n\r\n @speed_now.setter\r\n def speed_now(self, speed_now):\r\n self._speed_now = min(MIN_MONSTER_SPEED + MAX_MONSTER_SPEED - 2, max(MAX_MONSTER_SPEED - speed_now, 1))\r\n\r\n def is_can_be_attacked(self, typeof):\r\n return typeof in (\"all\", self.type) and self.alive\r\n\r\n def _init_polygon(self):\r\n x = self.x\r\n y = self.y\r\n w = self.width - 1\r\n h = self.height - 1\r\n return geo.Rectangle(x,y,w,h)#//g.polygon.Polygon(g.Point(x, y), g.Point(x + w, y), g.Point(x + w, y + h), g.Point(x, y + h))\r\n\r\n def refresh(self):\r\n if not self.alive:\r\n return\r\n self.polygon = self._init_polygon()\r\n self.effects.refresh_effects()\r\n self.lived_ticks += 1\r\n self.lived_ticks %= 100\r\n self.refresh_ai()\r\n if self.health < 1:\r\n self.alive = False\r\n self.x = -1\r\n self.y = -1\r\n\r\n def refresh_ai(self):\r\n if self.monster_way.in_city(self.way_position):\r\n self.monster_loot.in_city = True\r\n self.effects.Direction = 0\r\n self.alive = False\r\n if self.world.draw_system.draw_tick % self.speed_now == 0:\r\n self.lived_ticks += 1\r\n self.lived_ticks %= 100\r\n if self.monster_way.in_lobby(self.way_position):\r\n self.effects.Direction = 1\r\n self.move()\r\n\r\n def _movement(self, x, y):\r\n if self.alive:\r\n self.x += x\r\n self.y += y\r\n\r\n def move(self):\r\n self.way_position += self.step * self.effects.direction\r\n self.x = self.monster_way.x(self.way_position)\r\n self.y = self.monster_way.y(self.way_position)\r\n\r\n def in_screen(self, window_width, window_height):\r\n return 0 <= self.x <= window_width + self.width and 0 <= self.y <= window_height + self.height and self.alive\r\n\r\n def effect_on_tick(self):\r\n pass\r\n","sub_path":"Monsters.py","file_name":"Monsters.py","file_ext":"py","file_size_in_byte":10604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"42124548","text":"import sys\nsys.path.append('../')\nfrom utilities.utils import ModelUtils\nfrom logger.logger import Logger\nfrom db_operations.sqlite_db import SqliteDbHandler\nfrom utilities.utils import FileUtils\nimport os\nfrom joblib import dump, load\nfrom datetime import datetime\nimport more_itertools\nimport streamlit as st\nimport pandas as pd\nimport numpy as np\n\n\n\nclass Inference_Controller:\n def __init__(self,inference_db_path,preprocessor):\n self._inference_db_path = inference_db_path\n self._time_created = datetime.now()\n self._logger = Logger(f'inferencing_logs_{self._time_created.date()}_{self._time_created.strftime(\"%H%M%S\")}.log')\n self._db_handler = SqliteDbHandler(self._logger,self._inference_db_path,'inferencing_db')\n self._model_utils = ModelUtils(self._logger)\n self._preprocessor = preprocessor\n\n def _load_data(self):\n self._logger.log('Inference: Started Inferencing')\n self._logger.log('Inference: Loading data for Inferencing')\n try: \n self._db_handler.create_db_connection()\n df = self._db_handler.get_data_from_db('thyroid_inferencing')\n return df\n except Exception as e:\n self._logger.log(f'Inference: Exception occured while Loading data for Inferencing, {str(e)}')\n\n def _cluster_data(self,df):\n\n clustering_model_name_with_extension = self._all_models[0]\n model_name_only = clustering_model_name_with_extension.split('.')[0]\n clustering_model = self._model_utils.load_model(model_name_only)\n \n clusters = clustering_model.predict(df)\n df['clusters']=clusters\n self._clusters=df['clusters'].unique()\n\n return df\n \n def _get_model_for_clusters(self):\n \n model_repository = {}\n for cluster in self._clusters:\n model_repository[cluster]=self._model_utils.find_model_for_cluster(cluster)\n \n return model_repository\n\n def _get_label_encoder(self):\n return self._preprocessor.label_encoder\n\n def _make_predictions_for_clusters(self,df):\n\n label_encoder = self._get_label_encoder()\n all_models = self._get_model_for_clusters()\n\n final_predictions = pd.DataFrame()\n for cluster in self._clusters:\n current_cluster_data = df[df['clusters']==cluster]\n current_cluster_data = current_cluster_data.drop(['clusters'],axis=1)\n model = all_models.get(cluster)\n predicted_labels = model.predict(current_cluster_data)\n predicted_labels = predicted_labels.astype(int)\n predicted_labels = label_encoder.inverse_transform(predicted_labels)\n current_cluster_data['predictions'] = predicted_labels\n final_predictions = pd.concat([final_predictions,current_cluster_data])\n \n return final_predictions\n\n\n\n def run_inferencing(self):\n with st.spinner(\"Loading validated data from DB...\"):\n df = self._load_data()\n\n with st.spinner(\"Loading models from repository...\"):\n # self._all_models = list(more_itertools.flatten(self._model_utils.get_all_models_info()))\n self._all_models = self._model_utils.get_all_models_info()\n\n with st.spinner('Clustering data'):\n df = self._cluster_data(df)\n\n with st.spinner('Getting Predictions..'):\n st.info('Predictions:')\n final_predictions = self._make_predictions_for_clusters(df)\n st.write(final_predictions)\n\n with st.spinner('Writing Predictions to file..'):\n # file_utils = FileUtils(self._logger,os.path.join('.','data'))\n # predictions_save_path = file_utils.create('final_predictions',delete_before_creation=True)\n # predictions_save_path= os.path.join(predictions_save_path,'predictions.csv')\n final_predictions.to_csv('./data/final_predictions/predictions.csv',index=False)\n\n","sub_path":"Machine_Learning_Projects/Thyroid_Detection/inference/inference_controller.py","file_name":"inference_controller.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"547401003","text":"#!/usr/bin/env python\nimport cgi\nimport cgitb\ncgitb.enable()\nimport os\nimport datetime\n\n\ndefault = \"No Value Present\"\n\n\nprint(\"Content-Type: text/html\")\nprint(\"\")\n\nthis_day = datetime.datetime.today()\n\nbody = \"\"\"\n\nLab 1 - CGI experiments by Dennis Lee\n\n\n
Hey there, this page has been generated by {software}, running {script}.
\n
Today is {month} {date}, {year}.
\n
This page was requested by IP Address {client_ip}.
\n\n\"\"\".format(\n software=os.environ.get('SERVER_SOFTWARE', default),\n script=os.environ.get('SCRIPT_NAME', default),\n month=this_day.strftime(\"%B\"),\n date=this_day.day,\n year=this_day.year,\n client_ip=os.environ.get('REMOTE_ADDR')\n)\nprint(body)\n","sub_path":"cgi-bin/cgi_2.py","file_name":"cgi_2.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"614951023","text":"import numpy as np\n\n\nif __name__ == \"__main__\":\n X = np.array([[1, 2, 3], [5, 2, 1], [8, 3, 1], [5, 2, 1]])\n\n match = [5, 2, 1]\n\n\n a = [x for x in a if x != [1,1]]\n\n \n # print(X.shape)\n # exit()\n\n # # Get sum squares err\n # X_hat = np.sum(np.mean(X_test)) / n_samples\n # # X_means = [np.mean(x_mat) for x_mat in X_test]\n # reconstruct_X_test = model.inverse_transform(W_test)\n\n # SS_err = np.sum(X_test - reconstruct_X_test)**2\n # SS_tot = np.sum(X_test - X_hat)**2\n\n # fuv = SS_err / SS_tot\n # print(fuv)\n\n # test_error = _beta_divergence(X_test, W_test, model.components_, 'frobenius', square_root=False)\n # k_error_dict[i].append(test_error)\n\n # print(\"rep: \", rep, \" k: \", i, \"mean test error: \", np.mean(k_error_dict[i]))\n","sub_path":"data_analysis_notebook/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"477585878","text":"'''\nCreated on Oct 19, 2011\n\n@author: steger, jozsef\n@organization: ELTE\n@contact: steger@complex.elte.hu\n'''\nfrom DataError import UnitError\n\nclass UnitManager(object):\n '''\n @summary: the unit container\n \n @note: The relationship between various unit, describing the derivation paths are not stored in this model,\n because this information can be inferred from the dimension derivations, represented in the L{DimensionManager}.\n @note: Units that are formed by prepending a unit prefix (L{Prefix}) are dealt as a L{DerivedUnit}.\n \n @ivar units: container of known units\n @type units: dict(str: L{Unit})\n @ivar conversionpaths: is a map of operations to carry out from a unit to get a different unit\n @type conversionpaths: dict((L{Unit}, L{Unit}): (callable, args))\n @ivar basins: indicates the derivatives of a basic unit\n @type basins: dict(L{BasicUnit}: set(L{Unit}))\n @ivar duplicatesymbols: collection of unit symbols, which more than one unit may bare\n @type duplicatesymbols: set(str)\n '''\n\n class Unit(object):\n '''\n @summary: common skeleton of all units\n @ivar manager: reference to the unit manager\n @type manager: L{UnitManager}\n @ivar reference: unique reference of the unit\n @ivar symbol: short form of the unit\n @type symbol: str\n '''\n def __init__(self, manager, reference, symbol, ancestor):\n '''\n @summary: bind and store common information of the unit\n @param manager: the unit manager\n @type manager: L{UnitManager}\n @param reference: a unique identifier\n @param symbol: short human readable representation of the unit\n @type symbol: str\n @param ancestor: the ancestor of this unit is deriving from\n @type ancestor: L{Unit}\n '''\n self._data = (manager, reference, symbol)\n self._ancestor = ancestor\n @property\n def manager(self):\n return self._data[0]\n @property\n def reference(self):\n return self._data[1]\n @property\n def symbol(self):\n return self._data[2]\n def __str__(self):\n return self.symbol\n def __eq__(self, u):\n return self._data == u._data\n\n class BasicUnit(Unit):\n '''\n @summary: a unit axiom\n '''\n def __init__(self, manager, reference, symbol):\n '''\n @summary: constructor\n A BasicUnit is an instance of either set of BaseUnit, ProductUnit and PowerUnit as of the information model.\n @param manager: a reference to the unit manager\n @type manager: L{UnitManager} \n @param reference: the reference to the unit\n @param symbol: an abbreviation for the unit\n @type symbol: str\n '''\n UnitManager.Unit.__init__(self, manager, reference, symbol, None)\n \n class DerivedUnit(Unit):\n '''\n @summary: a unit deriving from various known units\n '''\n def __init__(self, manager, reference, symbol, ancestor):\n '''\n @summary: constructor\n A DerivedUnit is an instance of either set of LinearTransformedUnit and RegexpScaledUnit as of the information model.\n Also units that have any unit prefix fall in this set.\n @param manager: a reference to the unit manager\n @type manager: L{UnitManager} \n @param reference: the reference to the unit\n @param symbol: an abbreviation for the unit\n @type symbol: str\n @param ancestor: the neighbor unit, whose derivative this instance is.\n @type ancestor: L{Unit}\n '''\n UnitManager.Unit.__init__(self, manager, reference, symbol, ancestor)\n \n \n def __init__(self):\n '''\n @summary: constructor\n '''\n self.units = {}\n self.conversionpaths = {}\n self.basins = {}\n self.duplicatesymbols = set()\n \n def __contains__(self, item):\n '''\n @summary: check the existence of a unit\n @param item: a unit or its symbol\n @type item: L{Unit} or str\n @return: True if the unit is known by the L{UnitManager}\n @rtype: bool\n @raise L{UnitError}: Wrong item type\n '''\n units = set(self.units.values())\n if isinstance(item, self.Unit):\n return item in units\n elif isinstance(item, str):\n for unit in units:\n if unit.symbol == item:\n return True\n return False\n else:\n raise UnitError(\"Wrong item type %s\" % item)\n \n def __len__(self):\n '''\n @summary: the number of units known by the L{UnitManager}\n @return: the number of units known by the L{UnitManager}\n @rtype: int\n '''\n return len(self.units)\n\n @staticmethod\n def intORfloat(x):\n '''\n @summary: a conversion helper to read out a value as a number\n @param x: a number\n @type x: str\n @return: the number converted to integer or floating point decimal\n @rtype: int or float\n '''\n if isinstance(x, str):\n try:\n return int(x)\n except ValueError:\n return float(x)\n else:\n return float(x)\n\n def __getitem__(self, reference):\n '''\n @summary: look up the unit in the L{UnitManager} using its reference\n @param reference: the reference to the unit\n @return: the unit found\n @rtype: L{Unit}\n @raise L{UnitError}: Unit with reference not found\n '''\n if self.units.has_key(reference):\n return self.units[reference]\n raise UnitError(\"Unit with reference %s not found\" % reference)\n\n def newBasicUnit(self, reference, symbol):\n '''\n @summary: generate a new basic unit\n @param reference: the reference to the unit\n @param symbol: a short form of the unit\n @type symbol: str\n @return: the new unit\n @rtype: L{BasicUnit}\n @raise L{UnitError}: Unit with reference exists\n '''\n if self.units.has_key(reference): \n raise UnitError(\"Unit with reference %s exists\" % reference)\n if UnitManager.__contains__(self, symbol):\n self.duplicatesymbols.add(symbol)\n unit = self.BasicUnit(self, reference, symbol)\n self.units[reference] = unit\n self.basins[unit] = set([unit])\n self.__dict__[reference] = unit\n return unit\n\n def addLinearTransformedUnit(self, reference, symbol, derivedfrom, scale, offset = 0):\n '''\n @summary: generate a derived unit\n @param reference: the reference to the unit\n @param symbol: a short form of the unit\n @type symbol: str\n @param derivedfrom: the neighbor unit\n @type derivedfrom: L{Unit}\n @param scale: scaling factor for the linear transformation\n @type scale: float\n @param offset: the shift in the linear transformation, defaults to 0\n @type offset: float \n @return: the new unit\n @rtype: L{DerivedUnit}\n @raise L{UnitError}: Wrong type of derivedfrom / Unit not found / Unit with reference exists / Cannot extend basin with unit, because Unit not found\n '''\n if not isinstance(derivedfrom, self.Unit):\n raise UnitError(\"Wrong type of derivedfrom %s\" % derivedfrom)\n if not UnitManager.__contains__(self, str(derivedfrom)):\n raise UnitError(\"Unit %s not found\" % derivedfrom)\n if self.units.has_key(reference): \n raise UnitError(\"Unit with reference %s exists\" % reference)\n unit = self.DerivedUnit(self, reference, symbol, derivedfrom)\n basic = derivedfrom\n while basic._ancestor:\n basic = basic._ancestor\n if not self.basins.has_key(basic):\n raise UnitError(\"Cannot extend basin with unit %s, because Unit %s not found\" % (unit, basic))\n if UnitManager.__contains__(self, symbol):\n self.duplicatesymbols.add(symbol)\n self.units[reference] = unit\n self.conversionpaths[(unit, derivedfrom)] = (self.op_lt_forward, (scale, offset))\n self.conversionpaths[(derivedfrom, unit)] = (self.op_lt_inverse, (scale, offset))\n self.basins[basic].add(unit)\n self.__dict__[reference] = unit\n return unit\n\n def addRegexpTransformedUnit(self, reference, symbol, derivedfrom, expr_forward, expr_inverse):\n '''\n @summary: generate a derived unit\n @param reference: the reference to the unit\n @param symbol: a short form of the unit\n @type symbol: str\n @param derivedfrom: the neighbor unit\n @type derivedfrom: L{Unit}\n @param expr_forward: the expression driving the forward transformation\n @type expr_forward: str\n @param expr_inverse: the expression driving the inverse transformation\n @type expr_inverse: str\n @return: the new unit\n @rtype: L{DerivedUnit}\n @raise L{UnitError}: Wrong type of derivedfrom / Unit not found / Unit with reference exists / Cannot extend basin with unit, because Unit not found\n '''\n if not isinstance(derivedfrom, self.Unit):\n raise UnitError(\"Wrong type of derivedfrom %s\" % derivedfrom)\n if not UnitManager.__contains__(self, str(derivedfrom)):\n raise UnitError(\"Unit %s not found\" % derivedfrom)\n if self.units.has_key(reference): \n raise UnitError(\"Unit with reference %s exists\" % reference)\n unit = self.DerivedUnit(self, reference, symbol, derivedfrom)\n basic = derivedfrom\n while basic._ancestor:\n basic = basic._ancestor\n if not self.basins.has_key(basic):\n raise UnitError(\"Cannot extend basin with unit %s, because Unit %s not found\" % (unit, basic))\n if UnitManager.__contains__(self, symbol):\n self.duplicatesymbols.add(symbol)\n self.units[reference] = unit\n self.conversionpaths[(unit, derivedfrom)] = (self.op_rt_forward, expr_forward)\n self.conversionpaths[(derivedfrom, unit)] = (self.op_rt_inverse, expr_inverse)\n self.basins[basic].add(unit)\n self.__dict__[reference] = unit\n return unit\n\n def getBasinByUnit(self, unit):\n '''\n @summary: return the set of units, which are compatible with a given unit\n @param unit: the unit to look up\n @type unit: L{Unit}\n @return: the set of compatible units\n @rtype: set(L{Unit})\n @raise L{UnitError}: not found\n '''\n for basin in self.basins.values():\n if unit in basin:\n return basin\n raise UnitError(\"Basin for unit %s not found\" % unit)\n\n def getBasinByReference(self, reference):\n '''\n @summary: look up the compatible units of a given unit with the calling reference\n @param reference:\n @return: the set of compatible units\n @rtype: set(L{Unit})\n @raise L{UnitError}: not found\n '''\n try:\n unit = self[reference]\n return self.getBasinByUnit(unit)\n except UnitError:\n raise UnitError(\"Basin for unit reference %s not found\" % reference)\n\n def op_lt_forward(self, value, so):\n (scale, offset) = so\n def op(value):\n return scale * self.intORfloat( value ) + offset\n if isinstance(value, list):\n return map(lambda x: op(x), value)\n return op(value)\n\n def op_lt_inverse(self, value, so):\n (scale, offset) = so\n def op(value):\n return (self.intORfloat( value ) - offset) / float(scale)\n if isinstance(value, list):\n return map(lambda x: op(x), value)\n return op(value)\n\n def op_rt_forward(self, value, expression):\n def op(value):\n raise UnitError(\"not implemented\")\n if isinstance(value, list):\n return map(lambda x: op(x), value)\n return op(value)\n\n op_rt_inverse = op_rt_forward\n\n def convert(self, value, from_unit, to_unit):\n '''\n @summary: convert a value of one unit to the other\n @param value: input value in from_unit\n @param from_unit: the original unit of the input value\n @type from_unit: L{Unit}\n @param to_unit: the requested new unit\n @type to_unit: L{Unit}\n @raise L{UnitError}: unknown unit / incompatible units\n '''\n if not UnitManager.__contains__(self, str(from_unit)):\n raise UnitError(\"Unknown from_unit\")\n if not UnitManager.__contains__(self, str(to_unit)):\n raise UnitError(\"Unknown to_unit\")\n if from_unit == to_unit:\n return value\n\n while from_unit._ancestor:\n op, oparg = self.conversionpaths[(from_unit, from_unit._ancestor)]\n value = op(value, oparg)\n from_unit = from_unit._ancestor\n heap = []\n while to_unit._ancestor:\n op, oparg = self.conversionpaths[(to_unit._ancestor, to_unit)]\n heap.append((op, oparg))\n to_unit = to_unit._ancestor\n if from_unit != to_unit:\n raise UnitError(\"Different base units %s %s\" % (from_unit, to_unit))\n while len(heap):\n op, oparg = heap.pop(0)\n value = op(value, oparg)\n return value\n\n","sub_path":"Monitoring/MonitoringService/DataProcessing/Unit.py","file_name":"Unit.py","file_ext":"py","file_size_in_byte":13571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"211806979","text":"#! /usr/bin/env python\n\nT = int(input())\n\nfor t in range(1, T+1):\n n, s = input().split()\n n = int(n)\n ss = [ord(x) - ord('0') for x in s]\n need = 0\n now = 0\n for i, x in enumerate(ss):\n if now < i:\n need += i - now\n now = i\n now += x\n\n print(\"Case #{}: {}\".format(t, need))\n \n","sub_path":"solutions_5639104758808576_0/Python/LeoMao/pa.py","file_name":"pa.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"292755740","text":"import csv\nimport ConfigParser\nimport glob, os\n\t\nconfig = ConfigParser.RawConfigParser()\n\t\ntry: \n\tproperties = config.read('config.ini')\n\trows = int(config.get('CONFIGURATION', 'number_of_rows').strip('\"'))\n\tposition = int(config.get('CONFIGURATION', 'position_to_be_corrected').strip('\"'))\n\tdelimiter = config.get('CONFIGURATION', 'delimiter').strip('\"')\n\tsubstitute = config.get('CONFIGURATION', 'substitute').strip('\"')\n\nexcept (ConfigParser.NoSectionError, ConfigParser.NoOptionError):\n\trows = 20\n\tposition = 5\n\tdelimiter = ';'\n\tsubstitute = ''\n\nos.chdir(\"files/\")\nfor f in glob.glob(\"*.csv\"):\n\tif \"modified\" not in f:\n\t\tinput = open(f, 'rb')\n\t\tfile = csv.reader(input, delimiter=delimiter)\n\t\t\n\t\ttext = []\n\t\tfor row in file:\t\n\t\t\tnew_row = []\n\t\t\t\n\t\t\tif(len(row) > rows):\n\t\t\t\t\n\t\t\t\tdifference = len(row) - rows;\n\t\t\t\tnew_row = row[0:position-1]\n\t\t\t\tdescription = row[position-1:position+difference]\n\t\t\t\tdescription = substitute.join(description)\n\t\t\t\tnew_row.append(description)\n\t\t\t\tnew_row.extend(row[position+difference:])\n\t\t\t\ttext.append(new_row)\n\t\t\telse:\n\t\t\t\ttext.append(row)\n\n\t\twith open(os.path.splitext(os.path.basename(f))[0] + '_modified.csv', 'wb') as output:\n\t\t\tdestination = csv.writer(output, delimiter=';')\n\t\t\tdestination.writerows(text)\n\t\t\t\n\t\tinput.close()\n\t\toutput.close()","sub_path":"CSVCorrectorBETA.py","file_name":"CSVCorrectorBETA.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"398932856","text":"# =============================================================================\n'''\nQuick description of the file\n'''\n# =============================================================================\n__author__ = 'Simon Lassourreuille & Loizel Antoine'\n__version__ = ''\n__date__ = '26/01/2017'\n__email__ = 'simon.lassourreuille@etu.u-bordeaux.fr & antoine.loizel@etu.u-bordeaux.fr'\n__status__ = 'TD'\n# =============================================================================\nimport socket\nimport threading\nimport tkinter as tk\nfrom cmath import rect\nfrom math import pi, cos, sqrt\n\nfrom PIL import Image, ImageTk\n\nimport network\nfrom Main import *\n\n\n# =============================================================================\ndef load_image(path, resize=None):\n image = Image.open(path)\n if resize:\n image.thumbnail(resize, Image.ANTIALIAS)\n return ImageTk.PhotoImage(image)\n\n# =============================================================================\nclass Game(tk.Tk):\n def __init__(self, p = Plateau(5, 7), online=True):\n # Init of tk window\n tk.Tk.__init__(self)\n self.title(\"You Lost The Game\")\n\n # Attributes\n self.p = p\n self.width = 40\n self.player = 0\n self.__hexagons = {}\n self.__images = {}\n self.__tokens = []\n self.__victory = []\n self.finished = False\n\n # Init of tk canvas\n self.canvas = Workspace(self, p.hauteur, self.width)\n self.canvas.pack(expand=True, fill='both')\n self.canvas['height'] = self.p.hauteur * self.width * 1.7\n self.canvas['width'] = (2 * self.p.largeur + self.p.hauteur // 2) * 1.08 * self.width\n\n # Images init\n size = (self.width*2,self.width*2)\n for i in range(3):\n if i > 0:\n self.__images[i, '_'] = load_image(\"Sprites/Hexagon {} _.png\".format(i), size)\n if i < 2:\n self.__tokens.append(load_image(\"Sprites/Token {}.png\".format(i),(self.width,self.width)))\n self.__victory.append(load_image(\"Sprites/Victory {}.png\".format(i+1)))\n self.__images[i] = load_image(\"Sprites/Hexagon {}.png\".format(i), size)\n\n # Bindings\n self.bind('', self.on_click)\n self.bind('', self.test)\n self.bind('', self.replay)\n self.protocol(\"WM_DELETE_WINDOW\", self.on_closing)\n\n # Networking\n if online:\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # self.socket.connect(('192.168.173.1', network.PORT))\n self.socket.connect(('127.0.0.1', network.PORT))\n print(\" Connected to the server \".center(80, \"=\"))\n thread = threading.Thread(target=self.server_input, daemon=True)\n thread.start()\n self.token = 0\n\n print(\"=\" * 30 + \" Game Started \" + \"=\" * 30)\n self.reset()\n self.display()\n self.mainloop()\n\n # -------------------------------------------------------------------------\n def server_input(self):\n rest = bytes()\n while True:\n try:\n # blocks\n (msgs, rest) = network.recv_msgs(self.socket, rest)\n for msg in msgs:\n self.handle_requests(msg)\n except ConnectionError:\n print('Connection to server closed')\n self.socket.close()\n break\n\n # -------------------------------------------------------------------------\n def handle_requests(self, request):\n print(\"received request : \", request)\n eval(request)\n\n # -------------------------------------------------------------------------\n def reset(self):\n # Reset the Plateau\n self.finished = False\n self.p = Plateau(self.p.largeur, self.p.hauteur)\n self.p[0].valeur = NOIR\n self.p[-1].valeur = NOIR\n self.p[0, self.p.largeur - 1].valeur = BLANC\n self.p[self.p.hauteur - 1, 0].valeur = BLANC\n self.token = 0\n self.display()\n self.random()\n\n # -------------------------------------------------------------------------\n def check_victory(self):\n if (not self.p.jouables(NOIR)) or (not self.p.jouables(BLANC)):\n if self.p.jouables(NOIR):\n self.p.jouables(NOIR)[0].valeur = NOIR\n elif self.p.jouables(BLANC):\n self.p.jouables(BLANC)[0].valeur = BLANC\n self.display()\n if len(self.p.libres) > 0:\n self.after(1750, self.check_victory)\n else :\n self.on_game_end()\n\n # -------------------------------------------------------------------------\n def on_game_end(self):\n self.finished = True\n scores = [len(list(filter(lambda x: x.valeur == color, self.p.configuration))) for color in (BLANC, NOIR)]\n winner = 0 if scores[0] > scores[1] else 1\n self.canvas.create_image(self.winfo_width() * 0.5, self.winfo_height() * 0.5, image=self.__victory[winner])\n\n # -------------------------------------------------------------------------\n def replay(self, unused_ev):\n if self.finished:\n network.send_msg(self.socket, \"replay\")\n\n # ------------------------------------------------------------------------\n def random(self):\n if self.token == self.player and self.p.jouables([BLANC,NOIR][self.player]):\n cell = self.select(self.p.jouables([BLANC,NOIR][self.player]))\n i,j = self.p.pos2coord(cell.position)\n network.send_msg(self.socket, \"click {} {}\".format(i, j))\n self.check_victory()\n self.after(75, self.random)\n\n def select(self, jouables):\n color = [NOIR, BLANC][self.player]\n best_cell, score = None, -1\n for cell in jouables:\n if cell.force(color) >= score:\n score = cell.force(color)\n best_cell = cell\n return best_cell\n\n # ------------------------------------------------------------------------\n def on_closing(self):\n # Some code\n print(\"\\n\" + \"=\" * 31 + \" Game Ended \" + \"=\" * 31)\n self.destroy()\n\n # -------------------------------------------------------------------------\n def __getitem__(self, item):\n return self.__hexagons.__getitem__(item)\n\n # -------------------------------------------------------------------------\n def __setitem__(self, key, value):\n self.__hexagons.__setitem__(key, value)\n\n # -------------------------------------------------------------------------\n def play(self, i, j, color=None):\n color = [BLANC, NOIR][self.token] if color == None else color\n self.p[i, j].valeur = color\n for cell in self.p[i, j].voisins:\n if cell.valeur != VIDE and cell.valeur != color:\n cell.valeur = color\n self.display()\n self.check_victory()\n\n # -------------------------------------------------------------------------\n def test(self, ev):\n x = self.winfo_pointerx() - self.winfo_rootx()\n y = self.winfo_pointery() - self.winfo_rooty()\n for (i, j), hex in self.__hexagons.items():\n if hex.enter(x, y):\n pass\n\n # -------------------------------------------------------------------------\n def on_click(self, ev):\n print(\"Player :\", self.player, \"Token :\", self.token)\n for (i, j), hex in self.__hexagons.items():\n if hex.enter(ev.x, ev.y) and self.p[i, j].estAccessible([BLANC,NOIR][self.player]):\n network.send_msg(self.socket, \"click {} {}\".format(i, j))\n\n # -------------------------------------------------------------------------\n def display(self):\n self.canvas.delete(\"all\")\n\n self.canvas.create_image(self.width/2, self.width/1.8, image=self.__tokens[self.token])\n for x in self.p.configuration:\n i,j = self.p.pos2coord(x.position)\n p = self.canvas.coord2pixels((i, j),\n origin=((self.p.hauteur // 2) * 2 * self.width) * 1J + self.width)\n self[i, j] = Hexagon(self.width, int(p.real), int(p.imag))\n index = {VIDE: 0, BLANC: 1, NOIR: 2}[self.p[i, j].valeur]\n image = self.__images[index]\n self.canvas.create_image(p.real, p.imag, image=image, tags=(\"%s,%s\") % (i, j))\n # if True :\n # self.canvas.create_text(p.real, p.imag, text = str((i,j)))\n\n# =============================================================================\ndef create_complex(create):\n \" Décorateur pour permettre l'utilisation de complexes comme coordonnées \"\n def decorator(*args, **kwargs):\n newargs = []\n for element in args:\n if type(element) is complex:\n newargs += [element.real] + [element.imag]\n else:\n newargs.append(element)\n create(*newargs, **kwargs)\n\n return decorator\n# =============================================================================\n\nclass Workspace(tk.Canvas):\n def __init__(self, master, h, w, *args, **kwargs):\n tk.Canvas.__init__(self, master, *args, bg='#FFFFFF', **kwargs)\n self.create_polygon = create_complex(self.create_polygon)\n self.create_line = create_complex(self.create_line)\n self.board_height = h\n self.hexagon_width = w\n\n # -------------------------------------------------------------------------\n @create_complex\n def create_hexagon(self, width, x, y=None, angle = pi / 6):\n if y is None: x, y = x.real, x.imag\n points = []\n for i in range(6):\n points.append(x + y * 1j + rect(width, angle + i * (pi / 3)))\n self.create_polygon(*points, fill='white', outline='black')\n\n # -------------------------------------------------------------------------\n def coord2pixels(self, coords, origin = 50 + 200 * 1J):\n v = [rect(self.hexagon_width, pi / 6 + i * (pi / 3)) for i in range(6)]\n k = v[-1] + v[-2] if (coords[0] - self.board_height // 2) <= 0 else v[0] + v[1]\n return origin + coords[1] * (v[0] + v[-1]) + abs(coords[0] - self.board_height // 2) * k\n # -------------------------------------------------------------------------\n\n# =============================================================================\nclass Hexagon(object):\n id = 0\n\n def __init__(self, width, x, y, tag = ''):\n \"\"\" Stocke les coordonnées et dimensions d'un Hexagone\"\"\"\n self.tag = tag if tag else str(Hexagon.id)\n Hexagon.id += 1\n self.width = width\n self.x, self.y = x, y\n\n # -------------------------------------------------------------------------\n def enter(self, x, y):\n p = abs(self.x - x) + abs(self.y - y) * 1j\n if sqrt(p.real ** 2 + p.imag ** 2) > self.width:\n return False\n # |- - _ _\n # | - - _ _\n # | triangle - - _ _\n # | - - _ _\n # | |\n # | |\n # | Rectangle | height\n # | |\n # | ___________width_____________ |\n width = self.width * cos(pi / 6)\n height = sqrt(self.width ** 2 - width ** 2)\n # First : rectangle check\n if p.real < width and p.imag < height:\n return True\n # Second : triangle check\n p0 = 0 + height * 1j\n p1 = width + height * 1j\n p2 = 0 + self.width * 1j\n Area = 0.5 * (-p1.imag * p2.real + p0.imag * (-p1.real + p2.real)\n + p0.real * (p1.imag - p2.imag) + p1.real * p2.imag)\n s = 1 / (2 * Area) * (p0.imag * p2.real - p0.real * p2.imag +\n (p2.imag - p0.imag) * p.real + (p0.real - p2.real) * p.imag)\n t = 1 / (2 * Area) * (p0.real * p1.imag - p0.imag * p1.real +\n (p0.imag - p1.imag) * p.real + (p1.real - p0.real) * p.imag)\n\n if s > 0 and t > 0 and 1 - s - t > 0:\n return True\n return False\n # -------------------------------------------------------------------------\n\n\nif __name__ == '__main__':\n game = Game()\n","sub_path":"Random.py","file_name":"Random.py","file_ext":"py","file_size_in_byte":12214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"377269458","text":"from PIL import Image\nimport tensorflow as tf\nimport numpy as np\nimport glob\n\nflags = tf.app.flags\nflags.DEFINE_string('img_dir', '/home/plantvillage/Dropbox/Object_Detection/warehouse/Cassava/images/cassava_dashboard/cassava_capture/unsorted_images_backup', 'Path to the directory of images')\nFLAGS = flags.FLAGS\n\n\nimg_dir = FLAGS.img_dir\ni = 0\nj = 0\n# Read in images using Pillow\nfor img_path in glob.glob(img_dir + '*'):\n j+=1\n for second_img_path in glob.glob(img_dir + '*'):\n if img_path != second_img_path:\n if i % 100 == 0:\n print('Inside loop: %d\\tOutside loop: %d' % (i, j))\n i+=1\n image = Image.open(img_path)\n comp_image = Image.open(second_img_path)\n\n (comp_img_width, comp_img_height) = comp_image.size\n comp_image_np = np.array(comp_image.getdata()).reshape(\n (comp_img_width, comp_img_height, 3)).astype(np.uint8)\n\n # Convert image into numpy array\n (im_width, im_height) = image.size\n image_np = np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n # Look at all columns and all channels of a single row\n row = 0\n comp_row = comp_image_np[row,:,:]\n og_row = image_np[row, :, :]\n\n if np.array_equal(og_row, comp_row):\n print('Found Duplicate!!')\n print('First image:' + img_path)\n print('Second image:' + second_img_path)","sub_path":"tools/check_exact_duplicates.py","file_name":"check_exact_duplicates.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"194863608","text":"import time\nfrom typing import Set, Optional, Sequence, Tuple, Dict\nfrom dataclasses import dataclass, field\n\nfrom model.specs import (\n VALIDATOR_REGISTRY_LIMIT,\n ValidatorIndex, Slot,\n BeaconState, Attestation, SignedBeaconBlock,\n)\nfrom model.validatorlib import (\n BRValidator, SyncCommitteeBundle\n)\n\nfrom eth2spec.utils.ssz.ssz_typing import Container, List, uint64\n\nlog = False # set to True to receive an avalanche of messages\n\nclass NetworkSetIndex(uint64):\n pass\n\n@dataclass\nclass NetworkSet(object):\n validators: List[ValidatorIndex, VALIDATOR_REGISTRY_LIMIT]\n\n@dataclass\nclass NetworkAttestation(object):\n item: Attestation\n info_sets: List[NetworkSetIndex, VALIDATOR_REGISTRY_LIMIT]\n\n@dataclass\nclass NetworkSyncCommittee(object):\n item: SyncCommitteeBundle\n info_sets: List[NetworkSetIndex, VALIDATOR_REGISTRY_LIMIT]\n\n@dataclass\nclass NetworkBlock(object):\n item: SignedBeaconBlock\n info_sets: List[NetworkSetIndex, VALIDATOR_REGISTRY_LIMIT]\n\n@dataclass\nclass Network(object):\n validators: List[BRValidator, VALIDATOR_REGISTRY_LIMIT]\n sets: List[NetworkSet, VALIDATOR_REGISTRY_LIMIT]\n\n # In a previous implementation, we kept attestations and blocks in the same queue.\n # This was unwieldy. We can extend this easily by adding `Attester/ProposerSlashing`s\n attestations: List[NetworkAttestation, VALIDATOR_REGISTRY_LIMIT] = field(default_factory=list)\n sync_committees: List[SyncCommitteeBundle, VALIDATOR_REGISTRY_LIMIT] = field(default_factory=list)\n blocks: List[NetworkBlock, VALIDATOR_REGISTRY_LIMIT] = field(default_factory=list)\n\n # We have the possibility of malicious validators refusing to propagate messages.\n # Unused so far and untested too.\n malicious: List[ValidatorIndex, VALIDATOR_REGISTRY_LIMIT] = field(default_factory=list)\n\ndef get_all_sets_for_validator(network: Network, validator_index: ValidatorIndex) -> Sequence[NetworkSetIndex]:\n # Return indices of sets to which the validator belongs\n\n return [i for i, s in enumerate(network.sets) if validator_index in s.validators]\n\ndef get_all_sets_for_validators(\n network: Network,\n validator_indices: Sequence[ValidatorIndex]\n) -> Sequence[NetworkSetIndex]:\n # Return indices of sets to which validators in `validator_indices` belong\n\n return [i for i, s in enumerate(network.sets) if len(set(s.validators) & set(validator_indices)) > 0]\n\ndef items_known_by_sets(network: Network, info_sets: Sequence[NetworkSetIndex]) -> Dict[str, Sequence[Container]]:\n # Known network items of network sets `info_sets`\n\n known_attestations = [item for item in network.attestations if len(set(item.info_sets) & info_sets) > 0]\n known_sync_committees = [item for item in network.sync_committees if len(set(item.info_sets) & info_sets) > 0]\n known_blocks = [item for item in network.blocks if len(set(item.info_sets) & info_sets) > 0]\n return {\n \"attestations\": known_attestations,\n \"sync_committees\": known_sync_committees,\n \"blocks\": known_blocks,\n }\n\ndef knowledge_set(network: Network, validator_index: ValidatorIndex) -> Dict[str, Sequence[Container]]:\n # Known network items of validator `validator_index`\n\n info_sets = set(get_all_sets_for_validator(network, validator_index))\n return items_known_by_sets(network, info_sets)\n\ndef knowledge_set_union(\n network: Network,\n validator_indices: Sequence[ValidatorIndex]\n) -> Dict[str, Sequence[Container]]:\n # Known network items of validators in `validator_indices`\n\n info_sets = set(get_all_sets_for_validators(network, validator_indices))\n return items_known_by_sets(network, info_sets)\n\ndef ask_to_check_backlog(network: Network,\n validator_indices: Set[ValidatorIndex]) -> None:\n # Called right after a message (block or attestation) was sent to `validator_indices`\n # Asks validators to check if they can e.g., definitely include attestations in their\n # latest messages or record blocks.\n for validator_index in validator_indices:\n validator = network.validators[validator_index]\n\n # Check if there are pending attestations/blocks that can be recorded\n known_items = knowledge_set(network, validator_index)\n validator.check_backlog(known_items)\n\ndef disseminate_attestations(network: Network, items: Sequence[Tuple[ValidatorIndex, Attestation]]) -> None:\n # We get a set of attestations and disseminate them over the network\n\n # Finding out who receives a new attestation\n broadcast_validators = set()\n for item in items:\n sender = item[0]\n attestation = item[1]\n broadcast_list = get_all_sets_for_validator(network, sender)\n\n # The sender records that they have sent an attestation\n network.validators[sender].log_attestation(attestation)\n\n # Adding the attestation to network items\n networkItem = NetworkAttestation(item=attestation, info_sets=broadcast_list)\n network.attestations.append(networkItem)\n\n # Update list of validators who received a new item\n for info_set_index in broadcast_list:\n broadcast_validators |= set(network.sets[info_set_index].validators)\n\n ask_to_check_backlog(network, broadcast_validators)\n\ndef disseminate_sync_committees(network: Network, items: Sequence[Tuple[ValidatorIndex, SyncCommitteeBundle]]) -> None:\n # We get a set of sync committees and disseminate them over the network\n\n # Finding out who receives a new attestation\n broadcast_validators = set()\n for item in items:\n sender = item[0]\n sc_bundle = item[1]\n broadcast_list = get_all_sets_for_validator(network, sender)\n\n # The sender records that they have sent an attestation\n network.validators[sender].log_sync_committee(sc_bundle)\n\n # Adding the attestation to network items\n networkItem = NetworkSyncCommittee(item=sc_bundle, info_sets=broadcast_list)\n network.sync_committees.append(networkItem)\n\n # Update list of validators who received a new item\n for info_set_index in broadcast_list:\n broadcast_validators |= set(network.sets[info_set_index].validators)\n\n ask_to_check_backlog(network, broadcast_validators)\n\ndef disseminate_block(network: Network,\n sender: ValidatorIndex,\n item: SignedBeaconBlock,\n to_sets: List[NetworkSetIndex, VALIDATOR_REGISTRY_LIMIT] = None) -> None:\n # `sender` disseminates a block to its information sets, i.e., other validators they are peering\n # with.\n\n # Getting all the sets that `sender` belongs to\n broadcast_list = get_all_sets_for_validator(network, sender) if to_sets is None else to_sets\n\n # The validator records that they have sent a block\n network.validators[sender].log_block(item)\n\n # Adding the block to network items\n networkItem = NetworkBlock(item=item, info_sets=broadcast_list)\n network.blocks.append(networkItem)\n\n # A set of all validators who need to update their internals after reception of the block\n broadcast_validators = set()\n for info_set_index in broadcast_list:\n broadcast_validators |= set(network.sets[info_set_index].validators)\n\n ask_to_check_backlog(network, broadcast_validators)\n\ndef update_network(network: Network) -> None:\n # The \"heartbeat\" of the network. When called, items propagate one step further on the network.\n\n # We need to propagate both blocks and attestations\n item_sets = [network.blocks, network.attestations]\n\n # These are the validators who receive a new item (block or attestation)\n broadcast_validators = set()\n\n for item_set in item_sets:\n for item in item_set:\n # For each item, we find the new validators who hear about it for the first time\n # and the validators who already do. Items propagate from validators who know about them.\n known_validators = set()\n for info_set in item.info_sets:\n known_validators = known_validators.union(set(network.sets[info_set].validators))\n\n # When a validator belongs to a set A where the item was propagated AND\n # to a set B where it wasn't, the validator propagates the item to set B\n unknown_sets = [i for i, s in enumerate(network.sets) if i not in item.info_sets]\n for unknown_set in unknown_sets:\n new_validators = set(network.sets[unknown_set].validators)\n for new_validator in new_validators:\n if new_validator in known_validators and new_validator not in network.malicious:\n item.info_sets.append(unknown_set)\n broadcast_validators |= new_validators\n break\n\n ask_to_check_backlog(network, broadcast_validators)\n","sub_path":"notebooks/reorg/beaconrunner/model/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":8842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"151250450","text":"\"\"\"empty message\n\nRevision ID: 283656f60272\nRevises: \nCreate Date: 2018-07-13 19:24:09.979017\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '283656f60272'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('banner',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('banner_name', sa.String(length=250), nullable=False),\n sa.Column('image_url', sa.String(length=250), nullable=False),\n sa.Column('link_url', sa.String(length=250), nullable=False),\n sa.Column('priority', sa.Integer(), nullable=True),\n sa.Column('create_time', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('board',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('board_name', sa.String(length=20), nullable=False),\n sa.Column('create_time', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('cmsrole',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('name', sa.String(length=100), nullable=False),\n sa.Column('desc', sa.String(length=200), nullable=True),\n sa.Column('create_time', sa.DateTime(), nullable=True),\n sa.Column('permissions', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('cmsuser',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('username', sa.String(length=100), nullable=False),\n sa.Column('_password', sa.String(length=1500), nullable=False),\n sa.Column('email', sa.String(length=100), nullable=False),\n sa.Column('join_time', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email')\n )\n op.create_table('front_user',\n sa.Column('id', sa.String(length=100), nullable=False),\n sa.Column('telephone', sa.String(length=12), nullable=True),\n sa.Column('username', sa.String(length=100), nullable=False),\n sa.Column('_password', sa.String(length=1500), nullable=False),\n sa.Column('email', sa.String(length=30), nullable=True),\n sa.Column('realname', sa.String(length=50), nullable=True),\n sa.Column('avatar', sa.String(length=100), nullable=True),\n sa.Column('singature', sa.String(length=100), nullable=True),\n sa.Column('gender', sa.String(length=10), nullable=True),\n sa.Column('join_time', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email'),\n sa.UniqueConstraint('telephone')\n )\n op.create_table('cms_role_user',\n sa.Column('cms_role_id', sa.Integer(), nullable=False),\n sa.Column('cms_user_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['cms_role_id'], ['cmsrole.id'], ),\n sa.ForeignKeyConstraint(['cms_user_id'], ['cmsuser.id'], ),\n sa.PrimaryKeyConstraint('cms_role_id', 'cms_user_id')\n )\n op.create_table('follow',\n sa.Column('follower_id', sa.String(length=100), nullable=False),\n sa.Column('followed_id', sa.String(length=100), nullable=False),\n sa.Column('create_time', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['followed_id'], ['front_user.id'], ),\n sa.ForeignKeyConstraint(['follower_id'], ['front_user.id'], ),\n sa.PrimaryKeyConstraint('follower_id', 'followed_id')\n )\n op.create_table('post',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('title', sa.String(length=200), nullable=False),\n sa.Column('content', sa.Text(), nullable=False),\n sa.Column('create_time', sa.DateTime(), nullable=True),\n sa.Column('hit', sa.Integer(), nullable=True),\n sa.Column('comment_num', sa.Integer(), nullable=True),\n sa.Column('author_id', sa.String(length=100), nullable=False),\n sa.Column('board_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['author_id'], ['front_user.id'], ondelete='CASCADE'),\n sa.ForeignKeyConstraint(['board_id'], ['board.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('comment',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('content', sa.Text(), nullable=False),\n sa.Column('create_time', sa.DateTime(), nullable=True),\n sa.Column('post_id', sa.Integer(), nullable=True),\n sa.Column('author_id', sa.String(length=100), nullable=True),\n sa.ForeignKeyConstraint(['author_id'], ['front_user.id'], ondelete='CASCADE'),\n sa.ForeignKeyConstraint(['post_id'], ['post.id'], ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('highlight_post',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('post_id', sa.Integer(), nullable=True),\n sa.Column('create_time', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['post_id'], ['post.id'], ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('highlight_post')\n op.drop_table('comment')\n op.drop_table('post')\n op.drop_table('follow')\n op.drop_table('cms_role_user')\n op.drop_table('front_user')\n op.drop_table('cmsuser')\n op.drop_table('cmsrole')\n op.drop_table('board')\n op.drop_table('banner')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/283656f60272_.py","file_name":"283656f60272_.py","file_ext":"py","file_size_in_byte":5470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"498864458","text":"import urllib.request\nimport pandas as pd\nimport pathlib\nfrom Bio import pairwise2\nfrom Bio.pairwise2 import format_alignment\nimport numpy as np\nimport os \nimport Bio.PDB\nfrom operator import itemgetter\nfrom itertools import groupby\nimport warnings\n\n# silence biopython warning \nfrom Bio import BiopythonWarning\nwarnings.simplefilter('ignore', BiopythonWarning)\n\n\n#### Download pdb and get information about them\n\nclass get_pdbs(object):\n def __init__(self,seq_template,template_type,cutoff=80.0):\n '''\n seq_template: searching sequence template (can be residue sequence or PDBID_CHAINID)\n template_type: 'pdb' or 'fasta' \n cutoff: similarity cutoff \n '''\n self.seq_template = seq_template\n self.template_type = template_type\n self.cutoff = cutoff\n\n\n def search_for_seq(self):\n '''\n search pdb database by sequence similarity comparing to seq_template pdb or fasta sequence. Structures with similarity higher than the cutoff value are kept\n\n input param:\n result_file: result txt file to store similar pdb ids \n '''\n\n url = 'http://www.rcsb.org/pdb/rest/search'\n if self.template_type == 'pdb':\n PDB_id = self.seq_template[:4]\n chain = self.seq_template[-1]\n sequence =''\n elif self.template_type == 'fasta':\n PDB_id =''\n chain = ''\n sequence = self.seq_template\n else:\n print('input type error!')\n\n queryText = \"\"\"\n \n org.pdb.query.simple.SequenceQuery\n Sequence Search (Structure:Chain = %s:%s, Expectation Value = 90.0, Search Tool = BLAST)\n %s\n %s\n %s\n %s\n blast\n %s\n \n \"\"\"%(PDB_id,chain, PDB_id, chain, sequence, self.cutoff, self.cutoff)\n\n print(\"querying PDB ID ...\\n\")\n\n req = urllib.request.Request(url=url, data=queryText.encode('UTF-8'))\n f = urllib.request.urlopen(req)\n result = f.read()\n\n if result:\n print (\"Found number of PDB entries:\", result.decode('UTF-8').count('\\n'))\n self.pdb_ids = [l[0:4] for l in result.decode('UTF-8').split('\\n')][0:-1]\n #outfile = open(result_file,'w')\n #outfile.write(result.decode('UTF-8'))\n #outfile.close()\n\n else:\n print(\"Failed to retrieve results\")\n\n #pdb_id_list = [l[0:4] for l in result.decode('UTF-8').split('\\n')][0:-1]\n #return pdb_id_list\n\n\n def get_pdb_info(self,pdb_id_list=None):\n '''\n Use to get pdb structural info such as experimental tech, deposit date, resolution, chain length etc.\n\n param:\n pdb_id_list : a list of pdb ids. If None, self.pdb_ids is used. \n #result_file: a file contains pdb details of entries in pdb_id_list \n\n\n '''\n if not pdb_id_list:\n pdb_id_list = self.pdb_ids\n pdb_id_query = ','.join(pdb_id_list)\n queryText = \"http://www.rcsb.org/pdb/rest/customReport.csv?pdbids=\" + pdb_id_query + \\\n \"&customReportColumns=experimentalTechnique,depositionDate,resolution,chainLength,\" + \\\n \"uniprotRecommendedName,geneName,source,phValue,rFree,averageBFactor,ligandId,ligandSmiles,Ki,Kd,IC50\" \\\n + \"&service=wsdisplay&format=csv&ssa=nul\"\n\n\n print(\"querying PDB information... \\n\")\n\n\n f = urllib.request.urlopen(queryText)\n result = f.read()\n result = result.decode('UTF-8')\n xml_file = result.split(' ')\n xml_header = xml_file[0].split(',')\n index = len(xml_file)-1\n df = pd.DataFrame(index=range(1,index), columns=xml_header)\n a = 1\n for l in xml_file[1:-1]:\n b = 0\n for j in xml_header:\n df[j][a] = l.split(',')[b].strip('\"')\n b += 1\n a += 1\n\n #for i in df.index:\n # if df['ligandId'][i] in self.unwanted_hetams:\n # df['ligandId'][i] = np.nan\n # df['ligandSmiles'][i] = np.nan\n #df.drop([i], inplace=True)\n #df.drop_duplicates(subset=['structureId','chainId','ligandId'],inplace=True)\n #df.reset_index(inplace=True,drop=True)\n #df.to_csv(result_file,index_label='index')\n self.pdb_info = df\n\n\n\n def download_pdb(self,pdb_id,output_pdb):\n '''\n Use to download single pdb\n :param pdb_id: structure pdb id\n #output_pdb: output pdb file (dir/pdb_id.pdb)\n :return: None\n '''\n output_dir = '/'.join(output_pdb.split('/')[0:-1])\n os.makedirs(output_dir,exist_ok=True)\n try:\n urllib.request.urlretrieve('https://files.rcsb.org/download/%s.pdb'%pdb_id, output_pdb)\n except:\n print('Unable to download ' + pdb_id) \n\n\n def clean_pdb(self,pdb,output_pdb):\n '''\n clean pdb structure: fix insertion and alternative locations of atoms \n :param pdb: raw pdb file \n output_pdb: clean pdb file \n '''\n clean_pdb_dir = '/'.join(output_pdb.split('/')[0:-1])\n os.makedirs(clean_pdb_dir,exist_ok=True)\n \n# all_lines = [l for l in open(pdb,'r').readlines() if l.startswith('ATOM') or l.startswith('HETATM') or\\\n# l.startswith('TER') or l.startswith('MODEL') or l.startswith('ENDMDL')]\n all_lines = open(pdb,'r').readlines()\n atom_lines = [l for l in all_lines if l.startswith('ATOM') or l.startswith('HEATAM') or l.startswith('TER')]\n resi_label = atom_lines[0][22:27]\n resi_count = int(atom_lines[0][22:26])\n new_lines = []\n insertion = False\n for l in all_lines:\n if l.startswith('ATOM') or l.startswith('HETATM') or l.startswith('TER'):\n\n entry_type = l[0:6]\n altLoc = l[16]\n resi_label_new = l[22:27]\n icode = l[26]\n occupancy = l[54:60]\n\n # count number of residue by different residue label\n if resi_label_new != resi_label:\n resi_count +=1\n resi_label = resi_label_new\n altLoc_type = [] \n # label numbering shift if insertion happened\n if icode != ' ':\n insertion = True\n\n # fix residue number by residue count\n if insertion:\n l = l[0:22] + str(resi_count).rjust(4) + ' ' + l[27:]\n\n # for atom and hetatom with alternative position, keep those with occupancy >= 0.5\n\n if altLoc != ' ':\n if not altLoc in altLoc_type:\n altLoc_type.append(altLoc)\n\n #if (entry_type == 'ATOM ') and (altLoc == 'A'):\n # l = l[0:16] + ' ' + l[17:]\n # new_lines.append(l)\n if float(occupancy) >0.5:\n l = l[0:16] + ' ' + l[17:]\n new_lines.append(l)\n elif (float(occupancy) == 0.5) and (altLoc == altLoc_type[0]):\n l = l[0:16] + ' ' + l[17:]\n new_lines.append(l)\n\n elif entry_type == 'TER ':\n new_lines.append(l)\n else:\n new_lines.append(l)\n else:\n new_lines.append(l)\n output = open(output_pdb,'w')\n output.writelines(new_lines)\n\n\nclass complex_info(object):\n def __init__(self,pdb_info_csv,pdb_dir,unwanted_hetatms='default'):\n '''\n For each receptor chain get its ligand (can either be peptide or small molecules)\n process cleaned pdb structures: get receptor and ligand info, separate receptor and ligand structures and etc. \n param:\n pdb_info_csv: csv file generated from get_pdbs class \n pdb_dir: folder containing all pdbs listed in pdb_info_csv\n '''\n if type(pdb_info_csv) == str:\n if os.path.exists(pdb_info_csv) and pdb_info_csv.endswith('.csv'):\n self.df = pd.read_csv(pdb_info_csv,index_col='index')\n else:\n raise ValueError('unknown file type of pdb_info_csv. pdb_info_csv can be a csv file or a pandas DataFrame')\n elif type(pdb_info_csv) == pd.core.frame.DataFrame:\n self.df = pdb_info_csv\n else:\n raise ValueError('unknown file type of pdb_info_csv. pdb_info_csv can be a csv file or a pandas DataFrame')\n #self.pdb_info_csv = pdb_info_csv\n self.pdb_dir = pdb_dir\n if unwanted_hetatms == 'default':\n additive = ['1PE', 'ACT', 'AML', 'BCN', 'BEZ', 'BME', 'CIT', 'CO3', 'DMF','DMS', 'DTT', 'EDO', 'FMT', 'GOL',\n 'IMD', 'IPA', 'MES', 'MLA', 'MRD', 'PEG', 'PGE', 'PO4', 'SAR', 'SGM', 'SO4', 'SPK', 'TAR', 'TLA', 'TMO',\n 'TRS']\n\n ions = ['IOD', 'NA', 'BR', 'CL', 'K', 'SIN', 'ZN','MG']\n water = ['HOH']\n other = ['P15','PEU','EOH','O4B','MPO','GAI','PG4','MPD']\n self.unwanted_hetatms = additive + ions + water + other \n\n\n def get_receptor_ligand_info(self,template, template_type, template_pdb_dir=None, template_expt_type=None):\n ''' 1. For chains in a complex, distinguish receptor chains and peptide chains by a. sequence length and %alignment with template receptor chain \n 2. Check starting and ending residue id, sequence, gaps in receptor chain comparing to a template receptor chain \n 3. Get each receptor chains ligand info \n\n\n :param template_pdb_dir: folder containing template pdb \n :param template: pdb file use to define residue numbering and protein sequence, format pdbid_chainid or fasta AA sequence\n :param template_type: pdb or fasta\n :param template_pdb_dir: folder containing template pdb file (only needed for template_type == pdb)\n :param template_expt_type: SOLUTION NMR or X-RAY (only required for template_type == pdb) \n\n Note:\n 1. each receptor chain is aligned with template seq to get starting and ending residue number\n 2. peptide ligand chain screened as seq has poor match with the template sequence \n '''\n\n # get template sequence info \n if template_type == 'pdb':\n template_pdb = template.split('_')[0]\n template_chain = template.split('_')[1]\n if template_expt_type:\n temp_resStart, temp_resEnd, temp_seq = self._get_chain_res_info(template_pdb,template_chain,template_expt_type,\n pdb_folder=template_pdb_dir)\n else:\n raise ValueError('template_expt_type should be SOLUTION NMR or X-RAY')\n elif template_type == 'fasta':\n temp_resStart = 0\n temp_resEnd = len(template)-1\n temp_seq = template\n else:\n print('wrong template type')\n \n \n # pdb chains list \n# pdb_chains = self.df[['structureId','chainId','experimentalTechnique']].copy()\n# pdb_chains.drop_duplicates(inplace=True)\n # result header \n #A complex is a receptor chain with its ligand \n complex_info = np.append(self.df.columns,['resStart','resEnd','sequence_by_pdb_aligned','mutation','ligand_type', \\\n 'ligand_residue_id']).reshape(1,-1)\n\n # Peptide ligand info\n peptide_info = np.append(self.df.columns,['resStart','resEnd','sequence']).reshape(1,-1)\n\n# for i in pdb_chains.index:\n for i in self.df.index:\n #pdb = pdb_chains['structureId'][i]\n #chain = pdb_chains['chainId'][i]\n #expt_type = pdb_chains['experimentalTechnique'][i]\n\n pdb = self.df['structureId'].loc[i]\n chain = self.df['chainId'].loc[i]\n expt_type = self.df['experimentalTechnique'].loc[i]\n lig_name = self.df['ligandId'].loc[i]\n\n if not lig_name in self.unwanted_hetatms:\n #print(lig_name)\n if not (lig_name == '' or pd.isna(lig_name)):\n # distinguish regular ligand and modified residues \n lig_type, lig_resi_id = self._check_ligand(pdb,chain,lig_name,pdb_folder=self.pdb_dir)\n else:\n lig_type = 'apo'\n lig_resi_id = np.nan\n # get chain sequence info, modified residues are considered as part of the protein sequences \n resStart_pdb, resEnd_pdb, seq = self._get_chain_res_info(pdb,chain,expt_type,pdb_folder=self.pdb_dir)\n # get alignment result \n head_diff, end_diff, mutation, aligned_seq = self._align_seq(seq,temp_seq)\n if head_diff == None : ## head_diff == None indicates poor alignment --> not receptor chain\n peptide_info_entry = np.append(self.df.loc[i].tolist(), [resStart_pdb,resEnd_pdb,seq]).reshape(1,-1)\n peptide_info = np.append(peptide_info,peptide_info_entry,axis=0)\n \n else: \n # fix resStart and resEnd index using template seq residue indexing as reference \n resStart = int(temp_resStart) - head_diff \n resEnd = int(temp_resEnd) + end_diff \n # fix mutation site index using template seq residue indexing \n mut_new_list = [] \n for mut in mutation:\n mut_loc = int(mut[1:-1])\n if head_diff >= 0: \n mut_loc = mut_loc - head_diff \n else:\n mut_loc = mut_loc \n mut_new = mut[0] + str(mut_loc) + mut[-1]\n mut_new_list.append(mut_new)\n mutation_new = ';'.join(mut_new_list)\n\n \n # here only small molecule ligand is considered, peptide binder will be filled in later\n if lig_type in ['noncovalent','covalent','apo']:\n complex_info_entry = np.append(self.df.loc[i].tolist(),[resStart,resEnd,aligned_seq,mutation_new,lig_type,lig_resi_id]).reshape(1,-1)\n else: # in the case of modres\n new_df_info = self.df.loc[i].copy()\n new_df_info['ligandId'] = np.nan\n new_df_info['ligandSmiles'] = np.nan\n new_df_info['Ki'] = np.nan\n new_df_info['Kd'] = np.nan\n new_df_info['IC50'] = np.nan\n\n complex_info_entry = np.append(new_df_info.tolist(), [resStart,resEnd,aligned_seq,mutation_new,np.nan,np.nan]).reshape(1,-1)\n complex_info = np.append(complex_info,complex_info_entry,axis=0)\n else:\n pass\n \n complex_info_df = pd.DataFrame(data=complex_info[1:,:],columns=complex_info[0,:])\n complex_info_df.drop_duplicates(subset=['structureId','chainId','ligandId'],inplace=True)\n peptide_info_df = pd.DataFrame(data=peptide_info[1:,:],columns=peptide_info[0,:])\n peptide_pdbs = set(peptide_info_df['structureId'].tolist())\n\n \n peptide_ligand = complex_info_df.copy()\n peptide_ligand.drop_duplicates(subset=['structureId','chainId'],inplace=True)\n # fill in peptide inhibitor info\n peptide_drop_list = [] \n for i in peptide_ligand.index:\n pdb = peptide_ligand['structureId'].loc[i]\n chain = peptide_ligand['chainId'].loc[i]\n if pdb in peptide_pdbs:\n \n all_recep_chains = [c for c in peptide_ligand.loc[peptide_ligand['structureId'] == pdb]['chainId'].tolist()]\n peptide_chain = self._check_closest_peptide(pdb,chain, all_recep_chains, pdb_folder=self.pdb_dir)\n #print(peptide_chain)\n if peptide_chain:\n peptide_ligand['ligand_type'].loc[i] = 'peptide'\n peptide_ligand['ligandId'].loc[i] = peptide_chain \n peptide_ligand['ligand_residue_id'].loc[i] = peptide_chain\n peptide_ligand['Ki'].loc[i] = np.nan\n peptide_ligand['Kd'].loc[i] = np.nan\n peptide_ligand['IC50'].loc[i] = np.nan\n else: # if no nearby peptide chains detected, drop that row \n peptide_drop_list.append(i)\n else:\n peptide_drop_list.append(i)\n peptide_ligand.drop(peptide_drop_list,inplace=True)\n \n # label ligand binding site. If a chain has multiple ligands bound, each ligand is occupying a separate binding site.\n complex_all = pd.concat([complex_info_df,peptide_ligand],axis=0)\n complex_all.reset_index(inplace=True,drop=True)\n \n\n binding_site = [-1] * complex_all.shape[0] \n drop_list = [] \n for i in complex_all.index:\n pdb = complex_all['structureId'].loc[i]\n chain = complex_all['chainId'].loc[i]\n if binding_site[i] != -1:\n continue\n # print(pdb,chain)\n temp = complex_all.loc[(complex_all['structureId'] == pdb) & (complex_all['chainId'] == chain)]\n if temp.shape[0] > 1:\n site_count = 0\n for ind in temp.index:\n if not pd.isna(temp['ligandId'].loc[ind]):\n binding_site[ind] = site_count \n site_count += 1\n else:\n if not ind in drop_list:\n drop_list.append(ind)\n\n\n else:\n if pd.isna(complex_all['ligand_type'].loc[i]): # in the case of modres, ligand_type is originially set to np.nan. If after peptide ligand info updated, this chain still does not have a ligand, it should be an apo chain. \n complex_all['ligand_type'].loc[i] = 'apo' \n binding_site[i] = 0 \n \n complex_all.insert(complex_all.shape[1],'binding_site',binding_site) \n complex_all.drop(drop_list,inplace=True)\n self.complex_info = complex_all\n #self.peptide_info = peptide_info_df\n # Note: 2RUH has protein and peptide inhibitors linked together (CatS pdbs)\n\n @staticmethod\n def _check_ligand(pdb,chain,ligand_name,pdb_folder):\n '''\n For a ligand, find its residue id and check if it's a noncovalent ligand. \n \n :param pdb: pdb id\n :param chain: chain id\n :param ligand_name: the residue name of the ligand \n :param pdb_folder: folder for pdb files\n :return: ligand name list, number of ligands (one ligand name can have two ligands at diff sites)\n\n Note: additive, ions, water, and other cocrystal solvent is not considered as ligands\n '''\n pdb_lines = open(pdb_folder + '/' + pdb + '.pdb','r').readlines()\n link_lines = [l for l in pdb_lines if l.startswith('LINK')] \n link_resi = [q for t in [[l.split()[2],l.split()[6]] for l in link_lines] for q in t]\n modres_lines = [l for l in pdb_lines if l.startswith('MODRES')]\n modres = [l.split()[2] for l in modres_lines] \n\n #print(type(ligand_name))\n #print(ligand_name)\n if (ligand_name in link_resi) and (not ligand_name in modres):\n ligand_type = 'covalent'\n elif ligand_name in modres:\n ligand_type = 'modified residue'\n else:\n ligand_type = 'noncovalent'\n #print(ligand_name)\n for l in pdb_lines:\n if l[21] == chain and l[17:20].strip() == ligand_name and (l.startswith('ATOM') or l.startswith('HETATM')):\n ligand_resi_id = l[22:26].strip()\n break \n else:\n continue \n return ligand_type, ligand_resi_id\n\n# def _check_chain_hetatm(pdb,chain,pdb_folder):\n#\n# chain_lines = [l for l in pdb_lines if (l[21] == chain) and (l[17:20].strip() not in unwanted_hetatms)]\n#\n#\n# modified_resi = [] \n# modified_resi_id = [] \n# lig_resi =[]\n# lig_resi_id = [] \n#\n# hetatm_resi = [] \n# hetatm_resi_id = []\n# other_atm = False\n# for l in chain_lines: \n# if l.startswith('TER'):\n# \n# hetatm_resi_count = len(hetatm_resi)\n# if (hetatm_resi_count > 1) or (hetatm_resi_count == 1 and other_atm == True):\n# modified_resi.extend(hetatm_resi)\n# modified_resi_id.extend(hetatm_resi_id)\n# elif hetatm_resi_count == 1 and other_atm == False: \n# lig_resi.extend(hetatm_resi)\n# lig_resi_id.extend(hetatm_resi_id)\n# else:\n# pass \n# hetatm_resi = [] \n# hetatm_resi_id = []\n# other_atm = False \n#\n# elif l.startswith('HETATM'):\n# resi_name = l[17:20].strip()\n# resi_id = l[22:26].strip()\n# if not resi_id in hetatm_resi_id:\n# hetatm_resi_id.append(resi_id)\n# hetatm_resi.append(resi_name)\n# \n# elif l.startswith('ATOM'):\n# other_atm = True \n#\n# hetatm_resi_count = len(hetatm_resi)\n# if (hetatm_resi_count > 1) or (hetatm_resi_count == 1 and other_atm == True):\n# modified_resi.extend(hetatm_resi)\n# modified_resi_id.extend(hetatm_resi_id)\n# elif hetatm_resi_count == 1 and other_atm == False: \n# lig_resi.extend(hetatm_resi)\n# lig_resi_id.extend(hetatm_resi_id)\n# else:\n# pass \n#\n#\n# if modified_resi != []:\n# print(pdb + ' chain ' + chain + ' has nonstandard residues')\n## print('modified residues :')\n# print(modified_resi, modified_resi_id)\n#\n# \n# return lig_resi, lig_resi_id, modified_resi, modified_resi_id\n \n @staticmethod\n def _check_closest_peptide(pdb,chain,all_recep_chains, pdb_folder):\n '''\n for pdbs with peptide as ligand, get peptide chain id as ligand name\n :param pdb: pdb id\n :param chain: chain id\n :param receptor_csv: pandas dataframe containing receptor chain info\n :param pdb_folder: folder containing all pdb files\n :return: peptide ligand chain id\n '''\n\n\n def _calc_residue_dist(residue_one, residue_two):\n '''\n\n :param residue_one:\n :param residue_two:\n :return: return c-alpha distance between two residues\n '''\n diff_vector = residue_one['CA'].coord - residue_two['CA'].coord\n return np.sqrt(np.sum(diff_vector * diff_vector))\n\n def _calc_dist_matrix(chain_one, chain_two):\n '''\n\n :param chain_one:\n :param chain_two:\n :return: a matrix of C-alpha distance between two chains\n\n '''\n\n chain_one_resi = [i for i in chain_one for atom in i if atom.get_full_id()[4][0] == 'CA'] #get rid of wat and\n # capping which has no CA\n chain_two_resi = [i for i in chain_two for atom in i if atom.get_full_id()[4][0] == 'CA']\n\n answer = np.zeros((len(chain_one_resi),len(chain_two_resi)), np.float)\n for row, residue_one in enumerate(chain_one_resi):\n for col, residue_two in enumerate(chain_two_resi):\n answer[row,col] = _calc_residue_dist(residue_one, residue_two)\n return answer\n\n structure = Bio.PDB.PDBParser().get_structure(pdb,pdb_folder + '/' + pdb + '.pdb')\n model = structure[0] #in each model, it list all chains, unique chain id is considered as a seperate chain.\n # NMR structures has same chain id in different model, crystal structure has different chain id for diff monomer\n ref_chain = chain\n peptide_chain = None\n #print('all models ')\n if len(model) > 2: # non monomer and NMR including several models\n num_contact = 0\n for chain_name in model:\n #print(chain_name)\n chain_id = chain_name.get_full_id()[2]\n if chain_id != ref_chain and (chain_id not in all_recep_chains):\n dist_matrix = _calc_dist_matrix(model[chain_id], model[ref_chain])\n contact_array = np.where(dist_matrix < 8)\n num_contact_new = len(contact_array[0])\n\n if num_contact_new > num_contact:\n num_contact = num_contact_new\n peptide_chain = chain_id\n\n\n\n\n else: # monomer\n for chain_name in model:\n chain_id = chain_name.get_full_id()[2]\n if not chain_id == ref_chain:\n peptide_chain = chain_id\n return peptide_chain\n\n @staticmethod\n def _get_chain_res_info(pdb,chain,exp_type,pdb_folder):\n '''\n Get starting and ending residue id from pdb file and get sequence\n :param pdb: pdb id\n :param chain: chain id\n :return: starting residue id and ending residue id and AA sequence\n\n '''\n letters = {'ALA': 'A', 'ARG': 'R', 'ASN': 'N', 'ASP': 'D', 'CYS': 'C', 'GLU': 'E', 'GLN': 'Q', 'GLY': 'G',\n 'HIS': 'H', 'ILE':'I', 'LEU': 'L', 'LYS': 'K', 'MET': 'M', 'PHE': 'F', 'PRO': 'P', 'SER': 'S',\n 'THR': 'T', 'TRP': 'W', 'TYR': 'Y', 'VAL': 'V'}\n f = open(pdb_folder +'/' + pdb +'.pdb','r').readlines()\n link_lines = [l for l in f if l.startswith('LINK')] \n link_resi_in_chain = [] \n for l in link_lines:\n l_info = l.split()\n if l_info[3] == chain:\n link_resi_in_chain.append(l_info[2])\n if l_info[7] == chain:\n link_resi_in_chain.append(l_info[6])\n\n wanted_hetatms = [t for t in set(link_resi_in_chain) if not t in letters.keys()] \n\n if exp_type == 'SOLUTION NMR':\n for l in f:\n if l.startswith('MODEL'):\n chain_lines = []\n elif (l.startswith('ATOM') and l[21] == chain) or (l.startswith('HETATM') and l[21] == chain \\\n and (l[17:20].strip() in wanted_hetatms)):\n try:\n chain_lines.append(l)\n except ValueError:\n print('chain_lines not defined')\n\n elif l.startswith('ENDMDL'):\n break # only need to check the first model sequence in nmr structures \n\n else:\n chain_lines = [l for l in f if (l.startswith('ATOM') and l[21] == chain) or (l.startswith('HETATM') and l[21] == chain \\\n and (l[17:20].strip() in wanted_hetatms))]\n #chain_lines = [l for l in f if l.startswith('ATOM') or l and l[21] == chain]\n #print(pdb, chain)\n #print(chain_lines[0])\n resStart = chain_lines[0][22:26]\n resEnd = chain_lines[-1][22:26]\n\n res_id = None\n seq = ''\n for l in chain_lines:\n res_id_new = l[22:26]\n if not res_id_new == res_id:\n try:\n res_name = letters[l[17:20]] # if residue is normal amino acid \n except:\n res_name = 'x' # if residue is a modified aa \n seq = seq + res_name\n res_id = res_id_new\n\n else:\n next\n\n return resStart, resEnd, seq\n\n @staticmethod\n def _align_seq(seq,temp_seq):\n '''\n\n :param seq: sequence to be aligned\n :param temp_seq: template sequence\n :return:\n head_diff: n terminal sequence extra or missing number of residues comparing to template (int)\n end_diff: c terminal extra or missing number of resiudes (int)\n mutations: point of mutations format: Y12K\n '''\n\n def check_gap_and_mut(alignment_correct):\n aligned_seq = format_alignment(*alignment_correct).split('\\n')[0:3]\n\n gap_position = []\n gap_partner = []\n mutation = []\n for ind, x in enumerate(aligned_seq[1]):\n if x == ' ':\n gap_position.append(ind)\n if aligned_seq[0][ind] == '-':\n gap_partner.append(0) # seq = 0 \n else:\n gap_partner.append(1) # temp_seq = 1 \n elif x == '.':\n mut = aligned_seq[2][ind] + str(ind) + aligned_seq[0][ind]\n mutation.append(mut)\n\n\n #get sequence and template sequence gap position\n # seq = 0 and temp_seq = 1 in gap_partner array \n seq_gap_position = np.array(gap_position)[np.array(gap_partner)==0].tolist()\n temp_seq_gap_position = np.array(gap_position)[np.array(gap_partner) == 1].tolist()\n \n # get sequence gap group by grouping continuous gap positions\n if len(seq_gap_position) > 1:\n seq_group_result = []\n for key, group in groupby(enumerate(seq_gap_position),lambda x: x[0]-x[1]):\n group_result = tuple(map(itemgetter(1),group))\n seq_group_result.append(group_result)\n\n elif len(seq_gap_position) == 1:\n seq_group_result = [(seq_gap_position[0],)]\n else:\n seq_group_result = []\n\n # get template sequence gap groups by grouping continuous gap positons\n if len(temp_seq_gap_position) > 1:\n\n temp_seq_group_result = []\n for key, group in groupby(enumerate(temp_seq_gap_position),lambda x:x[0] - x[1]):\n\n group_result = tuple(map(itemgetter(1),group))\n temp_seq_group_result.append(group_result)\n\n elif len(temp_seq_gap_position) == 1:\n temp_seq_group_result = [(temp_seq_gap_position[0],)]\n else:\n temp_seq_group_result = []\n\n\n head_diff = 0\n end_diff = 0\n\n #real gaps are those not at the termini\n seq_real_gaps = []\n temp_seq_real_gaps = []\n for gap in seq_group_result:\n\n if 0 in gap:\n head_diff = -len(gap)\n elif len(aligned_seq[1])-1 in gap:\n end_diff = -len(gap)\n else:\n seq_real_gaps.append(gap)\n\n for gap in temp_seq_group_result:\n if 0 in gap:\n head_diff = len(gap)\n elif len(aligned_seq[1])-1 in gap:\n end_diff = len(gap)\n else:\n temp_seq_real_gaps.append(gap)\n\n return head_diff,end_diff, mutation, aligned_seq[0], seq_real_gaps, temp_seq_real_gaps\n\n\n\n\n alignments = pairwise2.align.globalms(seq,temp_seq, 2, -1, -2, -0.1) # score of identical characters is 2, penalize mismatch by score -1, penalize gap with score of -0.5 and penalize extending a gap by -0.1\n if alignments[0][2]< 0.5 * 2 * len(temp_seq): #sequence alignment score is < 60% of the identical matched template sequence. \n #print('poor_align')\n return None, None, None, None\n else:\n if len(alignments) > 1:\n #print('multiple alignments')\n template_gaps = float('inf')\n # if multiple alignment results, the one with least gaps is considered as final alignment results\n for i in alignments:\n head_diff,end_diff, mutation, aligned_seq,seq_real_gaps,temp_seq_real_gaps = check_gap_and_mut(i)\n if len(temp_seq_real_gaps) < template_gaps:\n alignment_correct = i\n template_gaps = len(temp_seq_real_gaps)\n\n else:\n alignment_correct = alignments[0]\n\n head_diff,end_diff, mutation, aligned_seq,seq_real_gaps,temp_seq_real_gaps = check_gap_and_mut(alignment_correct)\n\n mutation_new = []\n if len(temp_seq_real_gaps) > 0:\n\n\n gap_list = [pos for gap in temp_seq_real_gaps for pos in gap ]\n for j in mutation:\n shift_list = [pos for pos in gap_list if pos < int(j[1:-1])]\n shift = len(shift_list)\n mut_new = j[0] + str(int(j[1:-1]) - shift) + j[-1]\n mutation_new.append(mut_new)\n\n #print('warning: missing residues in template sequence!!!!!')\n else:\n mutation_new = mutation\n #if len(seq_real_gaps) > 0:\n #print('warning: missing residues in sequence')\n\n return head_diff, end_diff, mutation_new, aligned_seq\n\n","sub_path":"vs_pfm/data/pdb_info.py","file_name":"pdb_info.py","file_ext":"py","file_size_in_byte":33357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"510081377","text":"from BaseStrategy import BaseStrategy\nimport numpy as np\nimport datetime\n\nclass SimpleStrategy(BaseStrategy):\n def __init__(self, signal,price):\n \"\"\"\n Constructor of the class\n :param signal:\n \"\"\"\n self.signal= np.array(signal)\n self.length = signal.size\n self.__time__ = signal.index\n self.price = price\n\n def generate_position(self):\n \"\"\"\n Generate signal according strategy:\n :return: position\n \"\"\"\n curr_pos = 0\n position = np.zeros(self.length)\n \n for i in range(self.length):\n if self.signal[i]==np.sign(curr_pos)*(-1):\n position[i]=self.signal[i]-curr_pos\n curr_pos = self.signal[i]\n else:\n position[i]=self.signal[i]\n curr_pos+=self.signal[i]\n return position\n\n #def get_time_stamp(self):\n #return self.__time__\n\n #def get_prices(self):\n #return self.__bars__\n\n\n\n","sub_path":"Strategy/SimpleStrategy.py","file_name":"SimpleStrategy.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"377062613","text":"import aiohttp\nimport io\nimport re\n\nimport discord\nfrom discord.ext import commands\nimport html2text\nimport lxml.html\nfrom PIL import Image\n\nimport chickensmoothie as cs\n\n\nclass News(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.group(aliases=['announce', 'announcement'])\n @commands.guild_only()\n async def news(self, ctx):\n pass\n\n @news.command()\n @commands.guild_only()\n async def on(self, ctx):\n pass\n\n @news.command()\n @commands.guild_only()\n async def off(self, ctx):\n pass\n\n @news.command()\n @commands.guild_only()\n async def latest(self, ctx):\n news_articles = await cs.get_announcements() # Get the HTML list of all the news articles\n latest = news_articles[0] # Get the latest (first) news\n post_date = latest.getparent().getprevious().text # Get the news post date\n\n image_link = None\n image_list = None\n multiple_images = False\n canvas = None\n if latest.find('a/img[@alt=\"Image\"]') is not None: # If news has click-able images\n if len(latest.findall('a/img[@alt=\"Image\"]')) == 1: # If there is only 1 image\n image_tag = latest.find('a/img[@alt=\"Image\"]') # Get the 'img' tag\n image_link = image_tag.xpath('@src')[0] # Extract image link for use in embed later\n parent = image_tag.getparent() # Get parent tag of 'img', which is 'a' tag\n latest.remove(parent) # Remove the 'a' tag so it won't be converted to Markdown\n else: # If there is more than 1 image\n image_list = latest.findall('a/img[@alt=\"Image\"]') # Get the links to all the images\n multiple_images = True\n elif latest.find('img[@alt=\"Image\"]') is not None: # If the news has static images instead\n if len(latest.findall('img[@alt=\"Image\"]')) == 1: # If there is only 1 image\n image_tag = latest.find('img[@alt=\"Image\"]') # Get the 'img' tag\n image_link = image_tag.xpath('@src')[0] # Extract image link for use in embed later\n latest.remove(image_tag) # Remove the 'img' tag so it won't be parsed later\n else: # If there is more than 1 image\n image_tags = latest.findall('img[@alt=\"Image\"]') # Get all image tags\n image_links = [element.xpath('@src')[0] for element in image_tags] # Get the links to the image\n image_links = [url.replace('//', 'https://') for url in image_links] # Replace relative links with absolute links\n\n image_list = []\n async with aiohttp.ClientSession() as session:\n for link in image_links:\n async with session.get(link) as response:\n connection = await response.read()\n image_list.append(io.BytesIO(connection)) # Convert the images into bytes\n multiple_images = True\n\n if multiple_images: # If there are multiple images\n pil_images = list(map(Image.open, image_list)) # Open all byte images as PIL images\n\n current_width = 0\n current_heights = []\n for image in pil_images:\n current_width += image.width\n current_heights.append(image.height)\n max_height = max(current_heights) # Get the height of the tallest image\n\n x_offset = 10 # The spacing between images\n canvas_width = current_width + (x_offset * len(pil_images))\n canvas_height = max_height\n\n canvas = Image.new('RGBA', (canvas_width, canvas_height)) # Create an empty RGBA image\n current_x = 0\n for image in pil_images:\n canvas.paste(image, (current_x, (max_height - image.height)), image)\n current_x += image.width + x_offset\n\n text = lxml.html.tostring(latest) # Get the source HTML of the news article\n text_decoded = text.decode('utf-8') # Decode into UTF-8\n\n bold_span_tags = re.findall(r'(([\\w\\W]+?))', text_decoded) # Find all tags used to bold text\n if bold_span_tags: # If there are bolded text\n for tag in bold_span_tags:\n text_decoded = text_decoded.replace(tag[0], f'%@^{tag[1]}%@^') # Change the tag to a temporary name\n\n emoji_list = re.findall(r'\\s*', text_decoded) # Check if there are emojis in the news article\n if emoji_list: # If there are emojis\n for emoji in emoji_list:\n text_decoded = text_decoded.replace(emoji, '') # Remove the emoji\n\n text_decoded = text_decoded.replace('//', 'https://') # Replace all relative links to prefix with HTTPS\n links = set(re.findall(r'href=\"(.*?)\"', text_decoded)) # Get all href links\n for link in links:\n text_decoded = text_decoded.replace(link, f'https://www.chickensmoothie.com{link}') # Prepend Chicken Smoothie base URL\n\n content = html2text.html2text(text_decoded) # Convert remaining HTML into Markdown\n\n content = content.replace(' \\n', '$#@') # Fix up broken newlines\n content = content.replace('\\n', ' ')\n content = content.replace('$#@', '\\n')\n content = content.replace('%@^', '**') # Replace temporary span tags to **\n content = content.replace('\\n\\n\\n', '\\n') # Remove duplicate newlines\n\n links = re.findall(r'\\(http[s]*[\\w\\W]+?\\)', content) # Get all links in the Markdown\n for link in links:\n fixed_link = link.replace(' ', '') # Remove any spacing in them\n content = content.replace(link, fixed_link)\n\n # 11) Send embed\n embed = discord.Embed(title=post_date, description=content, colour=0x4ba139) # Create embed\n if multiple_images: # If there are multiple images\n output_buffer = io.BytesIO() # Convert the PIL output into bytes\n canvas.save(output_buffer, 'png') # Save the bytes as a PNG format\n output_buffer.seek(0) # Move the 'cursor' back to the start\n await ctx.send(embed=embed, file=discord.File(fp=output_buffer, filename='news.png')) # Upload the file to the channel where message came from\n elif image_link is not None: # If image exists in news\n embed.set_image(url=f'https:{image_link}') # Set embed image\n await ctx.send(embed=embed) # Send message\n else:\n await ctx.send(embed=embed) # Send message\n\n\ndef setup(bot):\n bot.add_cog(News(bot))\n","sub_path":"cogs/news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":6640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"3833397","text":"'''\n Write a program to calculate average marks of five inputted marks.\n\n'''\nmarks_data = []\nsub_count = 5;\ndef getData():\n for i in range(sub_count):\n inp = float(input(\"Enter the marks: \"))\n if 0<=inp<=100:\n marks_data.append(inp)\n else:\n print(\"Invalid marks entered\")\n\ndef calData():\n l_marks_data = len(marks_data)\n calc = 0;\n if l_marks_data == 5:\n for i in marks_data:\n calc = calc + i\n print(f\"Average of marks entered is: {calc/l_marks_data}\")\n else:\n print(\"Insufficient list of marks!\")\n\nif __name__ == \"__main__\":\n getData()\n calData()\n ","sub_path":"assignment4/average.py","file_name":"average.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"263361297","text":"# https://codechalleng.es/bites/180/\n\nfrom collections import defaultdict\n\n# fake data from https://www.mockaroo.com\ndata = \"\"\"last_name,first_name,country_code\nWatsham,Husain,ID\nHarrold,Alphonso,BR\nApdell,Margo,CN\nTomblings,Deerdre,RU\nWasielewski,Sula,ID\nJeffry,Rudolph,TD\nBrenston,Luke,SE\nParrett,Ines,CN\nBraunle,Kermit,PL\nHalbard,Davie,CN\"\"\"\n\n\ndef group_names_by_country(data: str = data) -> defaultdict:\n countries = defaultdict(list)\n for line in data.split('\\n'):\n last_name, first_name, country = line.split(',')\n countries[country].append(f\"{first_name} {last_name}\")\n countries.pop('country_code', None)\n return countries\nif __name__ == '__main__':\n group_names_by_country(data)\n","sub_path":"bites/bite180_names.py","file_name":"bite180_names.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"27691819","text":"import discord\nimport asyncio\nfrom logger import log\n\n\nasync def ex(args, message, client, invoke):\n author = message.author.name\n channel = message.channel.__str__()[20:]\n if author != channel:\n try:\n ammount = int(args[0]) + 1 if len(args) > 0 else 2\n except:\n await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.red(), description=\"Please enter another value than %s\" % ammount))\n return\n\n messages = []\n async for m in client.logs_from(message.channel, limit=ammount):\n messages.append(m)\n\n await client.delete_messages(messages)\n\n return_msg = await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.blue(), description=\"Cleared %s message(s).\" % ammount))\n await asyncio.sleep(4)\n await client.delete_message(return_msg)\n else:\n await client.send_message(message.author, embed=discord.Embed(color=discord.Color.red(), description=\"Can't delete direct messages!\"))\n log(\"Could not clear message(s)!\", \"error\")\n","sub_path":"commands/cmd_clear.py","file_name":"cmd_clear.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"39017480","text":"# from openpyxl import Workbook\n# wb = Workbook() # 새 워크북 생성\n# ws = wb.active\n# ws.title = \"NadoShee\"\n# ws.sheet_properties.tabColor = \"ff66ff\"\n# for x in range (1,11):\n# c= ws.cell(row = x, column = 1, value = 4)\n# print (c.value)\n# print(ws.max_row)\n\n# wb.save(\"sample.xlsx\")\n# wb.close()\n\nimport glob\nfilelocation = input(\"위치를적어주세요\")\nfiletype = input(\"파일유형 적어주세요\")\nmyList = glob.glob(filelocation + \"\\*.\" + filetype)\nif not myList:\n fileresult = input(\"잘못되었습니다\")\nelse:\n print (*myList, sep = \"\\n\")\n fileresult = input(\"여기있습니다\") \n\n# print (os.path.abspath(\"17194.xls\"))\n\n# 어떤 폴더에 어떤파일들이 있는지 알려주는 프로그램\n\n#C:\\Users\\Dave\\Documents\\정석윤\\9. 매크로 프로젝트\\gunsan\\*.xls\n\n#my testbed for codingxls\n","sub_path":"rpa_basic/1_excel/1_create_file.py","file_name":"1_create_file.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"3209459","text":"\"\"\"Class for Route53 domains.\"\"\"\n\n\nclass DomainManager:\n \"\"\"Manage a Route53 domain.\"\"\"\n\n def __init__(self, session):\n \"\"\"Create DomainManager object.\"\"\"\n self.session = session\n self.route53_client = session.client('route53')\n\n def find_hosted_zone(self, domain_name):\n \"\"\"Find a hosted zone of the domain.\"\"\"\n paginator = self.route53_client.get_paginator('list_hosted_zones')\n\n for page in paginator.paginate():\n for zone in page['HostedZones']:\n if domain_name.endswith(zone['Name'][:-1]):\n return zone\n\n return None\n\n def create_s3_domain_record(self, zone, domain_name, endpoint):\n \"\"\"Create an A record for the domain name.\"\"\"\n return self.route53_client.change_resource_record_sets(\n HostedZoneId=zone['Id'],\n ChangeBatch={\n 'Comment': 'Created by boto3 lib',\n 'Changes': [{\n 'Action': 'UPSERT',\n 'ResourceRecordSet': {\n 'Name': domain_name,\n 'Type': 'A',\n 'AliasTarget': {\n 'HostedZoneId': endpoint.zone,\n 'DNSName': endpoint.host,\n 'EvaluateTargetHealth': False\n }\n }\n\n }]\n }\n\n )\n\n def create_cf_domain_record(self, zone, domain_name, cf_domain):\n \"\"\"Create an domain record in zone for domain_name.\"\"\"\n print(zone, domain_name, cf_domain)\n return self.route53_client.change_resource_record_sets(\n HostedZoneId=zone['Id'],\n ChangeBatch={\n 'Comment': 'Created by boto3 lib',\n 'Changes': [{\n 'Action': 'UPSERT',\n 'ResourceRecordSet': {\n 'Name': domain_name,\n 'Type': 'A',\n 'AliasTarget': {\n 'HostedZoneId': 'Z2FDTNDATAQYW2',\n 'DNSName': cf_domain,\n 'EvaluateTargetHealth': False\n }\n }\n\n }]\n }\n\n )\n","sub_path":"scripts/domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"378424670","text":"# coding=utf-8\nimport unicodedata\nclass config_predict(object):\n def __init__(self,model_config='', doPredict = [1,1,1,1]): #__init__() 是类的初始化方法;它在类的实例化操作后 会自动调用,不需要手动调用;\n # 设置属性\n self.stopwords = [\" \", \" \", \" \", \",\", \",\", \".\", \"。\", \"、\", \"!\", \"!\", \"?\", \"?\", \";\", \";\", \"~\", \"~\", \"·\", \"·\", \".\", \"…\", \"-\",\n \"#_\", \"—\", \"+\", \"=\", \"'\", \"\\\"\", \"‘\", \"’\", \"“\", \"”\", \"*\", \"&\", \"^\", \"%\", \"$\", \"/\", \"\\\\\", \"@\"]\n self.stopwords,self.map_e2z = self.addStopwords()\n self.blackwords = ['自杀','死','火葬','我是你爸爸','我是你妈妈']\n self.specialwords_pre = ['祝福', '祝愿', '预祝']\n self.specialwords_gen = ['生日', '新年', '新春', '春节', '节日', '元旦']\n self.singlewords = ['哈','啊','哦','哦','呵','嘿','哎','哼']\n self.removed_words = ['⊙']\n self.punc_end = '.?!。?!》>'\n self.path_HighFreqWords = '../data/words_highFreq.txt'\n self.HighFreqWords = self.getHFW()\n self.min_contenlen = 8\n self.rate_gen2inp = 1.4\n self.batchGenerating = True\n self.max_nb_sents=4\n self.gpus = ['5','6','7']\n self.style = ['poem','prose','gou']\n if len(model_config)==0:\n self.model_configs = ['demo_config/config_poem.json','demo_config/config_godText_small_finetune_merged.json',\n 'demo_config/config_dabaigou.json']\n else:\n if type(model_config)==list:\n self.model_configs = model_config\n else:\n self.model_configs = [model_config]\n self.predict_nums = [4, 8, 8, 5]\n self.tags = ['(诗)', '(文)', '(大白狗)', '(句联想)']\n self.doPredict = [t==1 for t in doPredict]\n self.rmHFW = [False, False, True, False]\n self.maxNext_JLX = 3\n self.path_JLX_next = 'model/nnlm/D_next.json'\n self.path_JLX_simi = 'model/nnlm/D_simi.json'\n self.prefixTrim = True\n self.useThread = True\n self.fast_pattern = True\n self.repetition_penalty = [1.5,1.2,1.2]\n self.temperature = [0.7,0.6,0.5]\n self.length = [64,30,30]\n self.resort = True\n def addStopwords(self):\n punc_zh = \"!?。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟‧﹏.…\"\n punc_en = unicodedata.normalize('NFKC', punc_zh[:-1]) + unicodedata.normalize('NFKC', punc_zh[-1])[-1]\n punc_zh = punc_zh + '。'\n punc_en = punc_en + '。'\n map_e2z = {punc_en[i]: punc_zh[i] for i in range(len(punc_en))}\n stopwords = self.stopwords + list(punc_zh) + list(punc_en)\n stopwords = list(set(stopwords))\n return stopwords,map_e2z\n def getHFW(self):\n with open(self.path_HighFreqWords,'r') as f:\n s = f.read().strip().split('\\n')\n return s\n","sub_path":"test_online/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"33882772","text":"#!/usr/bin/env python3\n# coding utf-8\n\nimport cProfile\n\nimport copy\nimport math\nimport numpy as np\nimport random\nfrom datetime import datetime\n\nimport pprint\npprint = pprint.PrettyPrinter(indent=4).pprint\n\nfrom Classes.MatricesPrinter import MatricesPrinter\nfrom Classes.Options import Options\nfrom Classes.Point import Point\nfrom Classes.PolygonCylinderInTheShell import PolygonCylinderInTheShell\nfrom Classes.PropertiesPrinter import PropertiesPrinter\nfrom Classes.Vector import Vector\n\nfrom functions.boxCross import boxCross\nfrom functions.boxCrossByDiskInTheShell import boxCrossByDiskInTheShell\nfrom functions.checkPercolation import checkPercolation\nfrom functions.diskDiskInTheShellCross import diskDiskInTheShellCross\nfrom functions.disksCross import disksCross\nfrom functions.disksInTheShellCross import disksInTheShellCross\n\n\ndef mainExfoliation():\n o = Options()\n maxhMatrix = o.getProperty('maxh_m')\n maxhFiller = o.getProperty('maxh_f')\n maxhShell = o.getProperty('maxh_sh')\n desiredDisksNumber = int(o.getProperty('numberOfDisks'))\n maxAttempts = o.getProperty('maxAttempts')\n pcs = []\n l = o.getProperty('cubeEdgeLength')\n #cellString = 'solid cell = orthobrick(0, 0, 0;'\n #cellString += ' {0}, {0}, {0});\\n'.format(l)\n cellString = 'solid cell = plane(0, 0, {0}; 0, 0, {0})'.format(l)\n cellString += ' and plane(0, {0}, 0; 0, {0}, 0)'.format(l)\n cellString += ' and plane({0}, 0, 0; {0}, 0, 0)'.format(l)\n cellString += ' and plane(0, 0, 0; 0, 0, -{0})'.format(l)\n cellString += ' and plane(0, 0, 0; 0, -{0}, 0)'.format(l)\n cellString += ' and plane(0, 0, 0; -{0}, 0, 0);\\n'.format(l)\n matrixString = 'solid matrix = cell'\n attempt = 0\n v = o.getProperty('verticesNumber')\n r = o.getProperty('polygonalDiskRadius')\n h = o.getProperty('polygonalDiskThickness')\n ready = 0\n tmpPcs = []\n while ready < desiredDisksNumber and attempt < maxAttempts:\n attempt += 1\n if len(pcs) > 0:\n name = int(pcs[len(pcs) - 1].number()) + 1\n pc = PolygonCylinderInTheShell(r, h, name, int(v))\n else:\n pc = PolygonCylinderInTheShell(r, h, 0, int(v))\n random.seed(datetime.now())\n alpha = random.random() * 2 * math.pi\n beta = random.random() * 2 * math.pi\n gamma = random.random() * 2 * math.pi\n # rotate around 0x\n pc.changeByMatrix(np.array([\n [1, 0, 0, 0],\n [0, math.cos(alpha), -math.sin(alpha), 0],\n [0, math.sin(alpha), math.cos(alpha), 0],\n [0, 0, 0, 1]\n ]))\n # rotate around 0y\n pc.changeByMatrix(np.array([\n [math.cos(beta), 0, math.sin(beta), 0],\n [0, 1, 0, 0],\n [-math.sin(beta), 0, math.cos(beta), 0],\n [0, 0, 0, 1]\n ]))\n # rotate around 0z\n pc.changeByMatrix(np.array([\n [math.cos(gamma), -math.sin(gamma), 0, 0],\n [math.sin(gamma), math.cos(gamma), 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]\n ]))\n # translate into random point of the box\n dx = l * random.random()\n dy = l * random.random()\n dz = l * random.random()\n pc.changeByMatrix(np.array([\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [dx, dy, dz, 1]\n ]))\n tmpPcs = []\n copiedCount = 0\n pcToCheck = None\n for ix in [-1, 0, 1]:\n for iy in [-1, 0, 1]:\n for iz in [-1, 0, 1]:\n pc1 = copy.copy(pc)\n pc1.setCopied(copiedCount)\n copiedCount += 1\n pc1.changeByMatrix(np.array([\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [ix * l, iy * l, iz * l, 1]\n ]))\n tmpPcs.append(pc1)\n if (ix, iy, iz) == (0, 0, 0):\n pcToCheck = pc1\n flag = 0\n for oldPc in pcs:\n #for pc in tmpPcs:\n # if disksCross(oldPc, pc) or\\\n # disksCross(pc, oldPc) or\\\n # diskDiskInTheShellCross(oldPc, pc) or\\\n # diskDiskInTheShellCross(pc, oldPc):\n # flag = 1\n # break\n if disksCross(oldPc, pc) or\\\n disksCross(pc, oldPc) or\\\n diskDiskInTheShellCross(oldPc, pc) or\\\n diskDiskInTheShellCross(pc, oldPc):\n flag = 1\n break\n if flag != 1:\n ready += 1\n for pc in tmpPcs:\n pcs.append(pc)\n \n toPop = []\n for i, pc in enumerate(pcs):\n c = pc.c()\n if not 0 < c.x() < l or not 0 < c.y() < l or not 0 < c.z() < l:\n if not boxCrossByDiskInTheShell(pc):\n toPop.append(i)\n for i in toPop[::-1]:\n pcs.pop(i)\n s = 'End of attempt {0} ready {1} of {2}'\n print(s.format(attempt, ready, desiredDisksNumber))\n print('Checking for percolation len is {}'.format(len(pcs)))\n for pc in pcs:\n print(pc)\n checkPercolation(pcs)\n s = ' and not filler and not shell;\\ntlo matrix -transparent -maxh={0};\\n'\n matrixString += s.format(maxhMatrix)\n f = open(o.getProperty('fname'), 'w')\n f.write('algebraic3d\\n')\n f.write(cellString)\n if len(pcs) > 0:\n fillerString = 'solid filler = cell and ('\n shellString = 'solid shell = cell and ('\n for i, pc in enumerate(pcs):\n pc.printToCSG(f)\n if i != 0:\n fillerString += ' or polygonalDisk{0}'.format(pc.number())\n shellString += ' or pdShell{0}'.format(pc.number())\n else:\n fillerString += 'polygonalDisk{0}'.format(pc.number())\n shellString += 'pdShell{0}'.format(pc.number())\n fillerString += ');\\ntlo filler -maxh={0};\\n'.format(maxhFiller)\n s = ') and not filler;\\ntlo shell -maxh={0};\\n'\n shellString += s.format(maxhShell)\n f.write(fillerString)\n f.write(shellString)\n f.write(matrixString)\n print('Volume fraction is {}'.format(ready * math.pi * r**2 * h / l**3))\n mp = MatricesPrinter(pcs)\n pp = PropertiesPrinter(pcs)\n\n \nmainExfoliation()\n","sub_path":"mainExfoliationShellPeriodic.py","file_name":"mainExfoliationShellPeriodic.py","file_ext":"py","file_size_in_byte":7017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"600218024","text":"import bmm.parameters as para\n\nenv_type = para.game_version\nalgorithm_type = para.algorithms\npolicy_type = para.policy_type\ngame_type = para.game_type\npath = para.DataSavePath\n\nresult_dir = 'results-{0}-{1}-{2}-{3}'.format(env_type, algorithm_type, policy_type, game_type)\n\n\nimport numpy as np\nimport pandas as pd\n\nwindow_size = 100\nadjustment_rate_plot_range = 1\nwindow = 995000\nprint_episode = para.print_episode\n\n# Load Q value table\nplot_Q_list = [] # Initialize the Q_list for plot\nQ_table = np.load(path + 'numpy_data/' + result_dir + '/' + 'q_table_' + str(print_episode) + \".npy\") # Load Q_table\nPE_rows = np.array(np.arange(para.state_limits)) # States Prediction errors\nAR_cols = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # Actions: adjustment rate\n\n# Result save path\nsave_path = path + 'plot_results/' + result_dir\n\nimport numpy as np\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\nimport os\nimport matplotlib\nimport numpy as np\nimport matplotlib.cm as cm\nimport matplotlib.mlab as mlab\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nimport matplotlib.pyplot as plt\n\nmatplotlib.rcParams['xtick.direction'] = 'out'\nmatplotlib.rcParams['ytick.direction'] = 'out'\n\ndelta = 0.025\nx = PE_rows\ny = AR_cols\n\n\nX, Y = np.meshgrid(x, y)\n\nZ = np.array(Q_table)\nZ = np.transpose(Z)\n\nfig = plt.figure()\nplt.rc('font', family='serif', size=13)\n\nax = fig.gca(projection = '3d')\nsurf=ax.plot_surface(Y, X, Z, rstride=1, cstride=1,cmap=cm.coolwarm,\n linewidth=0, antialiased=True)\nax.contour(Y, X, Z, zdir='z', offset=np.min(Z)-1, cmap=cm.coolwarm)\nax.set_xlabel('Adjustment Rate')\nif para.game_version == \"OutlierGame-v1\":\n ax.set_ylabel('State')\nelif para.game_version == \"OutlierGame-v2\":\n ax.set_ylabel('State')\nax.set_zlabel('Q value')\nax.zaxis.set_major_locator(LinearLocator(6))\nax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\nfig.colorbar(surf, shrink=0.5, aspect=5) # colour bar\nax.set_zlim([np.min(Z)-1,0])\n\n\n\nplt.show()","sub_path":"bmm/plot_code/plot_3d.py","file_name":"plot_3d.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"479071961","text":"\"\"\"\r\nDefinition of TreeNode:\r\nclass TreeNode:\r\n def __init__(self, val):\r\n self.val = val\r\n self.left, self.right = None, None\r\n\"\"\"\r\nclass Solution:\r\n \"\"\"\r\n @param root: The root of binary tree.\r\n @return: An integer\r\n \"\"\" \r\n def maxDepth(self, root):\r\n if root is None:\r\n return 0\r\n \r\n self.depth = 0\r\n self.dfs(root, 1)\r\n return self.depth\r\n \r\n def dfs(self, node, height):\r\n if node.left is None and node.right is None:\r\n self.depth = max(self.depth, height)\r\n return\r\n if node.left:\r\n self.dfs(node.left, height + 1)\r\n if node.right:\r\n self.dfs(node.right, height + 1)","sub_path":"src/MaximumDepthOfBinaryTree.py","file_name":"MaximumDepthOfBinaryTree.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"481493648","text":"\nimport os\nos.environ['THEANO_FLAGS'] = 'device=gpu, floatX=float32'\nimport theano\n\nimport numpy as np\nimport numpy.random as npr\n\nimport matplotlib.pyplot as plt\nplt.ion()\n\nimport deepnet\nimport deepnet.autoencoder\nfrom deepnet.autoencoder import Autoencoder, SparseAutoencoder\nfrom deepnet.autoencoder import SparseTrainer, sgd\nfrom deepnet.functions import Linear, NoisyLIFApprox\nimport deepnet.image_tools\n\nfrom skdata.mnist.dataset import MNIST\nmnist = MNIST()\nmnist.meta # accessing this forces data arrays to be built\n\nimages = mnist.arrays['train_images'].astype('float32')\nimages = (images - images.mean()) / images.std()\n\nlabels = np.asarray([m['label'] for m in mnist.meta if m['split'] == 'train'])\nimshape = images.shape[1:]\n\nplt.figure(1)\nplt.clf()\ndeepnet.image_tools.tile(images, rows=5, cols=10)\n\n################################################################################\n### train one layer\n\n# loadfile = None\nloadfile = 'mnist_layer.pkl'\n\nif loadfile is None or not os.path.exists(loadfile):\n\n linear = Linear(slope=1.0)\n noisylif = NoisyLIFApprox(\n tRef=0.02, tauRC=0.06, alpha=10.0, xint=-0.5, amp=1./41, sigma=0.05)\n\n # layer = SparseAutoencoder(visshape=imshape, hidshape=(50,50),\n # rfshape=(9,9), f=noisylif, g=linear)\n layer = SparseAutoencoder(visshape=imshape, hidshape=(40,40),\n rfshape=(9,9), f=noisylif, g=linear)\n\n if loadfile is not None:\n layer.tofile(loadfile)\nelse:\n layer = deepnet.CacheObject.fromfile(loadfile)\n\n################################################################################\ntrain_params = {'rho': 0.01, 'lamb': 25, 'noise_std': 0.2}\ntrainer = SparseTrainer(layer, **train_params)\n\nsgd(trainer, images, nepochs=30, rate=0.05)\n\nif 0:\n ### untied training\n sgd(trainer, images, nepochs=1, rate=0.05)\n layer.untie()\n\n trainer = SparseTrainer(layer, **train_params)\n sgd(trainer, images, nepochs=30, rate=0.05)\n\nresults = layer.compVHV(images)\n\nplt.figure(1)\nplt.clf()\ndeepnet.image_tools.compare([images, results], vlims=(-1,1))\n","sub_path":"examples/mnist_layer.py","file_name":"mnist_layer.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"551852910","text":"#newlist = [*expression* for item in iterable if condition == True]\n\ntemps = [221, 234, 340, 230]\n\nnew_temps = [temp / 10 for temp in temps] #new way using list comprehension\n\n''' new_temps = []\nfor temp in temps:\n new_temps.append(temp / 10)''' #old way using a for loop\n\nprint(new_temps)\n\n\n\n\n\ntemps1 = [221, 234, 340, -9999, 230]\nnew_temps1 = [temp / 10 for temp in temps1 if temp != -9999]\nprint(new_temps1)\n\n\n\n\n\n#if / else list comprehension where if/else goes in between expression and \"for\" statement\ntemps2 = list(temps1)\nnew_temps2 = [temp / 10 if temp != -9999 else 0 for temp in temps2] # -9999 is replaced by 0\nprint(new_temps2)\n","sub_path":"Python Tutorial/python_basics/list_comprehension.py","file_name":"list_comprehension.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"86639866","text":"from decimal import Decimal\nfrom app.core.init import GET_FUNDS, INSERT_TRANSFER\nfrom app.core.models.adapters import xrates\n\n\nclass Transfer:\n @classmethod\n async def get_funds(cls, app, payer, amount: Decimal) -> Decimal:\n \"\"\" Получить остаток \"\"\"\n debt_credt = Decimal('0.0000')\n async with app['pg'].acquire() as pgcon:\n async with pgcon.cursor() as c:\n await c.execute(GET_FUNDS, ({'payer_id': payer[1], 'currency': payer[2]}))\n debt_credt = await c.fetchone()\n debt_credt = debt_credt[0]\n debt_credt = debt_credt if debt_credt else Decimal('0.0000')\n return debt_credt\n\n @classmethod\n async def create(cls, app, payer: tuple, payee: tuple, amount_payer: Decimal, description=None) -> Decimal:\n errors = []\n async with app['pg'].acquire() as pgcon:\n async with pgcon.cursor() as c:\n try:\n await c.execute(INSERT_TRANSFER, {\n 'payer_id': payer[1],\n 'payee_id': payee[1],\n 'amount': amount_payer,\n 'currency': payer[2],\n 'description': description})\n if payer[2] != payee[2]:\n # Требуется пересчёт валют\n amount_payee = await Transfer.recalcuale_amount(amount_payer, payer[2], payee[2])\n await c.execute(INSERT_TRANSFER, {\n 'payer_id': payer[1],\n 'payee_id': payee[1],\n 'amount': amount_payee,\n 'currency': payee[2],\n 'description': description})\n except Exception as e:\n errors.append({3001: str(e)})\n return errors\n\n @staticmethod\n async def recalcuale_amount(amount: Decimal, payer_currency, payee_currency):\n rates = await xrates.parse()\n base = rates.get('base')\n payee_k = 1 if payee_currency == base else rates.get('rates', {}).get(payee_currency)\n payer_k = 1 if payer_currency == base else rates.get('rates', {}).get(payer_currency)\n if payee_k and payer_k:\n amount /= payer_k \n amount *= payee_k\n return amount.quantize(Decimal('1.0000'))","sub_path":"app/core/models/transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"211827392","text":"\"\"\"\nThis is the the BOBA mosFET Mission Control script. \n\n@author: Hélène Verhaeghe\n@Coauthor (Satellite): Jerôme De Saulles \n\"\"\"\n\n#import necessary libaries\nimport cv2 # This is the vision library OpenCV\nimport numpy as np # This is a library for mathematical functions for python (used later)\nimport socket # This library will allow you to communicate over the network\nimport time # This library will allow us to access the system clock for pause/sleep/delay actions\nimport cv2.aruco as aruco #Import the AruCo library\nimport math # Import the math library\nimport itertools as it\nimport logging # This library will offer us a different method to print information on the terminal (better for debugging purposes)\nimport paho.mqtt.client as mqtt # This is the library to do the MQTT communications\nimport time # This is the library that will allow us to use the sleep function\nimport random\nimport threading\n\n\n# Initialise variables\nAngleReached = 0 #Field 4 MQTT\nDistanceReached = 0 #Field 5 MQTT\nCommandCount_A = 0 #Keeping Track of number of turning command was send to BB8\nCommandCount_D = 0 #Keeping Track of number of moving command was send to BB8\nInPosition = 0\n\nprint(\"CommandCount_A: \"+str(CommandCount_A))\nprint(\"CommandCount_D: \"+str(CommandCount_D))\n\n\n## MQTT Fields - BOBAmosFET\n# Field 1: Angle\n# Field 2: Distance\n# Field 3: Command\n# Field 4: AngleReached\n# Field 5: DistanceReached\n# Field 6: MagneticField \n# Field 7: \n# Field 8: ShipHeight\n\n# Satellite functions\n\ndef rotationMatrixToEulerAngles(R) :\n\n sy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])\n\n singular = sy < 1e-6\n\n if not singular :\n x = math.atan2(R[2,1] , R[2,2])\n y = math.atan2(-R[2,0], sy)\n z = math.atan2(R[1,0], R[0,0])\n else :\n x = math.atan2(-R[1,2], R[1,1])\n y = math.atan2(-R[2,0], sy)\n z = 0\n\n return np.array([x, y, z])\n\ndef second_smallest(numbers):\n m1, m2 = float('inf'), float('inf')\n for x in numbers:\n if x <= m1:\n m1, m2 = x, m1\n elif x < m2:\n m2 = x\n return m2\n\ndef vision():\n\n # Load the camera calibration values\n Camera = np.load('Calibrated_Rig_Camera.npz')\n CM = Camera['CM'] # camera matrix\n dist_coef = Camera['dist_coef'] # distortion coefficients from the camera\n\n aruco_dict = aruco.Dictionary_get(\n aruco.DICT_4X4_50) # Load the aruco dictionary\n pa = aruco.DetectorParameters_create() # Set the detection parameters\n\n # Select the correct camera (0) = front camera, (1) = rear camera\n cap = cv2.VideoCapture(1)\n\n # Set the width and heigth of the camera to 640x480\n cap.set(3, 640)\n cap.set(4, 480)\n\n # Create two opencv named windows\n cv2.namedWindow(\"frame-image\", cv2.WINDOW_AUTOSIZE)\n\n # Position the window\n cv2.moveWindow(\"frame-image\", 0, 0)\n\n t_end = time.time() + 1\n\n # Execute this continuously\n while time.time() < t_end:\n # Capture current frame from the camera\n ret, frame = cap.read()\n\n # Convert the image from the camera to Gray scale\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Run the detection formula\n corners, ids, rP = aruco.detectMarkers(gray, aruco_dict)\n\n # # Count the number of Arucos visible\n # try:\n # IDScount = len(ids)\n # except:\n # IDScount = 0\n\n # Calculate the pose of the markers\n rvecs, tvecs, _objPoints = aruco.estimatePoseSingleMarkers(corners, 53, CM, dist_coef) # <<<< IMPORTANT: number needs changing to width of printed arucos (in mm)\n # Draw the detected markers as an overlay\n out = aruco.drawDetectedMarkers(frame, corners, ids)\n\n # Create Coordinate Storage Arrays\n X = [] #X Coordinate Locations Array\n Y = []\n Z = []\n ID = []\n\n # Run loop if ids are detected\n if ids is not None:\n for i, id in enumerate(ids):\n # Overlay the axis on the image\n out = aruco.drawAxis(out, CM, dist_coef, rvecs[i][0][:], tvecs[i][0][:], 30)\n # Print the tvecs tranformation matrix or Aruco coordinates\n # print(\"X = {:4.1f} Y = {:4.1f} Z = {:4.1f} ID = {:2d}\".format(tvecs[i][0][0], tvecs[i][0][1], tvecs[i][0][2], ids[i][0]))\n X.append(tvecs[i][0][0])\n Y.append(tvecs[i][0][1])\n Z.append(tvecs[i][0][2])\n ID.append(ids[i][0])\n # debugTEST = []\n \n \n # Display the original frame in a window and aruco markers\n cv2.imshow('frame-image', frame)\n\n\n # If the button q is pressed in one of the windows\n if cv2.waitKey(20) & 0xFF == ord('q'):\n # Exit the While loop\n break\n\n # When everything done, release the capture\n cap.release()\n # close all windows\n cv2.destroyAllWindows()\n # # exit the kernel\n # exit(0)\n return X, Y, Z, ID, rvecs\n\ndef initialScan():\n X, Y, Z, ID, rvecs = vision()\n\n # Ensure all coordinates are +ve\n X = [abs(ele) for ele in X]\n Y = [abs(ele) for ele in Y]\n Z = [abs(ele) for ele in Z]\n\n # Combine X(0), Y(1), Z(2) coordinates and ID(3) into P (point) variables\n P = []\n ID_count = len(ID)\n for i in range(ID_count):\n P.append(\n [ID[i], X[i], Y[i], Z[i]]\n )\n # print(P)\n\n # Find the P value which corresponds to the Robot (ID = 0)\n robot_ind = [i for i, el in enumerate(P) if 0 in el][0]\n\n distance = []\n # Count the distances between the robot and the other IDs\n for i in range(ID_count):\n # print(P[i][1], P[robot_ind][1])\n distance.append(\n math.sqrt( ((P[i][1] - P[robot_ind][1]) **2) + ((P[i][2] - P[robot_ind][2]) **2) )\n ) #Compute using 2D Pythagoras\n\n # print(\"Distance vector =\", distance)\n min_distance = second_smallest(distance)\n min_ind = distance.index(min_distance)\n min_ID = P[min_ind][0]\n print(\"The nearest ID is\", min_ID)\n # print(\"The distance to ID\", min_ID, \"from the robot is\", min_distance, \"mm\")\n\n # Store the rvec's for the robot and nearest marker\n rob_rvec = rvecs[robot_ind][0][:]\n marker_rvec = rvecs[min_ind][0][:] # Replace 2 with min_ind when working properly\n output_rvecs = rvecs\n output_rvecs = np.delete(output_rvecs, robot_ind, 0)\n\n # Calculate the relative rotation about the Z axis between the robot ID and nearest ID (beta in notes)\n R_ref_to_cam = cv2.Rodrigues(rob_rvec)[0] #reference to camera\n R_test_to_cam = cv2.Rodrigues(marker_rvec)[0] #test to camera\n R_cam_to_ref = np.transpose(R_ref_to_cam) #inverse of reference to camera\n R_test_to_ref = np.matmul(R_test_to_cam,R_cam_to_ref) #test to reference\n angles_matrix = rotationMatrixToEulerAngles(R_test_to_ref) \n beta = np.degrees(angles_matrix[2])\n beta = 0 - beta\n\n # Calculate the relative angle between the Robot ID axis and the nearest ID location (sigma in notes)\n delta_x = P[robot_ind][1] - P[min_ind][1]\n delta_y = P[min_ind][2] - P[robot_ind][2]\n\n if delta_x > 0:\n if delta_y > 0:\n # upper right\n alpha = np.degrees(math.atan( (delta_x) / (delta_y) ))\n else:\n # lower right\n alpha = np.degrees(math.atan( (-1 * delta_y) / (delta_x) )) + 90\n else:\n if delta_y > 0:\n # upper left\n alpha = np.degrees(math.atan( (delta_y) / (-1 * delta_x) )) + 270\n else:\n # lower left\n alpha = np.degrees(math.atan( (-1 * delta_x) / (-1 * delta_y) )) + 180\n\n # print(\"Alpha =\", alpha, \"degrees\")\n\n # Combine beta and alpha above to calculate the movement direction needed by the robot (sigma in notes)\n angle = alpha - beta\n\n # Convert to counter clockwise motion if faster\n if angle > 180:\n angle = angle - 360\n\n # Rewrite the aruco locations with the robot location removed\n # ADD LOGICAL SORTING FUNCTION HERE TO ARRANGE ARUCOS IN ORDER THEY SHOULD BE VISITED\n arucoLocations = P\n del arucoLocations[robot_ind]\n\n return(arucoLocations, output_rvecs, angle, min_distance)\n \ndef BB8_check(target_arucoLocations, target_rvecs, tolerance):\n X, Y, Z, ID, rvecs = vision()\n\n # Ensure all coordinates are +ve\n X = [abs(ele) for ele in X]\n Y = [abs(ele) for ele in Y]\n Z = [abs(ele) for ele in Z]\n\n # Combine X(0), Y(1), Z(2) coordinates and ID(3) into P (point) variables\n P = []\n ID_count = len(ID)\n for i in range(ID_count):\n P.append(\n [ID[i], X[i], Y[i], Z[i]]\n )\n # print(P)\n\n # Find the P value which corresponds to the Robot (ID = 0)\n robot_ind = [i for i, el in enumerate(P) if 0 in el][0]\n robot_loc = P[robot_ind]\n robot_rvec = rvecs[robot_ind][0][:]\n\n distance = []\n # Count the distances between the robot and the target marker\n for i in range(len(target_arucoLocations)):\n # print(P[i][1], P[robot_ind][1])\n distance.append(\n math.sqrt( ((target_arucoLocations[i][1] - robot_loc[1]) **2) + \n ((target_arucoLocations[i][2] - robot_loc[2]) **2) )\n ) #Compute using 2D Pythagoras\n print('Distance i =', distance[i])\n\n\n # Define the acceptable tolerance from the target aruco location (in mm)\n dist_tol = tolerance\n # Logic for calculating either corrected target angle+distance or next target angle+distance\n if distance[0] < dist_tol and len(distance) == 1: # Target reached, final marker\n target_angle = 0\n target_distance = 0\n state = 1\n command = 0\n\n elif distance[0] < dist_tol and len(distance) == 2: # Target reached, move onto next marker\n # Calculate angle to next target aruco\n marker_rvec = target_rvecs[1][0][:] # Define target rvec\n\n # Calculate the relative rotation about the Z axis between the robot ID and nearest ID (beta in notes)\n R_ref_to_cam = cv2.Rodrigues(robot_rvec)[0] #reference to camera\n R_test_to_cam = cv2.Rodrigues(marker_rvec)[0] #test to camera\n R_cam_to_ref = np.transpose(R_ref_to_cam) #inverse of reference to camera\n R_test_to_ref = np.matmul(R_test_to_cam,R_cam_to_ref) #test to reference\n angles_matrix = rotationMatrixToEulerAngles(R_test_to_ref) \n beta = np.degrees(angles_matrix[2])\n beta = 0 - beta\n\n # Calculate the relative angle between the Robot ID axis and the nearest ID location (sigma in notes)\n delta_x = robot_loc[1] - target_arucoLocations[1][1]\n delta_y = target_arucoLocations[1][2] - robot_loc[2]\n if delta_x > 0:\n if delta_y > 0:\n # upper right\n alpha = np.degrees(math.atan( (delta_x) / (delta_y) ))\n else:\n # lower right\n alpha = np.degrees(math.atan( (-1 * delta_y) / (delta_x) )) + 90\n else:\n if delta_y > 0:\n # upper left\n alpha = np.degrees(math.atan( (delta_y) / (-1 * delta_x) )) + 270\n else:\n # lower left\n alpha = np.degrees(math.atan( (-1 * delta_x) / (-1 * delta_y) )) + 180\n # Combine beta and alpha above to calculate the movement direction needed by the robot (sigma in notes)\n target_angle = alpha - beta\n # Convert to counter clockwise motion if faster\n if target_angle > 180:\n target_angle = target_angle - 360\n\n # Output the target distance\n target_distance = distance[1]\n state = 1\n command = 0\n\n elif distance[0] > dist_tol: # Target missed, recalculate angle to current target\n # Calculate angle to current target aruco\n # Calculate angle to next target aruco\n marker_rvec = target_rvecs[0][0][:] # Define target rvec\n\n # Calculate the relative rotation about the Z axis between the robot ID and nearest ID (beta in notes)\n R_ref_to_cam = cv2.Rodrigues(robot_rvec)[0] #reference to camera\n R_test_to_cam = cv2.Rodrigues(marker_rvec)[0] #test to camera\n R_cam_to_ref = np.transpose(R_ref_to_cam) #inverse of reference to camera\n R_test_to_ref = np.matmul(R_test_to_cam,R_cam_to_ref) #test to reference\n angles_matrix = rotationMatrixToEulerAngles(R_test_to_ref) \n beta = np.degrees(angles_matrix[2])\n beta = 0 - beta\n\n # Calculate the relative angle between the Robot ID axis and the nearest ID location (sigma in notes)\n delta_x = robot_loc[1] - target_arucoLocations[1][1]\n delta_y = target_arucoLocations[1][2] - robot_loc[2]\n if delta_x > 0:\n if delta_y > 0:\n # upper right\n alpha = np.degrees(math.atan( (delta_x) / (delta_y) ))\n else:\n # lower right\n alpha = np.degrees(math.atan( (-1 * delta_y) / (delta_x) )) + 90\n else:\n if delta_y > 0:\n # upper left\n alpha = np.degrees(math.atan( (delta_y) / (-1 * delta_x) )) + 270\n else:\n # lower left\n alpha = np.degrees(math.atan( (-1 * delta_x) / (-1 * delta_y) )) + 180\n # Combine beta and alpha above to calculate the movement direction needed by the robot (sigma in notes)\n target_angle = alpha - beta\n # Convert to counter clockwise motion if faster\n if target_angle > 180:\n target_angle = target_angle - 360\n\n # Output the target distance\n target_distance = distance[0]\n state = 0\n command = 1\n\n\n return(state, target_angle, target_distance, command)\n\n\n# Connect to MQTT Server\n\n# After we connect we subsribe to one (or more) topics in this case the topic number 1\ndef on_connect(client,userdata,flags,rc):\n print (\"Connected with result code \"+str(rc))\n client.subscribe(MainTopic+\"4\")\n client.subscribe(MainTopic+\"5\")\n \n\n# The callback for when a PUBLISH message is received from the server. I.e. when a new value for the topic we subscribed to above updates\ndef on_message(client, userdata, msg):\n global Check\n global InPosition\n global TargetAngle\n global TargetDistance\n global CommandCount_A\n global CommandCount_D\n global Command\n \n print(str(time.time())+\" In topic: \"+msg.topic+\" the value was \"+ str(int(msg.payload.rstrip(b'\\x00'))))\n\n \n data = int(msg.payload.rstrip(b'\\x00'))\n\n if msg.topic == \"BOBAmosFET/4\":\n \n AngleReached = data\n \n if AngleReached == CommandCount_A + 1:\n \n Command = 2 #Satellite Function output\n print(\"Command value change to \"+str(Command))\n\n CommandCount_A = CommandCount_A + 1 # Set to next command index\n print(\"CommandCount_A: \"+str(CommandCount_A))\n\n elif msg.topic == \"BOBAmosFET/5\":\n \n DistanceReached = data\n \n if DistanceReached == CommandCount_D + 1:\n\n Check = 1 \n print(\"Check value change to \"+str(Check))\n\n InPosition, TargetAngle, TargetDistance, Command = BB8_check(target_arucoLocations, target_rvecs, tolerance)\n #print('InPosition, TargetAngle and TargetDistance =', InPosition, TargetAngle, TargetDistance)\n\n \n print(\"InPosition value change to \"+str(InPosition))\n #TargetAngle = 0 #Satellite Function output\n print(\"TargetAngle value change to \"+str(TargetAngle))\n #TargetDistance = 0 #Satellite Function output\n print(\"TargetDistance value change to \"+str(TargetDistance))\n #Command = 3 #Satellite Function output\n print(\"Command value change to \"+str(Command))\n\n CommandCount_D= CommandCount_D + 1 # Set to next command index\n print(\"CommandCount_D: \"+str(CommandCount_D))\n #else:\n #pass \n\n# Create the mqtt client object\nclient = mqtt.Client() \n# Assign the function for the connection event\nclient.on_connect = on_connect\n# Assign the function for the new message event\nclient.on_message = on_message\n\n# Set the username and password\nclient.username_pw_set(\"student\",password=\"smartPass\")\n\n# Connect to the server using a specific port with a timeout delay (in seconds)\nclient.connect(\"ec2-3-10-235-26.eu-west-2.compute.amazonaws.com\",31415,60)\n\n# Create your main topic string. Everything else should be fields with values 1-8\nMainTopic = \"BOBAmosFET/\"\n\n# Start the client\nclient.loop_start() \n\n################################ START ################################\n\n############################# INITIAL MODE ##############################\n\n### Send Command to Mill.Falcon ###\n\n# Generate random number between 0 and 10\nshipHeight = random.randint(0, 10)\n#print(\"Random integer from 0 to 10\")\n#print(\"Random integer: \", shipHeight)\n\n\n# Publish the value (integer) as a string. All messages are strings\nclient.publish(MainTopic+\"8\",str(shipHeight))\n# Plot in the terminal what we just did\nprint(\"%s %d\" % (MainTopic+\"8\", shipHeight))\n\n\n### Initial Scan ### \n\n#TargetAngle = 45\n#TargetDistance = 100 \narucoLocations, arucoRvecs, TargetAngle, TargetDistance = initialScan()\n#arucoRvecs = [[[-2.65077743, 0.01517437, 0.0167672 ]],[[ 3.45453988, -0.04192978, 0.42548113]]]\n#arucoLocations = [[11, 27.951521361774212, 88.53147453041412, 682.1787133172342], [13, 107.79970108395187, 105.40086628164487, 742.4444729628245]]\n\nfor i,_ in enumerate(arucoLocations):\n\n if i < len(arucoLocations)-1:\n\n target_arucoLocations = [[]]\n target_arucoLocations[i][:] = arucoLocations[i][:]\n target_arucoLocations.append(arucoLocations[i+1][:])\n print('target_arucoLocations =', target_arucoLocations)\n\n target_rvecs = np.array([[arucoRvecs[i][0][:]],[arucoRvecs[i+1][0][:]] ])\n # print('target_rvecs =', target_rvecs)\n tolerance = 50 # Distance tolerance to target aruco (in mm)\n\n else:\n target_arucoLocations = [[]]\n target_arucoLocations[i][:] = arucoLocations[i][:]\n print('target_arucoLocations =', target_arucoLocations)\n\n target_rvecs = np.array([[arucoRvecs[i][0][:]] ])\n # print('target_rvecs =', target_rvecs)\n tolerance = 50 # Distance tolerance to target aruco (in mm)\n\n InPosition = 0\n Check = 1\n Command = 1\n\n\n while InPosition < 1:\n\n ############################# TURNING MODE ##############################\n if Check == 1:\n\n print(\"Entered TURNING MODE\")\n ### Send Command to BB8\n\n Angle = TargetAngle\n Distance = 0\n\n # Publish the value (integer) as a string. All messages are strings\n client.publish(MainTopic+\"1\",str(Angle))\n client.publish(MainTopic+\"2\",str(Distance))\n client.publish(MainTopic+\"3\",str(Command))\n\n # Plot in the terminal what we just did\n print(\"%s %d\" % (MainTopic+\"1\", Angle))\n print(\"%s %d\" % (MainTopic+\"2\", Distance))\n print(\"%s %d\" % (MainTopic+\"3\", Command))\n\n Command = 0\n Check = 0\n \n \n ### 3. Wait for a signal from BB8. Once signal received, go to MOVING MODEs\n while Command == 0:\n print(\"waiting for a signal from BB8\")\n pass\n\n ############################# MOVING MODE ##############################\n print(\"Entered MOVING MODE\")\n if Command == 2:\n ### Send Command to BB8\n \n Angle = 0\n Distance = TargetDistance\n\n # Publish the value (integer) as a string. All messages are strings\n client.publish(MainTopic+\"1\",str(Angle))\n client.publish(MainTopic+\"2\",str(Distance))\n client.publish(MainTopic+\"3\",str(Command))\n\n # Plot in the terminal what we just did\n print(\"%s %d\" % (MainTopic+\"1\", Angle))\n print(\"%s %d\" % (MainTopic+\"2\", Distance))\n print(\"%s %d\" % (MainTopic+\"3\", Command))\n\n Command = 0\n ### 3. Once signal from BB8, position-check function will be triggered within on_message\n \n while Command == 0:\n print(\"waiting for a signal from BB8\")\n pass\n \n\n ############################# DETECTING MODE ##############################\n print(\"Entered DETECTING MODE\")\n\n\n\n\n\nclient.loop_stop()\n# Disconnect\nclient.disconnect()\n","sub_path":"MissionControl/Mechatronic-Project-Satellite/MissionControlTest2_SAT.py","file_name":"MissionControlTest2_SAT.py","file_ext":"py","file_size_in_byte":20670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"521220773","text":"# -*- coding: utf-8 -*-\nimport web\nfrom .models.todos import Todo, TodoTag\ndb = web.extensions.db\n\napp_jslink = ''\napp_desc = '待办列表'\n\ndb.create_all()\n\nurls = [\n \"/todos\", Todo,\n \"/todos/([^/]+)\", Todo,\n \"/tags\", TodoTag,\n \"/tags/([^/]+)\", TodoTag,\n ]\n","sub_path":"todo/appmain.py","file_name":"appmain.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"77564602","text":"import csv\nfrom numpy.linalg import norm\nfrom scipy import *\nfrom pylab import plot, show, legend,xlim,ylim,savefig,title,xlabel,ylabel,clf, loglog\nimport os\n\nwdatadir = \"../../../../../data/raw/P1P2P3/Beji/\"\nsdatadir = \"../../../../../data/postprocessing/Beji94FEM/o2/\"\nexp = \"sl\"\nwdir = wdatadir + exp+ \"/\"\nsexpdir = sdatadir + exp + \"/\"\n\nendt = 60\nbegt = 40 \nnts = []\nnwg1s = []\nnwg2s = []\nnwg3s = []\nnwg4s = []\nnwg5s = []\nnwg6s = []\nnwg7s = []\n\ns = wdir + \"NumWaveGauge.txt\"\nwith open(s,'r') as file1:\n readfile = csv.reader(file1, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n j = -1\n for row in readfile: \n if (j >= 0):\n nts.append(float(row[0]))\n nwg1s.append(float(row[1]))\n nwg2s.append(float(row[2]))\n nwg3s.append(float(row[3]))\n nwg4s.append(float(row[4]))\n nwg5s.append(float(row[5]))\n nwg6s.append(float(row[6]))\n nwg7s.append(float(row[7]))\n \n \n j = j + 1\n \n\nets = []\newg1s = []\newg2s = []\newg3s = []\newg4s = []\newg5s = []\newg6s = []\newg7s = [] \ns = wdir + \"WaveGauge.txt\"\nwith open(s,'r') as file1:\n readfile = csv.reader(file1, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n j = -1\n for row in readfile: \n if (j >= 0):\n ets.append(float(row[0]))\n ewg1s.append(float(row[1]))\n ewg2s.append(float(row[2]))\n ewg3s.append(float(row[3]))\n ewg4s.append(float(row[4]))\n ewg5s.append(float(row[5]))\n ewg6s.append(float(row[6]))\n ewg7s.append(float(row[7]))\n \n \n j = j + 1\n\nets0 = ets[1]\n\nendtei = int(endt/ets[1]) + 1 \nbegtei = int(begt/ets[1]) - 1\nets = array(ets[begtei:endtei])\newg1s = array(ewg1s[begtei:endtei])*100\newg2s = array(ewg2s[begtei:endtei])*100\newg3s = array(ewg3s[begtei:endtei])*100\newg4s = array(ewg4s[begtei:endtei])*100\newg5s = array(ewg5s[begtei:endtei])*100\newg6s = array(ewg6s[begtei:endtei])*100\newg7s = array(ewg7s[begtei:endtei])*100\n\n \nExpCom = []\nExpCom.append(ets)\nExpCom.append(ewg1s)\nExpCom.append(ewg2s)\nExpCom.append(ewg3s)\nExpCom.append(ewg4s)\nExpCom.append(ewg5s)\nExpCom.append(ewg6s)\nExpCom.append(ewg7s)\n\n\nmult = int(ets0/nts[1])\nendtni = int(endt/nts[1]) + 1\nbegtni = int(begt/nts[1]) - 1 \n\nnts = array(nts[begtni:endtni:mult])\nnwg1s = (array(nwg1s[begtni:endtni:mult])-0.4)*100\nnwg2s = array(nwg2s[begtni:endtni:mult])*100\nnwg3s = array(nwg3s[begtni:endtni:mult])*100\nnwg4s = array(nwg4s[begtni:endtni:mult])*100\nnwg5s = array(nwg5s[begtni:endtni:mult])*100\nnwg6s = array(nwg6s[begtni:endtni:mult])*100\nnwg7s = array(nwg7s[begtni:endtni:mult])*100\n \n \nNumCom = []\nNumCom.append(nts)\nNumCom.append(nwg1s)\nNumCom.append(nwg2s)\nNumCom.append(nwg3s)\nNumCom.append(nwg4s)\nNumCom.append(nwg5s)\nNumCom.append(nwg6s)\nNumCom.append(nwg7s)\n\n\nnc = len(NumCom)\n\nfor j in range(1,nc):\n sdir = sexpdir +\"WaveGauge\" + str(j) + \"/\"\n if not os.path.exists(sdir):\n os.makedirs(sdir)\n nn = len(nts) \n s = sdir + \"Numerical.dat\"\n with open(s,'w') as file1:\n for i in range(nn):\n s =\"%3.8f%5s%1.15f\\n\" %(NumCom[0][i],\" \",NumCom[j][i])\n file1.write(s)\n ne = len(ets) \n s = sdir + \"Experimental.dat\"\n with open(s,'w') as file1:\n for i in range(ne):\n s =\"%3.8f%5s%1.15f\\n\" %(ExpCom[0][i],\" \",ExpCom[j][i])\n file1.write(s)\n ","sub_path":"CODE/postprocessing/readplot/Beji/94CSV2DAT.py","file_name":"94CSV2DAT.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"622332001","text":"def swap_case(s):\n a = []\n for i in list(s):\n j = ''\n if i.isupper():\n j = i.lower()\n elif i.islower():\n j = i.upper()\n else:\n a.append(i)\n a.append(j)\n\n\n return ''.join(a)\n\nif __name__ == '__main__':\n s = input()\n result = swap_case(s)\n print(result)","sub_path":"swap_case.py","file_name":"swap_case.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"158421189","text":"from __future__ import unicode_literals\nfrom django.conf.urls import url\nfrom apps.pages import views\n\n\nurlpatterns = [\n url(r'^/?$', views.pages, name='dashboard_pages'),\n url(r'^/add_page/?$', views.add_page, name='dashboard_add_page'),\n url(r'^/edit_page_(?P[0-9]+)/?$', views.edit_page, name='dashboard_edit_page'),\n url(r'^/delete_page_(?P[0-9]+)/?$', views.delete_page, name='dashboard_delete_page'),\n url(r'^/menus/?$', views.menus, name='dashboard_menus'),\n url(r'^/menus/add_menu/?$', views.add_menu, name='dashboard_add_menu'),\n url(r'^/menus/edit_menu_(?P[0-9]+)/?$', views.edit_menu, name='dashboard_edit_menu'),\n url(r'^/menus/delete_menu_(?P[0-9]+)/?$', views.delete_menu, name='dashboard_delete_menu'),\n]\n","sub_path":"apps/pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"395929481","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom collections import Counter\n\n\n# In[11]:\n\n\namsterdam = pd.read_csv('datasets/amsterdam-attraction.csv')\n\namsterdam = amsterdam.dropna()\namsterdam.head()\nX=amsterdam.loc[:,['lat','lng']]\nX = X.dropna()\nX\n\n\n# In[27]:\n\n\n#run KMeans\nid_n=8\nkmeans = KMeans(n_clusters=id_n, random_state=0).fit(X)\ncluster = pd.DataFrame()\nid_label=kmeans.labels_\n\n\n# In[28]:\n\n\n#plot result\nptsymb = np.array(['b.','r.','m.','g.','c.','k.','b*','r*','m*','r^']);\nplt.figure(figsize=(12,12))\nplt.ylabel('Longitude', fontsize=12)\nplt.xlabel('Latitude', fontsize=12)\nfor i in range(id_n):\n cluster=np.where(id_label==i)[0]\n plt.plot(X.lat[cluster].values,X.lng[cluster].values,ptsymb[i])\nplt.show()\n\n\n# In[29]:\n\n\nimport math\n\ndef distance(origin, destination):\n lat1, lon1 = origin\n lat2, lon2 = destination\n radius = 6371 # km\n\n dlat = math.radians(lat2-lat1)\n dlon = math.radians(lon2-lon1)\n a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))\n d = radius * c\n\n return d\n\n","sub_path":"vagary/recommend_attractions.py","file_name":"recommend_attractions.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"346687037","text":"# 별찍는 함수 만들기\ndef square(number):\n\n # 주어지는 number가 3일 때가 가장 기본 형태 \n if number == 3:\n star = ['***','* *','***']\n return star\n\n # number가 3이 아닌 3의 거듭제곱일 때 재귀함수 이용\n else:\n # 리스트 star의 길이는 number\n star = [''] * number\n \n # square(number//3)의 리스트로부터 number에 대한 star을 만들어줌\n for i, s in enumerate(square(number//3)):\n\n # 새로운 star는 square(number//3)의 3배 길이이므로 i, i+(number//3), i+(number//3)*2마다 규칙성 생김\n # star[i]와 star[i+(number//3)*2]는 s의 3배를 해준 값\n # star[i+(number//3)]은 s + (number//3)만큼의 공백 + s 의 값\n star[i] = s*3\n star[i+(number//3)] = s + ' ' * (number//3) + s\n star[i+(number//3)*2] = s*3\n\n return star\n\n\nnumber = int(input())\n\n# square(number)는 number길이 만큼의 리스트 형태이므로 요소별로 출력\nfor s in square(number):\n print(s)\n","sub_path":"code/jina/재귀/별찍기-10.py","file_name":"별찍기-10.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"425212710","text":"#!/usr/bin/env python\nimport sys, OpenGL, PySide.QtOpenGL\nsys.path += ['.']\nfrom PySide.QtCore import *\nfrom PySide.QtGui import *\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom SceneManager import SceneManager\nfrom MainWindow import MainWindow\nfrom Entities import *\nfrom Loader import Load\nfrom Utils import *\n\n\nSM = SceneManager()\nsphere = Entity()\nsphere.m_mesh = Load('model.ply')\nsphere.m_name = 'sphere1'\nsphere.m_position = vector3(0,-1,-3.8)\n\n\ncube = Entity()\ncube.m_mesh = Load('cube.ply')\ncube.m_name = 'cube1'\ncube.m_position = vector3(0.3,3,-3.6)\ncube.m_rotate = vector4(0.4,0,1,-10)\n\n\nSM.AddEntity('sphere1', sphere)\nSM.AddEntity('cube1', cube)\n\n\n\napp = QApplication(sys.argv)\nw = MainWindow(60, SM)\n\n\n\nw.mainWindow.show()\n\n\nglMatrixMode(GL_MODELVIEW)\nglLoadIdentity()\nglTranslate(sphere.m_position.x, sphere.m_position.y, sphere.m_position.z)\ntemp = glGetDoublev(GL_MODELVIEW_MATRIX)\nsphere.m_matrix1 = transPoint(sphere.m_mesh.m_vertices, temp)\nsphere.m_matrix2 = transVector(sphere.m_mesh.m_normals, temp)\n\nglLoadIdentity()\nglTranslate(cube.m_position.x, cube.m_position.y, cube.m_position.z)\nglRotate(cube.m_rotate.t, cube.m_rotate.x, cube.m_rotate.y, cube.m_rotate.z)\ntemp = glGetDoublev(GL_MODELVIEW_MATRIX)\ncube.m_matrix1 = transPoint(cube.m_mesh.m_vertices, temp)\ncube.m_matrix2 = transVector(cube.m_mesh.m_normals, temp)\n\napp.exec_()\nsys.exit()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"123272308","text":"from struct_methods import *\nimport io\nimport numpy\nfrom scipy.signal import butter, lfilter\nimport math\nimport pickle\nimport random\n\n\nclass offlineParamOpt(object):\n def __init__(self, channel, num, groups, N=3):\n self.Fs = 1000\n self.filt_n = 4\n self.N = N \n self.channelRaw = channel\n self.channels = [i-1 for i in self.channelRaw]\n self.DataLength = len(self.channels)\n self.num = num\n self.samples_per_packet = 43\n self.allChannels = 16\n self.groups = groups\n self.NtoLastN = [i for i in range(N)]\n self.NtoLastN.extend([i for i in range(self.DataLength-N, self.DataLength)])\n self.classOne = numpy.zeros(shape=(16, 43*self.num, self.groups))\n self.classTwo = numpy.zeros(shape=(16, 43*self.num, self.groups))\n self.frequency = [[8,30], [8,13], [13,20], [20,30]]\n self.timepoint = [1000, 4000]\n\n def readOffData(self, path):\n self.fid = open(path, \"rb\")\n # self.fid.seek(0)\n currentGroupOne = 0\n currentGroupTwo = 0\n packets = 0\n while currentGroupOne != self.groups or currentGroupTwo != self.groups:\n trigger = read_uint16le(self.fid)\n packets += 1\n if trigger == 1:\n currentGroupOne += 1\n self.fid.seek(12, 1)\n all_samples = []\n for i in range(self.samples_per_packet): \n samples = []\n for j in range(self.allChannels):\n sample = read_uint16le(self.fid)\n samples.append(sample) \n all_samples.append(samples) \n first_Packet = numpy.array(all_samples)\n firstPacketMatrics = first_Packet.reshape((self.samples_per_packet, self.allChannels))\n self.classOne[:, 0:43, currentGroupOne-1] = firstPacketMatrics.T\n for p in range(self.num-1): \n self.fid.seek(14, 1)\n all_samples = []\n for i in range(self.samples_per_packet): \n samples = []\n for j in range(self.allChannels):\n sample = read_uint16le(self.fid)\n samples.append(sample) \n all_samples.append(samples)\n next_Packet = numpy.array(all_samples)\n nextPacketMatrics = next_Packet.reshape((self.samples_per_packet, self.allChannels))\n self.classOne[:, 43*p+43:43*p+86, currentGroupOne-1] = nextPacketMatrics.T\n elif trigger == 2:\n currentGroupTwo += 1\n self.fid.seek(12, 1)\n all_samples = []\n for i in range(self.samples_per_packet): \n samples = []\n for j in range(self.allChannels):\n sample = read_uint16le(self.fid)\n samples.append(sample) \n all_samples.append(samples) \n first_Packet = numpy.array(all_samples)\n firstPacketMatrics = first_Packet.reshape((self.samples_per_packet, self.allChannels))\n self.classTwo[:, 0:43, currentGroupTwo-1] = firstPacketMatrics.T\n for p in range(self.num-1): \n self.fid.seek(14, 1)\n all_samples = []\n for i in range(self.samples_per_packet): \n samples = []\n for j in range(self.allChannels):\n sample = read_uint16le(self.fid)\n samples.append(sample) \n all_samples.append(samples)\n next_Packet = numpy.array(all_samples)\n nextPacketMatrics = next_Packet.reshape((self.samples_per_packet, self.allChannels))\n self.classTwo[:, 43*p+43:43*p+86, currentGroupTwo-1] = nextPacketMatrics.T\n else:\n self.fid.seek(1388, 1)\n self.fid.close()\n\n def offlineClass(self, path):\n self.readOffData(path)\n trainGroups = int(0.8*self.groups)\n testGroups = self.groups - trainGroups\n acc = numpy.zeros((4,100)) # need to change\n for fre in range(4):\n Wn = [self.frequency[fre][0]/(self.Fs/2), self.frequency[fre][1]/(self.Fs/2)]\n filter_b, filter_a = butter(self.filt_n, Wn, btype='band')\n Cov1 = numpy.zeros(shape=(self.DataLength, self.DataLength, self.groups)) \n Cov2 = numpy.zeros(shape=(self.DataLength, self.DataLength, self.groups))\n for i in range(self.groups):\n dataTofilter = self.classOne[self.channels, :, i]\n dataFiltered = lfilter(filter_b, filter_a, dataTofilter, axis=1)\n Dr = dataFiltered[:, self.timepoint[0]:self.timepoint[1]]\n Cov1[:, :, i] = numpy.dot(Dr, Dr.T)\n dataTofilter = self.classTwo[self.channels, :, i]\n dataFiltered = lfilter(filter_b, filter_a, dataTofilter, axis=1)\n Dr = dataFiltered[:, self.timepoint[0]:self.timepoint[1]]\n Cov2[:, :, i] = numpy.dot(Dr, Dr.T)\n for cross in range(100):\n randGroup =[i for i in range(self.groups)]\n random.shuffle(randGroup)\n R1 = numpy.zeros(shape=(self.DataLength, self.DataLength))\n R2 = numpy.zeros(shape=(self.DataLength, self.DataLength))\n for t in range(trainGroups):\n R1 += Cov1[:, :, randGroup[t]]\n R2 += Cov2[:, :, randGroup[t]]\n R1 = R1/numpy.trace(R1)\n R2 = R2/numpy.trace(R2)\n R3 = R1 + R2\n sigma, U0 = numpy.linalg.eig(R3)\n P = numpy.dot(numpy.diag(sigma**(-0.5)), U0.T)\n YL = numpy.dot(numpy.dot(P,R1),P.T)\n sigmaL, UL = numpy.linalg.eig(YL)\n Isorted = numpy.argsort(-sigmaL)\n F = numpy.dot(P.T, UL[:, Isorted[self.NtoLastN]])\n f = numpy.zeros(shape=(2*self.N, 1))\n f1 = numpy.zeros(shape=(2*self.N, self.groups))\n f2 = numpy.zeros(shape=(2*self.N, self.groups))\n for i in range(trainGroups):\n for j in range(2*self.N):\n f[j, 0] = numpy.log(numpy.dot(numpy.dot(F[:,j].reshape(1, self.DataLength),Cov1[:,:,randGroup[i]]),F[:,j]))\n f1[:, i] = f[:, 0]\n for j in range(2*self.N):\n f[j, 0] = numpy.log(numpy.dot(numpy.dot(F[:,j].reshape(1, self.DataLength),Cov2[:,:,randGroup[i]]),F[:,j]))\n f2[:, i] = f[:, 0]\n F1 = f1.T\n F2 = f2.T\n M1 = numpy.mean(F1, 0)\n M1.shape = (2*self.N, 1)\n M2 = numpy.mean(F2, 0)\n M2.shape = (2*self.N, 1)\n count1 = numpy.size(f1, 1)-1\n count2 = numpy.size(f2, 1)-1 \n w = numpy.dot(numpy.linalg.inv((count1*numpy.cov(F1.T)+count2*numpy.cov(F2.T))/(count1+count2)),(M2-M1)).reshape(1,2*self.N)\n b = -numpy.dot(w,M1+M2)/2\n TypeOneSign = numpy.dot(w, M1)+b\n right = 0\n for i in range(trainGroups, self.groups):\n for j in range(2*self.N): \n f[j, 0] = numpy.log(numpy.dot(numpy.dot(F[:,j].reshape(1, self.DataLength),Cov1[:,:,randGroup[i]]),F[:,j]))\n y = numpy.dot(w, f)+b\n if y*TypeOneSign >= 0:\n right +=1 \n for j in range(2*self.N): \n f[j, 0] = numpy.log(numpy.dot(numpy.dot(F[:,j].reshape(1, self.DataLength),Cov2[:,:,randGroup[i]]),F[:,j]))\n y = numpy.dot(w, f)+b\n if y*TypeOneSign <= 0:\n right +=1\n acc[fre, cross] = right/(2*testGroups)\n meanAcc = numpy.mean(acc, axis=1)\n meanaccList = meanAcc.tolist()\n frequencyIndex = meanaccList.index(max(meanaccList))\n return meanaccList, frequencyIndex","sub_path":"offlineParamOptimization.py","file_name":"offlineParamOptimization.py","file_ext":"py","file_size_in_byte":8442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"222305836","text":"def main():\n N = int(input('Digite um número inteiro: '))\n limite_inferior = int(input('Informe um valor para o limite inferior: '))\n limite_superior = int(input('Informe um valor para o limite superior: '))\n\n multiplo(N, limite_inferior, limite_superior)\n\ndef multiplo(numero, inferior, supeior):\n print(f'Os números no intervalo de {inferior} a {supeior} que são múltiplos de {numero} são: ',end=' ')\n while inferior <= supeior:\n if inferior % numero == 0:\n print(inferior, end=' ')\n inferior += 1\nmain()","sub_path":"Lista_Prof_Fabio/Algoritmos_Exercicio-03-REPETICAO-WHILE/fb_ex3_q8-while.py","file_name":"fb_ex3_q8-while.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"484203743","text":"# Copyright (c) 2018 gevent. See LICENSE for details.\nfrom __future__ import print_function, absolute_import, division\n\nimport os\nimport sys\nimport traceback\n\nfrom weakref import ref as wref\n\nfrom greenlet import settrace\nfrom greenlet import getcurrent\n\nfrom gevent import config as GEVENT_CONFIG\nfrom gevent.monkey import get_original\nfrom gevent.util import format_run_info\nfrom gevent.events import notify\nfrom gevent.events import EventLoopBlocked\nfrom gevent.events import MemoryUsageThresholdExceeded\nfrom gevent.events import MemoryUsageUnderThreshold\nfrom gevent.events import IPeriodicMonitorThread\nfrom gevent.events import implementer\n\nfrom gevent._compat import thread_mod_name\nfrom gevent._compat import perf_counter\nfrom gevent._util import gmctime\n\n\n__all__ = [\n 'PeriodicMonitoringThread',\n]\n\nget_thread_ident = get_original(thread_mod_name, 'get_ident')\nstart_new_thread = get_original(thread_mod_name, 'start_new_thread')\nthread_sleep = get_original('time', 'sleep')\n\n\n\nclass MonitorWarning(RuntimeWarning):\n \"\"\"The type of warnings we emit.\"\"\"\n\n\nclass GreenletTracer(object):\n\n # A counter, incremented by the greenlet trace function\n # we install on every greenlet switch. This is reset when the\n # periodic monitoring thread runs.\n greenlet_switch_counter = 0\n\n # The greenlet last switched to.\n active_greenlet = None\n\n # The trace function that was previously installed,\n # if any.\n previous_trace_function = None\n\n def __init__(self):\n prev_trace = settrace(self)\n self.previous_trace_function = prev_trace\n\n def kill(self): # pylint:disable=method-hidden\n # Must be called in the monitored thread.\n settrace(self.previous_trace_function)\n self.previous_trace_function = None\n # Become a no-op\n self.kill = lambda: None\n\n def __call__(self, event, args):\n # This function runs in the thread we are monitoring.\n self.greenlet_switch_counter += 1\n if event in ('switch', 'throw'):\n # args is (origin, target). This is the only defined\n # case\n self.active_greenlet = args[1]\n else:\n self.active_greenlet = None\n if self.previous_trace_function is not None:\n self.previous_trace_function(event, args)\n\n def did_block_hub(self, hub):\n # Check to see if we have blocked since the last call to this\n # method. Returns a true value if we blocked (not in the hub),\n # a false value if everything is fine.\n\n # This may be called in the same thread being traced or a\n # different thread; if a different thread, there is a race\n # condition with this being incremented in the thread we're\n # monitoring, but probably not often enough to lead to\n # annoying false positives.\n\n active_greenlet = self.active_greenlet\n did_switch = self.greenlet_switch_counter != 0\n self.greenlet_switch_counter = 0\n\n if did_switch or active_greenlet is None or active_greenlet is hub:\n # Either we switched, or nothing is running (we got a\n # trace event we don't know about or were requested to\n # ignore), or we spent the whole time in the hub, blocked\n # for IO. Nothing to report.\n return False\n return True, active_greenlet\n\n def ignore_current_greenlet_blocking(self):\n # Don't pay attention to the current greenlet.\n self.active_greenlet = None\n\n def monitor_current_greenlet_blocking(self):\n self.active_greenlet = getcurrent()\n\n def did_block_hub_report(self, hub, active_greenlet, format_kwargs):\n report = ['=' * 80,\n '\\n%s : Greenlet %s appears to be blocked' %\n (gmctime(), active_greenlet)]\n report.append(\" Reported by %s\" % (self,))\n try:\n frame = sys._current_frames()[hub.thread_ident]\n except KeyError:\n # The thread holding the hub has died. Perhaps we shouldn't\n # even report this?\n stack = [\"Unknown: No thread found for hub %r\\n\" % (hub,)]\n else:\n stack = traceback.format_stack(frame)\n report.append('Blocked Stack (for thread id %s):' % (hex(hub.thread_ident),))\n report.append(''.join(stack))\n report.append(\"Info:\")\n report.extend(format_run_info(**format_kwargs))\n\n return report\n\nclass _HubTracer(GreenletTracer):\n def __init__(self, hub, max_blocking_time):\n GreenletTracer.__init__(self)\n self.max_blocking_time = max_blocking_time\n self.hub = hub\n\n def kill(self): # pylint:disable=method-hidden\n self.hub = None\n GreenletTracer.kill(self)\n\n\nclass HubSwitchTracer(_HubTracer):\n # A greenlet tracer that records the last time we switched *into* the hub.\n\n last_entered_hub = 0\n\n def __call__(self, event, args):\n GreenletTracer.__call__(self, event, args)\n if self.active_greenlet is self.hub:\n self.last_entered_hub = perf_counter()\n\n def did_block_hub(self, hub):\n if perf_counter() - self.last_entered_hub > self.max_blocking_time:\n return True, self.active_greenlet\n\n\nclass MaxSwitchTracer(_HubTracer):\n # A greenlet tracer that records the maximum time between switches,\n # not including time spent in the hub.\n\n max_blocking = 0\n\n def __init__(self, hub, max_blocking_time):\n _HubTracer.__init__(self, hub, max_blocking_time)\n self.last_switch = perf_counter()\n\n def __call__(self, event, args):\n old_active = self.active_greenlet\n GreenletTracer.__call__(self, event, args)\n if old_active is not self.hub and old_active is not None:\n # If we're switching out of the hub, the blocking\n # time doesn't count.\n switched_at = perf_counter()\n self.max_blocking = max(self.max_blocking,\n switched_at - self.last_switch)\n\n def did_block_hub(self, hub):\n if self.max_blocking == 0:\n # We never switched. Check the time now\n self.max_blocking = perf_counter() - self.last_switch\n\n if self.max_blocking > self.max_blocking_time:\n return True, self.active_greenlet\n\n\nclass _MonitorEntry(object):\n\n __slots__ = ('function', 'period', 'last_run_time')\n\n def __init__(self, function, period):\n self.function = function\n self.period = period\n self.last_run_time = 0\n\n def __eq__(self, other):\n return self.function == other.function and self.period == other.period\n\n def __repr__(self):\n return repr((self.function, self.period, self.last_run_time))\n\n\n@implementer(IPeriodicMonitorThread)\nclass PeriodicMonitoringThread(object):\n # This doesn't extend threading.Thread because that gets monkey-patched.\n # We use the low-level 'start_new_thread' primitive instead.\n\n # The amount of seconds we will sleep when we think we have nothing\n # to do.\n inactive_sleep_time = 2.0\n\n # The absolute minimum we will sleep, regardless of\n # what particular monitoring functions want to say.\n min_sleep_time = 0.005\n\n # The minimum period in seconds at which we will check memory usage.\n # Getting memory usage is fairly expensive.\n min_memory_monitor_period = 2\n\n # A list of _MonitorEntry objects: [(function(hub), period, last_run_time))]\n # The first entry is always our entry for self.monitor_blocking\n _monitoring_functions = None\n\n # The calculated min sleep time for the monitoring functions list.\n _calculated_sleep_time = None\n\n # A boolean value that also happens to capture the\n # memory usage at the time we exceeded the threshold. Reset\n # to 0 when we go back below.\n _memory_exceeded = 0\n\n # The instance of GreenletTracer we're using\n _greenlet_tracer = None\n\n def __init__(self, hub):\n self._hub_wref = wref(hub, self._on_hub_gc)\n self.should_run = True\n\n # Must be installed in the thread that the hub is running in;\n # the trace function is threadlocal\n assert get_thread_ident() == hub.thread_ident\n self._greenlet_tracer = GreenletTracer()\n\n self._monitoring_functions = [_MonitorEntry(self.monitor_blocking,\n GEVENT_CONFIG.max_blocking_time)]\n self._calculated_sleep_time = GEVENT_CONFIG.max_blocking_time\n # Create the actual monitoring thread. This is effectively a \"daemon\"\n # thread.\n self.monitor_thread_ident = start_new_thread(self, ())\n\n # We must track the PID to know if your thread has died after a fork\n self.pid = os.getpid()\n\n def _on_fork(self):\n # Pseudo-standard method that resolver_ares and threadpool\n # also have, called by hub.reinit()\n pid = os.getpid()\n if pid != self.pid:\n self.pid = pid\n self.monitor_thread_ident = start_new_thread(self, ())\n\n @property\n def hub(self):\n return self._hub_wref()\n\n\n def monitoring_functions(self):\n # Return a list of _MonitorEntry objects\n\n # Update max_blocking_time each time.\n mbt = GEVENT_CONFIG.max_blocking_time # XXX: Events so we know when this changes.\n if mbt != self._monitoring_functions[0].period:\n self._monitoring_functions[0].period = mbt\n self._calculated_sleep_time = min(x.period for x in self._monitoring_functions)\n return self._monitoring_functions\n\n def add_monitoring_function(self, function, period):\n if not callable(function):\n raise ValueError(\"function must be callable\")\n\n if period is None:\n # Remove.\n self._monitoring_functions = [\n x for x in self._monitoring_functions\n if x.function != function\n ]\n elif period <= 0:\n raise ValueError(\"Period must be positive.\")\n else:\n # Add or update period\n entry = _MonitorEntry(function, period)\n self._monitoring_functions = [\n x if x.function != function else entry\n for x in self._monitoring_functions\n ]\n if entry not in self._monitoring_functions:\n self._monitoring_functions.append(entry)\n self._calculated_sleep_time = min(x.period for x in self._monitoring_functions)\n\n def calculate_sleep_time(self):\n min_sleep = self._calculated_sleep_time\n if min_sleep <= 0:\n # Everyone wants to be disabled. Sleep for a longer period of\n # time than usual so we don't spin unnecessarily. We might be\n # enabled again in the future.\n return self.inactive_sleep_time\n return max((min_sleep, self.min_sleep_time))\n\n def kill(self):\n if not self.should_run:\n # Prevent overwriting trace functions.\n return\n # Stop this monitoring thread from running.\n self.should_run = False\n # Uninstall our tracing hook\n self._greenlet_tracer.kill()\n\n def _on_hub_gc(self, _):\n self.kill()\n\n def __call__(self):\n # The function that runs in the monitoring thread.\n # We cannot use threading.current_thread because it would\n # create an immortal DummyThread object.\n getcurrent().gevent_monitoring_thread = wref(self)\n\n try:\n while self.should_run:\n functions = self.monitoring_functions()\n assert functions\n sleep_time = self.calculate_sleep_time()\n\n thread_sleep(sleep_time)\n\n # Make sure the hub is still around, and still active,\n # and keep it around while we are here.\n hub = self.hub\n if not hub:\n self.kill()\n\n if self.should_run:\n this_run = perf_counter()\n for entry in functions:\n f = entry.function\n period = entry.period\n last_run = entry.last_run_time\n if period and last_run + period <= this_run:\n entry.last_run_time = this_run\n f(hub)\n del hub # break our reference to hub while we sleep\n\n except SystemExit:\n pass\n except: # pylint:disable=bare-except\n # We're a daemon thread, so swallow any exceptions that get here\n # during interpreter shutdown.\n if not sys or not sys.stderr: # pragma: no cover\n # Interpreter is shutting down\n pass\n else:\n hub = self.hub\n if hub is not None:\n # XXX: This tends to do bad things like end the process, because we\n # try to switch *threads*, which can't happen. Need something better.\n hub.handle_error(self, *sys.exc_info())\n\n def monitor_blocking(self, hub):\n # Called periodically to see if the trace function has\n # fired to switch greenlets. If not, we will print\n # the greenlet tree.\n\n # For tests, we return a true value when we think we found something\n # blocking\n\n did_block = self._greenlet_tracer.did_block_hub(hub)\n if not did_block:\n return\n\n active_greenlet = did_block[1]\n report = self._greenlet_tracer.did_block_hub_report(\n hub, active_greenlet,\n dict(greenlet_stacks=False, current_thread_ident=self.monitor_thread_ident))\n\n stream = hub.exception_stream\n for line in report:\n # Printing line by line may interleave with other things,\n # but it should also prevent a \"reentrant call to print\"\n # when the report is large.\n print(line, file=stream)\n\n notify(EventLoopBlocked(active_greenlet, GEVENT_CONFIG.max_blocking_time, report))\n return (active_greenlet, report)\n\n def ignore_current_greenlet_blocking(self):\n self._greenlet_tracer.ignore_current_greenlet_blocking()\n\n def monitor_current_greenlet_blocking(self):\n self._greenlet_tracer.monitor_current_greenlet_blocking()\n\n def _get_process(self): # pylint:disable=method-hidden\n try:\n # The standard library 'resource' module doesn't provide\n # a standard way to get the RSS measure, only the maximum.\n # You might be tempted to try to compute something by adding\n # together text and data sizes, but on many systems those come back\n # zero. So our only option is psutil.\n from psutil import Process, AccessDenied\n # Make sure it works (why would we be denied access to our own process?)\n try:\n proc = Process()\n proc.memory_full_info()\n except AccessDenied: # pragma: no cover\n proc = None\n except ImportError:\n proc = None\n\n self._get_process = lambda: proc\n return proc\n\n def can_monitor_memory_usage(self):\n return self._get_process() is not None\n\n def install_monitor_memory_usage(self):\n # Start monitoring memory usage, if possible.\n # If not possible, emit a warning.\n if not self.can_monitor_memory_usage():\n import warnings\n warnings.warn(\"Unable to monitor memory usage. Install psutil.\",\n MonitorWarning)\n return\n\n self.add_monitoring_function(self.monitor_memory_usage,\n max(GEVENT_CONFIG.memory_monitor_period,\n self.min_memory_monitor_period))\n\n def monitor_memory_usage(self, _hub):\n max_allowed = GEVENT_CONFIG.max_memory_usage\n if not max_allowed:\n # They disabled it.\n return -1 # value for tests\n\n rusage = self._get_process().memory_full_info()\n # uss only documented available on Windows, Linux, and OS X.\n # If not available, fall back to rss as an aproximation.\n mem_usage = getattr(rusage, 'uss', 0) or rusage.rss\n\n event = None # Return value for tests\n\n if mem_usage > max_allowed:\n if mem_usage > self._memory_exceeded:\n # We're still growing\n event = MemoryUsageThresholdExceeded(\n mem_usage, max_allowed, rusage)\n notify(event)\n self._memory_exceeded = mem_usage\n else:\n # we're below. Were we above it last time?\n if self._memory_exceeded:\n event = MemoryUsageUnderThreshold(\n mem_usage, max_allowed, rusage, self._memory_exceeded)\n notify(event)\n self._memory_exceeded = 0\n\n return event\n\n def __repr__(self):\n return '<%s at %s in thread %s greenlet %r for %r>' % (\n self.__class__.__name__,\n hex(id(self)),\n hex(self.monitor_thread_ident),\n getcurrent(),\n self._hub_wref())\n","sub_path":"src/gevent/_monitor.py","file_name":"_monitor.py","file_ext":"py","file_size_in_byte":17195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"620387523","text":"import bs4, requests\r\n\r\nres = requests.get(\"http://automatetheboringstuff.com/\")\r\nres.raise_for_status()\r\n\r\nsoup = bs4.BeautifulSoup(res.text, \"html.parser\")\r\n# right click element > inspect\r\n# right click highlighted code > copy > copy selector\r\nelems = soup.select(\"body > div.main > div:nth-child(1) > h2:nth-child(19)\")\r\nprint(elems[0].text)\r\n","sub_path":"0_reference/AutomateTheBoringStuff/example_web_html.py","file_name":"example_web_html.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"192426306","text":"# 1812 / calculate how many tiles will be needed\nfor T in range(int(input())):\n N, M = map(int, input().split()) # number of needed tiles, len of basic tile\n S = sorted(list(map(int, input().split())), reverse=True) # power number list\n\n # set basic number of needed tiles and remain tiles list\n cnt = 1\n areas = [(M, M)]\n for s in S:\n ln = 2 ** s # calculate len of cutting tile\n for i in range(len(areas)):\n w, h = areas[i] # compare width and height of cutted tile\n # if len of original tile is bigger, cut it\n if w >= ln and h >= ln:\n areas.append((w - ln, h - ln))\n areas.append((w - ln, ln))\n areas.append((ln, h - ln))\n areas = areas[:i] + areas[i + 1:]\n break\n # else plus 1 to counter and add cutted tile\n elif i == len(areas) - 1:\n cnt += 1\n areas.append((M - ln, M - ln))\n areas.append((M - ln, ln))\n areas.append((ln, M - ln))\n\n print(f'#{T + 1} {cnt}')\n ","sub_path":"D5/1812.py","file_name":"1812.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"125918260","text":"# -*- coding: utf-8 -*-\n\n# Copyright (C) 2017 Luis López \n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU 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, MA 02110-1301,\n# USA.\n\n\nimport re\nimport sys\nfrom urllib import parse\n\n\nfrom appkit import utils\nfrom appkit.db import sqlalchemyutils as sautils\nfrom sqlalchemy import (\n Column,\n Integer,\n String,\n ForeignKey,\n and_,\n # event,\n func,\n orm,\n schema\n)\nfrom sqlalchemy.ext.hybrid import hybrid_property\n\n\nfrom arroyo import bittorrentlib\n\n\nsautils.Base.metadata.naming_convention = {\n \"ix\": 'ix_%(column_0_label)s',\n \"uq\": \"uq_%(table_name)s_%(column_0_name)s\",\n \"ck\": \"ck_%(table_name)s_%(constraint_name)s\",\n \"fk\": \"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s\",\n \"pk\": \"pk_%(table_name)s\"\n}\n\n\nclass Variable(sautils.KeyValueItem, sautils.Base):\n __tablename__ = 'variable'\n __table_args__ = schema.UniqueConstraint('key'),\n\n\nclass Source(sautils.Base):\n __tablename__ = 'source'\n\n # Required\n id = Column(Integer, autoincrement=True, primary_key=True)\n name = Column(String, nullable=False)\n uri = Column(String, nullable=False, unique=True)\n provider = Column(String, nullable=False)\n\n # EntitySupport\n episode_id = Column(Integer,\n ForeignKey('episode.id', ondelete=\"SET NULL\"),\n nullable=True)\n episode = orm.relationship('Episode',\n uselist=False,\n backref=orm.backref(\"sources\",\n cascade_backrefs=False,\n lazy='select'))\n\n movie_id = Column(Integer,\n ForeignKey('movie.id', ondelete=\"SET NULL\"),\n nullable=True)\n movie = orm.relationship('Movie',\n uselist=False,\n backref=orm.backref(\"sources\",\n cascade_backrefs=False,\n lazy='select'))\n\n def __init__(self, name, uri, provider,\n timestamp=None,\n size=None,\n seeds=None,\n leechers=None,\n type=None,\n language=None,\n meta=None,\n tags=None):\n\n # Non database attributes\n self.meta = meta or []\n self.language = language\n self.leechers = leechers\n self.seeds = seeds\n self.size = size\n self.timestamp = timestamp or utils.now_timestamp()\n self.tags = tags or []\n self.type = type\n\n super().__init__(name=name, uri=uri, provider=provider)\n\n def __eq__(self, other):\n return _eq_from_attrs(self, other, ('uri',))\n\n def __lt__(self, other):\n return _lt_from_attrs(self, other, ('name',))\n\n def __repr__(self):\n return \"\".format(\n id=self.id or '??',\n oid=id(self),\n fmt=self.format())\n\n def __str__(self):\n return self.format()\n\n def __hash__(self):\n return hash(self.uri)\n\n @orm.validates('name', 'provider', 'urn', 'uri', 'language', 'type')\n def validate(self, key, value):\n \"\"\"\n Wrapper around static method normalize\n \"\"\"\n return self.normalize(key, value)\n\n @staticmethod\n def normalize(key, value):\n def _normalize():\n nonlocal key\n nonlocal value\n\n # Those keys must be a non empty strings\n if key in ['name', 'provider', 'urn', 'uri']:\n if value == '':\n raise ValueError()\n\n return str(value)\n\n # Those keys must be an integer (not None)\n elif key in ['created', 'last_seen']:\n return int(value)\n\n # Those keys must be an integer or None\n elif key in ['size', 'seeds', 'leechers']:\n if value is None:\n return None\n\n return int(key)\n\n # language must be in form of xxx-xx or None\n elif key == 'language':\n if value is None:\n return None\n\n value = str(value)\n\n if not re.match(r'^...(\\-..)?$', value):\n raise ValueError()\n\n return value\n\n # type is limited to some strings or None\n elif key == 'type':\n if value is None:\n return None\n\n value = str(value)\n\n if value in (\n 'application',\n 'book',\n 'episode',\n 'game',\n 'movie',\n 'music',\n 'other',\n 'xxx'):\n return value\n\n raise ValueError()\n\n else:\n raise KeyError()\n\n # Wrap the whole process for easy exception handling\n try:\n return _normalize()\n\n except TypeError as e:\n msg = 'invalid type for {key}: {type}'\n msg = msg.format(key=key, type=type(value))\n raise TypeError(msg) from e\n\n except ValueError as e:\n msg = 'invalid value for {key}: {value}'\n msg = msg.format(key=key, value=repr(value))\n raise ValueError(msg) from e\n\n @hybrid_property\n def entity(self):\n return _entity_getter(self)\n\n @entity.setter\n def entity(self, entity):\n _entity_setter(self, entity)\n\n @property\n def age(self):\n return utils.now_timestamp() - self.timestamp\n\n @property\n def needs_postprocessing(self):\n return self.urn is None and self.uri is not None\n\n @property\n def ratio(self):\n seeds = self.seeds if self.seeds is not None else 0\n leechers = self.leechers if self.leechers is not None else 0\n\n if not self.seeds and not self.leechers:\n return None\n\n if seeds and leechers == 0:\n return float(sys.maxsize)\n\n if seeds == 0 and leechers:\n return 0.0\n\n return seeds / leechers\n\n @property\n def selected(self):\n return (\n self.entity and\n self.entity.selection and\n self.entity.selection.source == self)\n\n @property\n def urn(self):\n if self.uri.startswith('http'):\n return None\n\n qs = parse.urlparse(self.uri).query\n try:\n urn = parse.parse_qs(qs)['xt'][-1]\n except KeyError:\n return None\n urn = bittorrentlib.normalize_urn(urn)\n return urn.lstrip('urn:')\n\n def asdict(self):\n return _asdict_from_attrs(\n self, (\n 'age',\n 'entity',\n 'episode',\n 'episode_id',\n 'id',\n 'language',\n 'leechers',\n 'movie',\n 'movie_id',\n 'name',\n 'provider',\n 'ratio',\n 'seeds',\n 'size',\n 'tags',\n 'timestamp',\n 'type',\n 'uri',\n 'urn'))\n\n def format(self, fmt='{name}', extra_data={}):\n data = self.asdict()\n data['seeds'] = data.get('seeds', '-')\n data['leechers'] = data.get('leechers', '-')\n data['language'] = data.get('language', 'unknow')\n data.update(extra_data)\n\n return fmt.format(**data)\n\n\n# @event.listens_for(Source.tags, 'dispose_collection')\n# @event.listens_for(Source.tags, 'init_collection')\n# @event.listens_for(Source.tags, 'remove')\n# def _source_tags_modifier_cb(target, *args):\n# target.tags_map = {tag.key: tag.value for tag in target.tags}\n\n\n# class SourceTag(sautils.KeyValueItem, sautils.Base):\n# __tablename__ = 'sourcetag'\n# __table_args__ = (\n# schema.UniqueConstraint('source_id', 'key'),\n# )\n\n# source_id = Column(Integer, ForeignKey('source.id', ondelete=\"cascade\"))\n# source = orm.relationship(\"Source\", back_populates=\"tags\", uselist=False)\n\n\n# class Selection(sautils.Base):\n# __tablename__ = 'selection'\n# __mapper_args__ = {\n# 'polymorphic_on': 'type'\n# }\n\n# id = Column(Integer, primary_key=True)\n# type = Column(String(50))\n# source_id = Column(Integer,\n# ForeignKey('source.id', ondelete=\"cascade\"),\n# nullable=False)\n# source = orm.relationship('Source')\n\n# @hybrid_property\n# def entity(self):\n# return _entity_getter(self)\n\n# @entity.setter\n# def entity(self, entity):\n# _entity_setter(self, entity)\n\n\n# class EpisodeSelection(Selection):\n# __mapper_args__ = {\n# 'polymorphic_identity': 'episode'\n# }\n\n# episode_id = Column(Integer,\n# ForeignKey('episode.id', ondelete=\"CASCADE\"),\n# nullable=True)\n# episode = orm.relationship(\"Episode\",\n# backref=orm.backref(\"selection\",\n# cascade=\"all, delete\",\n# uselist=False))\n\n# def __repr__(self):\n# fmt = ' source:{source}'\n# return fmt.format(\n# id=self.id,\n# episode=repr(self.episode),\n# source=repr(self.source))\n\n\n# class MovieSelection(Selection):\n# __mapper_args__ = {\n# 'polymorphic_identity': 'movie'\n# }\n\n# movie_id = Column(Integer,\n# ForeignKey('movie.id', ondelete=\"CASCADE\"),\n# nullable=True)\n# movie = orm.relationship(\"Movie\",\n# backref=orm.backref(\"selection\",\n# cascade=\"all, delete\",\n# uselist=False))\n\n# def __repr__(self):\n# fmt = ' source:{source}'\n# return fmt.format(\n# id=self.id,\n# movie=repr(self.movie),\n# source=repr(self.source))\n\n\nclass Episode(sautils.Base):\n __tablename__ = 'episode'\n __table_args__ = (\n schema.UniqueConstraint('series', 'modifier', 'season', 'number'),\n )\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n series = Column(String, nullable=False)\n modifier = Column(String, nullable=False, default='')\n season = Column(Integer, nullable=False)\n number = Column(Integer, nullable=False)\n\n # SELECTION_MODEL = EpisodeSelection\n\n def __init__(self, *args, modifier='', **kwargs):\n attrs = (\n 'series',\n 'season',\n 'number'\n )\n _init_check_required(kwargs, attrs)\n super().__init__(*args, modifier=modifier, **kwargs)\n\n def __eq__(self, other):\n attrs = (\n 'series',\n 'modifier',\n 'season',\n 'number'\n )\n return _eq_from_attrs(self, other, attrs)\n\n def __lt__(self, other):\n attrs = (\n 'series',\n 'modifier'\n 'season',\n 'number'\n )\n return _lt_from_attrs(self, other, attrs)\n\n def __repr__(self):\n return \"\".format(\n id=self.id or '??',\n oid=id(self),\n fmt=self.format())\n\n def __str__(self):\n return self.__unicode__()\n\n def __unicode__(self):\n return self.format()\n\n @orm.validates(\n 'series',\n 'modifier',\n 'season',\n 'number'\n )\n def validate(self, key, value):\n return self.normalize(key, value)\n\n @classmethod\n def normalize(cls, key, value):\n if key == 'series':\n value = value.lower()\n if not value:\n raise ValueError(value)\n\n elif key == 'modifier':\n value = str(value) if value is not None else ''\n\n elif key in ['season', 'number']:\n value = int(value)\n if value < 0:\n raise ValueError(value)\n\n else:\n raise NotImplementedError(key)\n\n return value\n\n def asdict(self):\n attrs = (\n 'series',\n 'modifier',\n 'season',\n 'number',\n )\n return _asdict_from_attrs(self, attrs)\n\n def format(self, fmt='{series_with_mod} s{season:02d} e{number:02d}',\n extra_data={}):\n d = self.asdict()\n\n if self.modifier:\n series_with_mod = \"{series} ({modifier})\"\n else:\n series_with_mod = \"{series}\"\n\n d['series_with_mod'] = series_with_mod.format(**d)\n d.update(**extra_data)\n\n try:\n return fmt.format(**d)\n except TypeError:\n pass\n\n\nclass Movie(sautils.Base):\n __tablename__ = 'movie'\n __table_args__ = (\n schema.UniqueConstraint('title', 'modifier'),\n )\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n title = Column(String, nullable=False)\n modifier = Column(String, nullable=False, default='')\n\n # SELECTION_MODEL = MovieSelection\n\n def __init__(self, *args, modifier='', **kwargs):\n attrs = (\n 'title',\n )\n _init_check_required(kwargs, attrs)\n super().__init__(*args, modifier=modifier, **kwargs)\n\n def __eq__(self, other):\n attrs = (\n 'title',\n 'modifier'\n )\n return _eq_from_attrs(self, other, attrs)\n\n def __lt__(self, other):\n attrs = (\n 'title',\n 'modifier'\n )\n return _lt_from_attrs(self, other, attrs)\n\n def __repr__(self):\n return \"\".format(\n id=self.id or '??',\n oid=id(self),\n fmt=self.format())\n\n def __str__(self):\n return self.__unicode__()\n\n def __unicode__(self):\n return self.format()\n\n @orm.validates(\n 'title',\n 'modifier'\n )\n def validate(self, key, value):\n return self.normalize(key, value)\n\n @classmethod\n def normalize(cls, key, value):\n if key == 'title':\n value = value.lower()\n if not value:\n raise ValueError(value)\n\n elif key == 'modifier':\n value = str(value) if value else ''\n\n else:\n raise NotImplementedError(key)\n\n return value\n\n def asdict(self):\n attrs = (\n 'title',\n 'modifier'\n )\n return _asdict_from_attrs(self, attrs)\n\n def format(self, fmt='{title_with_mod}', extra_data={}):\n d = self.asdict()\n\n if self.modifier:\n title_with_mod = \"{title} ({modifier})\"\n else:\n title_with_mod = \"{title}\"\n\n d['title_with_mod'] = title_with_mod.format(**d)\n d.update(**extra_data)\n\n return fmt.format(**d)\n\n\nclass Download(sautils.Base):\n __tablename__ = 'download'\n __table_args__ = (\n schema.UniqueConstraint('foreign_id'),\n )\n\n source_id = Column(Integer,\n ForeignKey(\"source.id\", ondelete=\"CASCADE\"),\n primary_key=True, nullable=False)\n source = orm.relationship(\"Source\",\n backref=orm.backref(\"download\",\n cascade=\"all, delete\",\n uselist=False))\n foreign_id = Column(String, nullable=False)\n state = Column(Integer, nullable=False)\n\n @classmethod\n def normalize(cls, key, value):\n if key in ('plugin', 'foreign_id'):\n if not isinstance(value, str):\n value = str(value)\n if value == '':\n raise ValueError(value)\n\n elif key == 'state':\n value = int(value)\n\n # valid_states = [\n # State.INITIALIZING,\n # State.QUEUED, State.PAUSED, State.DOWNLOADING,\n # State.SHARING, State.DONE, State.ARCHIVED]\n # if value not in valid_states:\n # raise ValueError(value)\n\n else:\n raise NotImplementedError(key)\n\n return value\n\n @orm.validates('plugin', 'foreign_id', 'state')\n def validate(self, key, value):\n return self.normalize(key, value)\n\n def __repr__(self):\n fmt = ''\n return fmt.format(id=id(self), state=self.state)\n # return fmt.format(id=id(self), state=STATE_SYMBOLS[self.state])\n\n# class Download(sautils.Base):\n# __tablename__ = 'download'\n\n# id = Column(Integer, primary_key=True)\n# state = Column(String(50))\n# type = Column(String(20))\n\n# __mapper_args__ = {\n# 'polymorphic_on': type,\n# # polymorphic_identity is not defined because this is an\n# # \"abstract base class\"\n# # 'polymorphic_identity': ''\n# }\n\n\n# class EpisodeDownload(Download):\n# __mapper_args__ = {\n# 'polymorphic_identity': 'episode'\n# }\n# episode_id = Column(Integer,\n# ForeignKey(Episode.id, ondelete=\"CASCADE\"),\n# nullable=True)\n# episode = orm.relationship(Episode,\n# uselist=False,\n# backref=orm.backref(\"download\",\n# uselist=False,\n# cascade_backrefs=False,\n# lazy='select'))\n\n\n# class MovieDownload(Download):\n# __mapper_args__ = {\n# 'polymorphic_identity': 'movie'\n# }\n\n# movie_id = Column(Integer,\n# ForeignKey(Movie.id, ondelete=\"CASCADE\"),\n# nullable=True)\n# movie = orm.relationship(Movie,\n# uselist=False,\n# backref=orm.backref(\"download\",\n# uselist=False,\n# cascade_backrefs=False,\n# lazy='select'))\n\n\ndef _init_check_required(kwargs, reqs):\n check = all([attr in kwargs for attr in reqs])\n\n if not check:\n err = (\"Insufficient arguments. \"\n \"Required: {req}, got: {got}\")\n err = err.format(req=', '.join(reqs),\n got=', '.join(kwargs.keys()))\n raise TypeError(err)\n\n\ndef _eq_from_attrs(a, b, attrs):\n if not isinstance(b, a.__class__):\n raise TypeError(b.__class__)\n\n try:\n return all([\n getattr(a, attr) == getattr(b, attr)\n for attr in attrs\n ])\n except AttributeError as e:\n raise TypeError(b) from e\n\n\ndef _lt_from_attrs(a, b, attrs):\n for attr in attrs:\n if not hasattr(a, attr):\n raise TypeError(a)\n\n if not hasattr(b, attr):\n raise TypeError(a)\n\n ret = getattr(a, attr).__lt__(getattr(b, attr))\n if ret != 0:\n return ret\n\n return 0\n\n\ndef _asdict_from_attrs(x, attrs):\n return {attr: getattr(x, attr, None) for attr in attrs}\n\n\ndef _entity_getter(x):\n entity_attrs = (\n 'episode',\n 'movie'\n )\n\n for attr in entity_attrs:\n value = getattr(x, attr, None)\n if value:\n return value\n\n return None\n\n\ndef _entity_setter(x, entity):\n entity_map = {\n Episode: 'episode',\n Movie: 'movie'\n }\n\n # Check for unknown entity type\n if entity is not None and entity.__class__ not in entity_map:\n raise TypeError(entity)\n\n # Set all entity-attributes correctly\n for (model, attr) in entity_map.items():\n value = entity if isinstance(entity, model) else None\n setattr(x, attr, value)\n","sub_path":"arroyo/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":20749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"240017000","text":"# в python3 такая строчка обычно не нужна\n# но если у вас специфичные настройки компьютера\n# может пригодиться\n# -*- coding: UTF-8 -*-\nimport json\nimport xml.etree.ElementTree as eTree\n\n\n# Удаляем из текста все HTML тэги и спецсимволы, такие как :/\\'\" .,()\ndef remove_html_tags(text):\n while text.find('<') > -1:\n open_tag = text.find('<')\n close_tag = text.find('>')\n text = '{} {}'.format(text[:open_tag], text[close_tag + 1:])\n return text.replace('(', '').replace(')', '').replace('.', '').replace('\"', '').replace('\\'', '') \\\n .replace('\\\\', '').replace('/', '').replace(',', '').replace(';', '').replace(':', '')\n\n\n# Чтение файла JSON\ndef read_json(filename, encoding): # Чтение файла JSON\n with open(filename, encoding=encoding) as news:\n data = (json.load(news))\n articles = data['rss']['channel']['item'] # Список со статьями\n text = ''\n for article in articles:\n article_text = article['description']\n if isinstance(article_text, dict):\n article_text = article_text[\"__cdata\"]\n text += remove_html_tags(article_text)\n return text\n\n\n# Чтение файла XML\ndef read_xml(filename, encoding):\n parser = eTree.XMLParser(encoding=encoding)\n tree = eTree.parse(filename, parser)\n root = tree.getroot()\n text = ''\n for item in root.iter('item'):\n article = item.find('description')\n article_text = remove_html_tags(article.text)\n text += article_text\n return text\n\n\n# Вывод результатов в консоль\ndef print_results(filename, top_10):\n print('Топ-10 слов в файле {}'.format(filename))\n for word, count in top_10:\n print('{:20}: {} раз '.format(word, count))\n print('-' * 30)\n\n\n# Получение списка файлов и их обработка\ndef get_files(files, func):\n for file in files:\n text = func(file['filename'], file['encoding'])\n words = text.split()\n words_count = {}\n for word in words:\n if len(word) > 6:\n words_count[word] = words_count.get(word, 0) + 1\n top_10 = sorted(words_count.items(), key=lambda x: x[1], reverse=True)[:10]\n print_results(file['filename'], top_10)\n\n\nfiles_json = [\n {'filename': 'newsafr.json', 'encoding': \"utf8\"},\n {'filename': 'newsfr.json', 'encoding': \"iso8859_5\"},\n {'filename': 'newscy.json', 'encoding': \"koi8-r\"},\n {'filename': 'newsit.json', 'encoding': \"cp1251\"}\n]\nfiles_xml = [\n {'filename': 'newsafr.xml', 'encoding': \"cp1251\"},\n {'filename': 'newsfr.xml', 'encoding': \"iso8859_5\"},\n {'filename': 'newscy.xml', 'encoding': \"koi8-r\"},\n {'filename': 'newsit.xml', 'encoding': \"cp1251\"}\n]\n\nprint('Программа выводит Топ 10 наиболее встречающихся слов в файлах XML либо JSON')\nwhile True:\n print('Введите:\\n'\n '1 - чтобы вывести Топ 10 слов из файлов JSON\\n'\n '2 - чтобы вывести Топ 10 слов из файлов XML\\n'\n '0 - чтобы выйти из программы')\n choice = input()\n if choice == '1':\n get_files(files_json, read_json)\n continue\n elif choice == '2':\n get_files(files_xml, read_xml)\n continue\n elif choice == '0':\n break\n else:\n print('Введен неверный номер')\n continue\n","sub_path":"newsparser.py","file_name":"newsparser.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"281559440","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSMS.context_processors\n\nModule contains get_user_info function for making global LOGGED_USER\nvariable in all templates.\n\n:copyright: (c) 2015 by Oleksii Omelchuk.\n:license: BSD.\n\"\"\"\n\nfrom django.http import HttpRequest\n\nfrom apps.mainteacher.models.teachers import Teachers\n\n\ndef get_user_info(request):\n \"\"\"Make global template variable LOGGED_USER\n from session user_id.\n \"\"\"\n try:\n logged_user = Teachers.objects.get(pk=request.session['teacher_id'])\n except KeyError:\n logged_user = None\n\n return {'LOGGED_USER': logged_user}\n","sub_path":"SMS/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"95384342","text":"import sys\nimport os\nimport math\nfrom PIL import Image \nfrom PIL import ImageDraw\nfrom PIL import ImageFilter\n\nif __name__ == '__main__':\n args = sys.argv\n faces = ( \"x+\", \"x-\", \"y+\", \"y-\", \"z+\", \"z-\" )\n out_width = 1024\n start_x = 0\n img = Image.new('RGBA', [out_width*6, out_width], (0x00,0x00,0x00,0xff))\n for face in faces:\n srcimg = Image.open(face+\".png\", 'r')\n resized_img = srcimg.resize((out_width, out_width))\n clipboard = resized_img.crop((0, 0, out_width, out_width))\n img.paste(clipboard, (start_x, 0, start_x + out_width, out_width))\n start_x += out_width\n #end\n\n outdir = \".\"\n outpath = outdir + '/skybox.png'\n img.save(outpath);\n#EOF\n","sub_path":"Tools/stitch2.py","file_name":"stitch2.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"445723425","text":"import os\nfrom django.test import TestCase\nfrom corehq.apps.app_manager.const import APP_V2\nfrom corehq.apps.app_manager.models import Application, Module\nfrom corehq.apps.userreports.dbaccessors import delete_all_report_configs\nfrom corehq.apps.userreports.models import DataSourceConfiguration\nfrom corehq.apps.userreports.reports.builder.forms import ConfigureListReportForm\n\n\ndef read(rel_path):\n path = os.path.join(os.path.dirname(__file__), *rel_path)\n with open(path) as f:\n return f.read()\n\n\nclass ReportBuilderTest(TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.app = Application.new_app('domain', 'Untitled Application', application_version=APP_V2)\n module = cls.app.add_module(Module.new_module('Untitled Module', None))\n cls.form = cls.app.new_form(module.id, \"Untitled Form\", 'en', read(['data', 'forms', 'simple.xml']))\n cls.app.save()\n\n @classmethod\n def tearDownClass(cls):\n cls.app.delete()\n for config in DataSourceConfiguration.all():\n config.delete()\n delete_all_report_configs()\n\n def test_updating_out_of_date_report(self):\n \"\"\"\n Test that editing a report for an outdated data source creates a new data source.\n Data sources are tied to app version.\n \"\"\"\n\n # Make report\n builder_form = ConfigureListReportForm(\n \"Test Report\",\n self.app._id,\n \"form\",\n self.form.unique_id,\n existing_report=None,\n data={\n 'filters': '[]',\n 'columns': '[{\"property\": \"/data/first_name\", \"display_text\": \"first name\"}]',\n }\n )\n self.assertTrue(builder_form.is_valid())\n report = builder_form.create_report()\n first_data_source_id = report.config_id\n\n # Bump version of app by saving it\n self.app.save()\n\n # Modify the report\n builder_form = ConfigureListReportForm(\n \"Test Report\",\n self.app._id,\n \"form\",\n self.form.unique_id,\n existing_report=report,\n data={\n 'filters': '[]',\n 'columns': '[{\"property\": \"/data/first_name\", \"display_text\": \"first name\"}]',\n }\n )\n self.assertTrue(builder_form.is_valid())\n report = builder_form.update_report()\n second_data_source_id = report.config_id\n\n self.assertNotEqual(first_data_source_id, second_data_source_id)\n","sub_path":"corehq/apps/userreports/tests/test_report_builder.py","file_name":"test_report_builder.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"492981755","text":"import boto3\nimport sys\nimport os\nimport time\nfrom texttable import Texttable\n\ndef SG_Intuit_CIDR_SSH(profilename):\n\t#print(\"SG_Intuit_CIDR_SSH\")\n\t#client = boto3.client('cloudformation')\n\tif profilename:\n\t\tProfile_Session = boto3.session.Session(profile_name=profilename)\n\t\tclient = Profile_Session.client('cloudformation')\n\t\tProfilename = Profile_Session.profile_name\n\telse:\n\t\tprint(bcolors.WARNING,\"Profile argument is not given and Currently you are not logged into any profile, hence can't proceed and exiting the script\",bcolors.ENDC)\n\t\tsys.exit()\n\ttry:\n\t\tresponse = client.create_stack(\n\t\t StackName='intuit-cidr-ingress-tcp-22',\n\t\t TemplateURL='https://s3-us-west-2.amazonaws.com/286056532910-scripts/intuit-cidr-ingress.yml',\n\t\t Parameters=[\n\t\t {\n\t\t 'ParameterKey': 'Name',\n\t\t 'ParameterValue': 'intuit-cidr-ingress',\n\t\t },\n\t\t {\n\t\t 'ParameterKey': 'Port',\n\t\t 'ParameterValue': '22',\n\t\t },\n\t\t {\n\t\t 'ParameterKey': 'VpcId',\n\t\t 'ParameterValue': 'vpc-73703315',\n\t\t },\n\t\t ],\n\t\t)\n\t\t#print(response)\n\texcept Exception as error:\n\t\tprint(StackName,\" Stack is not created for the following reason\")\n\t\tprint(error)\n\t\tprint(\"\\n\")\n\t\tdelete = input(\"Do you like to Delete this existing Stack (y/N) : \")\n\t\tif delete == 'y' or delete == 'Y':\n\t\t\tdelete_stack(\"intuit-cidr-ingress-tcp-22\",profilename)\n\t\tsys.exit()\n\tprint(\"Stack with Name \\\"intuit-cidr-ingress-tcp-22\\\" is created\",)\n\tmonitor_stack('intuit-cidr-ingress-tcp-22',profilename)\n\n\ndef SG_Intuit_CIDR_HTTP():\n\tprint(\"SG_Intuit_CIDR_HTTP\")\n\ndef SG_Intuit_CIDR_HTTPS():\n\tprint(\"SG_Intuit_CIDR_HTTPS\")\n\ndef SG_Intuit_APIGW_CIDR_HTTPS():\n\tprint(\"SG_Intuit_APIGW_CIDR_HTTPS\")\n\ndef monitor_stack(Stack_Name,profilename):\n\tif profilename:\n\t\tProfile_Session = boto3.session.Session(profile_name=profilename)\n\t\tclient = Profile_Session.client('cloudformation')\n\t\tProfilename = Profile_Session.profile_name\n\telse:\n\t\tprint(bcolors.WARNING,\"Profile argument is not given and Currently you are not logged into any profile, hence can't proceed and exiting the script\",bcolors.ENDC)\n\t\tsys.exit()\n\ttry:\n\t\twhile True:\n\t\t\tresponse = client.describe_stack_events(\n\t\t\t\tStackName=Stack_Name,\n\t\t\t)\n\t\t\tList = []\n\t\t\tList = [['Stack_Id', 'Stack_Name', 'Resource_Status', 'Resource_Status_Reason']]\n\t\t\tprint(response['StackEvents'][0]['ResourceStatus'])\n\t\t\tList.append([response['StackEvents'][0]['StackId'],response['StackEvents'][0]['StackName'], response['StackEvents'][0]['ResourceStatus'], response['StackEvents'][0]['ResourceStatusReason']])\n\t\t\tt = Texttable()\n\t\t\tt.add_rows(List)\n\t\t\tprint(t.draw())\n\t\t\tresp = client.describe_stacks(\n\t\t\t\tStackName=Stack_Name,\n\t\t\t)\n\t\t\tStackStatus = resp['Stacks'][0]['StackStatus']\n\t\t\tif StackStatus == 'ROLLBACK_COMPLETE' or StackStatus == 'CREATE_FAILED' or StackStatus == 'CREATE_COMPLETE':\n\t\t\t\tprint(\"Current status of the Stack is \",StackStatus)\n\texcept Exception as error:\n\t\tprint(error)\n\n\ndef delete_stack(Stack_Name,profilename):\n\tif Stack_Name == '':\n\t\tStack_Name = input(\"Enter the Stack Name : \")\n\tif profilename:\n\t\tProfile_Session = boto3.session.Session(profile_name=profilename)\n\t\tclient = Profile_Session.client('cloudformation')\n\t\tProfilename = Profile_Session.profile_name\n\telse:\n\t\tprint(bcolors.WARNING,\"Profile argument is not given and Currently you are not logged into any profile, hence can't proceed and exiting the script\",bcolors.ENDC)\n\t\tsys.exit()\n\ttry:\t\n\t\tresponse = client.delete_stack(\n\t\t StackName=Stack_Name\n\t\t)\n\t\tprint(Stack_Name,\" is deleted successfully\")\n\texcept Exception as error:\n\t\tprint(error)\n\t\tprint(\"Unable to delete stack - \",Stack_Name)\n\ndef main():\n\tProfile = sys.argv[1]\n\twhile True:\t\n#\t\tos.system('clear')\n\t\tprint(\"1. Create Stack - Security Group with Intuit CIDR for SSH\")\n\t\tprint(\"2. Create Stack - Security Group with Intuit CIDR for HTTP\")\n\t\tprint(\"3. Create Stack - Security Group with Intuit CIDR for HTTPS\")\n\t\tprint(\"4. Create Stack - Security Group with Intuit API GW CIDR for HTTPS\")\n\t\tprint(\"5. Delete Stack of your Choice\")\n\t\tprint(\"6. Exit\")\n\t\tprint(\"\\n\")\n\t\tchoice = input(\"Enter Your Choice : \")\n\t\tif choice == '1':\n\t\t\tSG_Intuit_CIDR_SSH(Profile)\n\t\t\tbreak\n\t\telif choice == '2':\n\t\t\tSG_Intuit_CIDR_HTTP()\n\t\telif choice == '3':\n\t\t\tSG_Intuit_CIDR_HTTPS()\n\t\telif choice == '4':\n\t\t\tSG_Intuit_APIGW_CIDR_HTTPS()\n\t\telif choice == '5':\n\t\t\tdelete_stack('',Profile)\n\t\telif choice == '6':\n\t\t\tprint(\"Thank you for using the Script\")\n\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"Wrong Choice\")\n\t\t\ttime.sleep('5')\n\t\t\tcontinue\n\n\nif __name__ == '__main__' :\n\ttry:\n\t\tmain()\n\texcept KeyboardInterrupt:\n\t\tprint('')\n\t\tprint('\\033[1m' + '\\nKeyboard Interruption..Calm Down')\n\t\tprint('\\033[1m' + '\\nExiting !!!!\\n')\n\t\tprint('\\033[0m')\n\t\tsys.exit()","sub_path":"boto3/scripts/Trigger_v1.0.py","file_name":"Trigger_v1.0.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"339285959","text":"import tkinter as tk\nimport collections\n\nimport View.ViewConfigs as sViewConfigs\nimport View.TkVariables as sVariables\nimport View.WidgetManager as sWidgetManager\n\nimport View.RootManager as mRootManager\nimport View.TextManager as mTextManager\nimport View.FileManager as mFileManager\nimport View.MessageManager as mMsgManager\nimport View.ManagerBus as mManagerBus\nimport View.MainFrameManager as mMainFrameManager\nimport View.ShortCutManager as mShortCutManager\nimport View.MenuManager as mMenuManager\n\nclass View():\n def __init__(self):\n self._variables = sVariables.TkVariables.getInstance()\n self._viewConfigs = sViewConfigs.ViewConfigs.getInstance()\n self._widgetManager = sWidgetManager.WidgetManager.getInstance()\n\n self._managers= collections.OrderedDict()\n\n def createWindow(self):\n self._createManagers()\n\n self._configTkVariables()\n self._configViewConfigs()\n self._configManagers()\n\n def _createManagers(self):\n self._managers[\"root\"] = mRootManager.RootManager()\n\n self._managers[\"bus\"] = mManagerBus.ManagerBus()\n\n self._managers[\"message\"] = mMsgManager.MessageManager()\n\n self._managers[\"file\"] = mFileManager.FileManager()\n\n self._managers[\"menu\"] = mMenuManager.MenuManager()\n\n self._managers[\"shortCut\"] = mShortCutManager.ShortCutManager()\n\n self._managers[\"mainFrame\"] = mMainFrameManager.MainFrameManager()\n\n self._managers[\"text\"] = mTextManager.TextManager(True)\n\n self._managers[\"output\"] = mTextManager.TextManager(False)\n\n def _configViewConfigs(self):\n self._viewConfigs.setConfigs(self._managers)\n\n def _configTkVariables(self):\n for name in (\"enableLineNum\", \"enableCursorInfo\", \"enableHighlightCurrentLine\"):\n self._variables.createInt(name)\n\n for name in (\"themes\",):\n self._variables.createString(name)\n\n def _configManagers(self):\n for k, v in self._managers.items():\n try:\n v.configure(self._managers)\n except:\n print(\"config error: {0}\".format(k))\n\n def showWindow(self):\n win = self._widgetManager.get(\"Root\")\n\n win.mainloop()\n","sub_path":"View/View.py","file_name":"View.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"27903185","text":"'''\npandas分组与聚合\n'''\nimport pandas as pd\nimport numpy as np\nsales = [{'account': 'Jones LLC','type':'a', 'Jan': 150, 'Feb': 200, 'Mar': 140},\n {'account': 'Alpha Co','type':'b', 'Jan': 200, 'Feb': 210, 'Mar': 215},\n {'account': 'Blue Inc','type':'a', 'Jan': 50, 'Feb': 90, 'Mar': 95 }]\ndf = pd.DataFrame(sales)\n# print(df.groupby('type').groups)\n# >>> {'b': Int64Index([1], dtype='int64'), 'a': Int64Index([0, 2], dtype='int64')}\n# for a,b in df.groupby('type'): #打印分组信息\n# print(a)\n# print(b)\n\n# res = df.groupby('type').aggregate({'type':'count', 'Feb':'sum'})\n# 按照'type'分为a,b两组,以a,b别作为行索引,将分组的'type'列求个数作为第一列,'Feb'列求和作为第二列,\n# print(res)\n# >>>:\n# Feb type\n# type\n# a 290 2\n# b 210 1\ngroup=['x','y','z']\ndata=pd.DataFrame({\n \"group\":[group[x] for x in np.random.randint(0,len(group),10)] ,\n \"salary\":np.random.randint(5,50,10),\n \"age\":np.random.randint(15,50,10)\n })\nprint(data)\n# res = data.groupby('group').agg('mean') # 以'group'分组,求各组的年龄和薪资平均值\n# print(res)\n\n# res = data.groupby('group').mean().to_dict() # 等价与上面\n# print(res)\n\n# res = data.groupby('group').transform('mean')\n# print(res)\n\nres = pd.pivot_table(data,\n values='salary',\n columns='group',\n index='age',\n aggfunc='count',\n margins=True\n ).reset_index()\nprint(res)\n","sub_path":"week04/section7.py","file_name":"section7.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"448080300","text":"from flask import Flask, render_template, request, flash, session, redirect, url_for, Blueprint, request, jsonify\nfrom flask_login import login_required, login_user, logout_user, current_user\nfrom Scheduler.model import db, Announcement\nfrom Scheduler.forms import AnnouncementForm\nfrom Scheduler.decorators import admin_required\nfrom sqlalchemy import func\nfrom sqlalchemy import and_\nimport datetime\nimport calendar\nimport sys\n\nannouncement = Blueprint('announcement', __name__, template_folder='templates')\n\ndef create_announcement(title, author, body):\n newAnnouncement = Announcement(title, author, body)\n db.session.add(newAnnouncement)\n db.session.commit()\n return newAnnouncement\n\ndef delete_announcement(id):\n announcement = Announcement.query.filter_by(id=id).first()\n db.session.delete(announcement)\n db.session.commit()\n\n@announcement.route('/announcements')\ndef announcements():\n announcements = Announcement.query.all()\n list.reverse(announcements)\n if len(announcements) > 0:\n return render_template('announcements.html', announcements=announcements)\n else:\n msg = 'No Announcements Found'\n return render_template('announcements.html', msg=msg)\n\n@announcement.route('/announcement//')\ndef view_announcement(id):\n announcement = Announcement.query.filter_by(id=id).first()\n return render_template('announcement.html', announcement=announcement)\n\n@announcement.route('/add_announcement', methods=['GET', 'POST'])\n@admin_required\ndef add_announcement():\n form = AnnouncementForm(request.form)\n if form.validate_on_submit():\n create_announcement(form.title.data, session['username'], form.body.data)\n flash('Announcement created!', 'success')\n return redirect(url_for('regular.dashboard'))\n return render_template('add_announcement.html', form=form)\n\n@announcement.route('/edit_announcement//', methods=['GET', 'POST'])\n@admin_required\ndef edit_announcement(id):\n announcement = Announcement.query.filter_by(id=id).first()\n form = AnnouncementForm(request.form)\n form.title.data = announcement.title\n form.body.data = announcement.body\n\n if form.validate_on_submit():\n delete_announcement(announcement.id)\n title = request.form['title']\n body = request.form['body']\n\n create_announcement(title, session['username'], body)\n\n flash('Announcement edited!', 'success')\n \n return redirect(url_for('regular.dashboard'))\n return render_template('edit_announcement.html', form=form)\n\n@announcement.route('/delete_announcement//')\n@admin_required\ndef delete_route(id):\n delete_announcement(id)\n flash('Announcement Deleted!', 'success')\n return redirect(url_for('regular.dashboard'))","sub_path":"Scheduler/announcement.py","file_name":"announcement.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"498376433","text":"import check\nimport info\nimport variables\n#from dateutil import parser\n\ndef setVariablesFromArgs(args):\n\t\n\tvariables.files = list(args.file)\n\n\tif args.EffectParams is not None:\n\t\t\tvariables.Settings = list(args.EffectParams)\n\n\tif args.TimeFormat == None and variables.TimeFormat == None:\n\t\tvariables.TimeFormat = \"[%Y/%m/%d %H:%M:%S]\"\n\telif args.TimeFormat is not None:\n\t\tvariables.TimeFormat = args.TimeFormat\n\n\tif not args.YMax == None: \n\t\ttry:\n\t\t\tvariables.YMax = check.MAX_TYPE(args.YMax)\n\t\texcept:\n\t\t\tinfo.err(\"YMax of value <\" + args.YMax + \"> is invalid.\")\n\ttry:\n\t\tvariables.YMin = check.MIN_TYPE(args.YMin)\n\texcept:\n\t\tinfo.err(\"YMin of value <\" + args.YMin + \"> is invalid.\")\n\n\tif args.Speed is not None and args.Time is not None and args.FPS is not None:\n\t\tinfo.err(\"Set only two of the following: [FPS] [Speed] [Time]\")\n\n\tif args.Speed is not None and (check.is_int(args.Speed) or check.is_float(args.Speed)):\n\t\tvariables.Speed = args.Speed\n\n\tif args.Time is not None and (check.is_int(args.Time) or check.is_float(args.Time)):\n\t\tvariables.Time = args.Time\n\n\tif args.FPS is not None and (check.is_int(args.FPS) or check.is_float(args.FPS)):\n\t\tvariables.FPS = args.FPS\n\n\tif args.Legend is not None:\n\t\tvariables.Legend = args.Legend\n\n\tif args.Name is not None:\n\t\tvariables.Name = args.Name.rstrip('/')\n\telse:\n\t\tvariables.Name = variables.tmpdir\n\n\tif variables.Speed is not None and variables.Time is not None and variables.FPS is not None:\n\t\tinfo.err(\"There has been set all of the following by combining config file and args: [FPS] [Speed] [Time]\")\n\n\tif variables.FPS is not None and variables.Time is not None:\n\t\tvariables.Speed = 1\n\n\tinfo.info(\"Params from command line set succesfully.\")\n\n\ndef setVar(name, value):\n\tif name.lower() == \"timeformat\":\n\t\t# should check the format validity\n\t\tvariables.TimeFormat = value\n\n\telif name.lower() == \"ymin\":\n\t\ttry:\n\t\t\tvariables.YMin = check.MIN_TYPE(value)\n\t\texcept:\n\t\t\tinfo.err(\"YMin of value <\" + value + \"> in config file is invalid.\")\n\n\telif name.lower() == \"ymax\":\n\t\ttry:\n\t\t\tvariables.YMax = check.MAX_TYPE(value)\n\t\texcept:\n\t\t\tinfo.err(\"YMax of value <\" + value + \"> in config file is invalid.\")\n\n\telif name.lower() == \"speed\":\n\t\tif variables.Time is not None and variables.FPS is not None:\n\t\t\tinfo.err(\"Speed is already set by setting the Time and FPS.\")\n\t\t\t\t\n\t\tif check.is_int(value) or check.is_float(value):\n\t\t\tvariables.Speed = value\n\t\telse:\n\t\t\tinfo.err(\"Speed value is not numeric.\")\n\n\telif name.lower() == \"time\":\n\t\tif variables.Speed is not None and variables.FPS is not None:\n\t\t\tinfo.err(\"Time is already set by setting the Speed and FPS.\")\n\t\t\t\t\n\t\tif check.is_int(value) or check.is_float(value):\n\t\t\tvariables.Time = value\n\t\telse:\n\t\t\tinfo.err(\"Time value is not numeric.\")\n\telif name.lower() == \"fps\":\n\t\tif variables.Time is not None and variables.Speed is not None:\n\t\t\tinfo.err(\"FPS is already set by setting the Time and Speed.\")\n\t\t\t\n\t\tif check.is_int(value) or check.is_float(value):\n\t\t\tvariables.FPS = value\n\t\telse:\n\t\t\tinfo.err(\"FPS value is not numeric.\")\n\t\n\telif name.lower == \"legend\":\n\t\tvariables.Legend = value\n\n\telif name.lower == \"name\":\n\t\tif value is not None:\n\t\t\tvariables.Name = str(value).rstrip('/') \n\n\n\telse:\n\t\tinfo.err(\"Keyword <\" + name + \"> with value <\" + value + \"> from config file does not appear to be valid.\")\n\n\ndef loadConfig(configFile):\n\tif configFile is None:\n\t\tinfo.info(\"Config file path not set, skipping loading from config.\")\n\t\treturn\n\tif not check.file_exists(configFile):\n\t\tinfo.err(\"Config file does not exist!\")\n\t\n\t# now start loading some shit maybe?\n\ttry: \n\t\tfile = open(configFile, mode='r', encoding='utf-8')\n\texcept:\n\t\terr(\"Could not open config file for reading. Insufficient permissions?\")\n\n\tfor line in file:\n\t\tline=line.strip()\n\t\t# skip comments and lines with whitespaces only\n\t\tif line.startswith('#') or not line.strip():\n\t\t\tcontinue\n\t\tif \"#\" in line:\n\t\t\tline=line[0:line.find('#')]\n\t\t\tline.rstrip()\n\t\t#create array of values\t\n\t\tline = line.split(\" \", 1)\n\t\tsetVar(line[0],line[1])\n\n\tinfo.info(\"Params from config file loaded sucessfully.\")\n\treturn True\n\ndef checkVars():\n\tif variables.FPS is None and variables.Time is None:\n\t\tvariables.FPS = 25\n\tif variables.Speed is None:\n\t\tvariables.Speed = 1\n\n\n\n","sub_path":"reset.py","file_name":"reset.py","file_ext":"py","file_size_in_byte":4217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"327659074","text":"from flaskps import db\nfrom sqlalchemy_utils import ChoiceType\nfrom .constants import (\n GENDER_CHOICES,\n)\n\nclass Students(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n surname = db.Column(db.String(60))\n name = db.Column(db.String(60))\n birth_date = db.Column(db.Date())\n borned = db.Column(db.String(60))\n locality = db.Column(db.String(60))\n address = db.Column(db.String(60))\n gender = db.Column(ChoiceType(GENDER_CHOICES))\n document_type = db.Column(db.String(60))\n document_number = db.Column(db.String(60))\n tutor = db.Column(db.String(60))\n phone = db.Column(db.String(60))\n tutor_name = db.Column(db.String(60))\n level_id = db.Column(db.Integer, db.ForeignKey('level.id'), nullable=False)\n school_id = db.Column(db.Integer, db.ForeignKey('school.id'), nullable=False)\n neighborhood_id = db.Column(db.Integer, db.ForeignKey('neighborhood.id'), nullable=False)\n\n\n\n def __repr__(self):\n return '' % self.name\n\n @classmethod\n def create(cls, form):\n instance = cls(\n name=form.name.data,\n surname=form.surname.data,\n birth_date=form.birth_date.data,\n borned=form.borned.data,\n locality=form.locality.data,\n address=form.address.data,\n neighborhood_id=form.neighborhood.data,\n gender=form.gender.data,\n document_type=form.document_type.data,\n document_number=form.document_number.data,\n tutor=form.tutor.data,\n phone=form.phone.data,\n school_id=form.school.data,\n level_id=form.level.data,\n tutor_name=form.tutor_name.data,\n )\n db.session.add(instance)\n try:\n db.session.commit()\n except:\n db.session.rollback()\n return instance\n\n @classmethod\n def delete(cls, student_id):\n student = Students.query.filter_by(id=student_id).first_or_404()\n db.session.delete(student)\n db.session.commit()\n\n def update(self, form):\n self.name = form.name.data\n self.surname = form.surname.data\n self.birth_date = form.birth_date.data\n self.borned = form.borned.data\n self.locality = form.locality.data\n self.address = form.address.data\n self.neighborhood = form.neighborhood.data\n self.gender = form.gender.data\n self.document_type = form.document_type.data\n self.document_number = form.document_number.data\n self.tutor = form.tutor.data\n self.phone = form.phone.data\n self.school = form.school.data\n self.level = form.level.data\n\n db.session.commit()\n\n\nclass Neighborhood(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n name = db.Column(db.String(60), unique=True, nullable=False)\n\nclass Level(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n name = db.Column(db.String(60), unique=True, nullable=False)\n\nclass School(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n name = db.Column(db.String(60), unique=True, nullable=False)\n address = db.Column(db.String(100))\n phone = db.Column(db.String(20))\n","sub_path":"flaskps/app/students/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"246735351","text":"class Solution:\n def romanToInt(self, s: str) -> int:\n # Start by splitting the string into symbols\n # Group subtractions together, maybe loop through once and check for them?\n # E.g. look ahead to next letter and if it is greater then group\n # Sum up the resulting symbols\n\n symbols = [letter for letter in s]\n\n subtraction = False # Keep track of whether current loop is subtraction\n\n numeral_to_int = 0\n\n for idx, letter in enumerate(symbols):\n\n # Skip this loop if the previous loop was subtraction\n if subtraction:\n subtraction = False # Reset subtraction so we continue with the loop\n continue\n\n # first check to make sure we are not at the end of the list\n if (idx + 1) < len(symbols):\n next_letter = symbols[idx+1]\n\n # Check for all subtractions\n\n # check for CD and CM subtraction\n if letter == \"C\" and next_letter == \"D\":\n numeral_to_int += 400\n subtraction = True\n continue\n if letter == \"C\" and next_letter == \"M\":\n numeral_to_int += 900\n subtraction = True\n continue\n\n # Check for XL and XC subtraction\n if letter == \"X\" and next_letter == \"L\":\n numeral_to_int += 40\n subtraction = True\n continue\n if letter == \"X\" and next_letter == \"C\":\n numeral_to_int += 90\n subtraction = True\n continue\n\n # Check for IV and IX subtraction\n if letter == \"I\" and next_letter == \"V\":\n numeral_to_int += 4\n subtraction = True\n continue\n if letter == \"I\" and next_letter == \"X\":\n numeral_to_int += 9\n subtraction = True\n continue\n\n # If no subtractions, add the correct numeral value\n # Unindented bc this can be the last element of the list\n numeral_values = {\n \"I\": 1,\n \"V\": 5,\n \"X\": 10,\n \"L\": 50,\n \"C\": 100,\n \"D\": 500,\n \"M\": 1000\n }\n\n numeral_to_int += numeral_values[letter]\n\n return numeral_to_int\n\n","sub_path":"leetcode/romanToInt.py","file_name":"romanToInt.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"496733968","text":"import pygame\r\n\r\nclass Node:\r\n 'single grid node class'\r\n\r\n def __init__(self):\r\n self.id = 0\r\n self.color = 0 # 0 - white\r\n self.neighbours = []\r\n self.rect = pygame.Rect(0,0,50,50)\r\n self.handled = False\r\n self.isWall = False\r\n self.x = 0\r\n self.y = 0\r\n self.parent = None\r\n self.inOpenSet = False\r\n self.g = 0\r\n self.h = 0\r\n self.f = 0\r\n\r\n def __eq__(self, other):\r\n if self.id == other.id:\r\n return True\r\n else:\r\n return False\r\n \r\n def __lt__(self,other):\r\n return self.f < other.f\r\n\r\n\r\n def draw(self, window, x, y, sprites):\r\n if self.color == 0:\r\n window.blit(sprites[0], (x, y))\r\n elif self.color == 1:\r\n window.blit(sprites[1], (x, y))\r\n elif self.color == 2:\r\n window.blit(sprites[2], (x, y))\r\n elif self.color == 3:\r\n window.blit(sprites[3], (x, y))\r\n elif self.color == 4:\r\n window.blit(sprites[4], (x, y))\r\n\r\n def getColor(self):\r\n return self.color","sub_path":"grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"23741420","text":"from django.conf.urls import url\nfrom trash import views\n\nurlpatterns = [\n url(r'^$', views.trash_list, name='trash_index'),\n url(r'^add$', views.trash_add, name='trash_add'),\n url(r'^list$', views.trash_list, name='trash_list'),\n url(r'^detail/(?P\\d+)$', views.trash_details, name='trash_details'),\n url(r'^delete/(?P\\d+)$', views.trash_delete, name='trash_delete'),\n url(r'^(?P\\d+)/recovery', views.recovery_file, name='recovery_file'),\n]","sub_path":"trash/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"477880577","text":"from sys import argv as argument\ntry:\n argument[1]\nexcept IndexError:\n exit()\n\nimport sqlite3\n\n\nconnection = sqlite3.connect('users.db')\nc = connection.cursor()\n\nif argument[1] == \"insert\":\n user_name = input(\"Name: \")\n user_age = input(\"Age: \")\n c.execute(\"INSERT INTO users VALUES (?, ?)\", (user_name, user_age))\n\nelif argument[1] == \"show\":\n username = input(\"User-Name: \")\n c.execute(\"SELECT * FROM users WHERE name=?\", (username,))\n print(c.fetchone())\n\nconnection.commit()\nconnection.close()\n","sub_path":"Database/sqlite/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}
+{"seq_id":"382824071","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\n# plt.style.use('simple') # --- makes nicer plots\n\n\n\n\ndef make_significance_plot(img, threshold = 2.5, show = False, filename = False, imsize = 1):\n\n fig = plt.figure(figsize=(imsize, imsize))\n ax = fig.add_axes([0,0,1,1])\n\n ax.axis('off')\n\n sig = (img.sci/img.noise)\n\n ax.imshow(sig, cmap = cm.Greys, vmin = -5.0, vmax = 5.0, origin = 'lower')\n ax.imshow(np.ma.masked_where(sig <= threshold, sig), cmap = cm.plasma, vmin = threshold, vmax = 100, origin = 'lower')\n\n if filename:\n plt.savefig(filename)\n if show:\n plt.show()\n\n plt.close(fig)\n\n\n\n\ndef make_significance_plots(imgs, threshold = 2.5):\n\n n = len(imgs)\n\n fig, axes = plt.subplots(1, n, figsize = (4*n,4))\n plt.subplots_adjust(left=0, top=1, bottom=0, right=1, wspace=0.01, hspace=0.0)\n\n for ax, (filter, img) in zip(axes, imgs.items()):\n\n sig = (img.sci/img.noise)\n\n ax.set_axis_off()\n ax.imshow(sig, cmap = cm.Greys, vmin = -5.0, vmax = 5.0, origin = 'lower')\n ax.imshow(np.ma.masked_where(sig <= threshold, sig), cmap = cm.plasma, vmin = threshold, vmax = 100, origin = 'lower')\n\n plt.show()\n plt.close(fig)\n\n\n\n\ndef make_segm_plot(segm, imsize = 1, filename = False, show = False):\n\n fig, ax = plt.subplots(1, 1, figsize = (imsize,imsize))\n\n plt.subplots_adjust(left=0, top=1, bottom=0, right=1, wspace=0.0, hspace=0.0)\n\n new_cmap = rand_cmap(int(np.max(segm)), type='bright', first_color_black=True, last_color_black=False, verbose=False)\n\n ax.imshow(segm, cmap = new_cmap, origin = 'lower')\n\n ax.set_axis_off()\n\n if filename:\n plt.savefig(filename)\n if show:\n plt.show()\n\n plt.close(fig)\n\n\n\ndef make_plots(imgs, threshold = 2.5, signficance_plot = False, filter_label = False, filename = False, show = False, use_vmax = True, fixed_range = False, imsize = 1, frame = True):\n\n n = len(imgs)\n\n if show:\n imsize = 4\n else:\n imsize = imsize\n\n if hasattr(next(iter(imgs.values())), 'sci'):\n fig, axes = plt.subplots(1, n, figsize = (n*imsize,1*imsize), dpi = next(iter(imgs.values())).sci.shape[0])\n else:\n fig, axes = plt.subplots(1, n, figsize = (n*imsize,1*imsize))\n\n plt.subplots_adjust(left=0, top=1, bottom=0, right=1, wspace=0.0, hspace=0.0)\n\n if type(signficance_plot) != list: signficance_plot = [signficance_plot]*n\n\n if hasattr(next(iter(imgs.values())), 'sci'):\n if fixed_range:\n vmax = np.max([np.max(img.sci) for img in imgs.values()])\n else:\n if fixed_range:\n vmax = np.max([np.max(img) for img in imgs.values()])\n\n\n for ax, (filter, img), sig_plot in zip(axes, imgs.items(), signficance_plot):\n\n if frame:\n ax.get_xaxis().set_ticks([])\n ax.get_yaxis().set_ticks([])\n else:\n ax.set_axis_off()\n\n if filter_label: ax.text(0.5, 0.9, filter, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize = 8, color = '1.0')\n\n if sig_plot:\n\n sig = (img.sci/img.noise)\n\n ax.imshow(sig, cmap = cm.Greys, vmin = -5.0, vmax = 5.0, origin = 'lower')\n ax.imshow(np.ma.masked_where(sig <= threshold, sig), cmap = cm.plasma, vmin = threshold, vmax = 100, origin = 'lower')\n\n else:\n\n new_cmap = rand_cmap(np.max(img), type='bright', first_color_black=True, last_color_black=False, verbose=False)\n\n if fixed_range:\n vmin = 0.0\n else:\n vmin = None\n vmax = None\n\n if hasattr(img, 'sci'):\n ax.imshow(img.sci, cmap = cm.viridis, origin = 'lower', vmin = vmin, vmax = vmax)\n else:\n ax.imshow(img, cmap = new_cmap, origin = 'lower', vmin = vmin, vmax = vmax) # --- assumes img is just a 2D array\n\n\n\n\n if filename:\n plt.savefig(filename)\n if show:\n plt.show()\n\n plt.close(fig)\n\n\n\ndef rand_cmap(nlabels, type='bright', first_color_black=True, last_color_black=False, verbose=True):\n \"\"\"\n Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks\n :param nlabels: Number of labels (size of colormap)\n :param type: 'bright' for strong colors, 'soft' for pastel colors\n :param first_color_black: Option to use first color as black, True or False\n :param last_color_black: Option to use last color as black, True or False\n :param verbose: Prints the number of labels and shows the colormap. True or False\n :return: colormap for matplotlib\n \"\"\"\n from matplotlib.colors import LinearSegmentedColormap\n import colorsys\n\n\n\n if type not in ('bright', 'soft'):\n print ('Please choose \"bright\" or \"soft\" for type')\n return\n\n if verbose:\n print('Number of labels: ' + str(nlabels))\n\n # Generate color map for bright colors, based on hsv\n if type == 'bright':\n randHSVcolors = [(np.random.uniform(low=0.0, high=1),\n np.random.uniform(low=0.2, high=1),\n np.random.uniform(low=0.9, high=1)) for i in range(nlabels)]\n\n # Convert HSV list to RGB\n randRGBcolors = []\n for HSVcolor in randHSVcolors:\n randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0], HSVcolor[1], HSVcolor[2]))\n\n if first_color_black:\n randRGBcolors[0] = [0, 0, 0]\n\n if last_color_black:\n randRGBcolors[-1] = [0, 0, 0]\n\n random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)\n\n # Generate soft pastel colors, by limiting the RGB spectrum\n if type == 'soft':\n low = 0.6\n high = 0.95\n randRGBcolors = [(np.random.uniform(low=low, high=high),\n np.random.uniform(low=low, high=high),\n np.random.uniform(low=low, high=high)) for i in range(nlabels)]\n\n if first_color_black:\n randRGBcolors[0] = [0, 0, 0]\n\n if last_color_black:\n randRGBcolors[-1] = [0, 0, 0]\n random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)\n\n # Display colorbar\n if verbose:\n from matplotlib import colors, colorbar\n from matplotlib import pyplot as plt\n fig, ax = plt.subplots(1, 1, figsize=(15, 0.5))\n\n bounds = np.linspace(0, nlabels, nlabels + 1)\n norm = colors.BoundaryNorm(bounds, nlabels)\n\n cb = colorbar.ColorbarBase(ax, cmap=random_colormap, norm=norm, spacing='proportional', ticks=None,\n boundaries=bounds, format='%1i', orientation=u'horizontal')\n\n return random_colormap\n\n\ndef COG_plots(Properties, ModelProperties = False, filename = False, show = False):\n\n nfilters = len(Properties)\n\n fig, axes = plt.subplots(1, nfilters, figsize = (3*(nfilters),3), dpi = 200)\n\n plt.subplots_adjust(left=0.025, top=0.85, bottom=0.2, right=0.9, wspace=0.2, hspace=0.0)\n\n for ax, (filter, properties) in zip(axes, Properties.items()):\n\n ax.set_title(filter, fontsize = 10)\n\n ax.plot(properties['photometry']['aperture'].radii, properties['photometry']['aperture'].flux, c = '0.5', label = 'curve-of-growth')\n ax.axvline(properties['photometry']['aperture'].optimum_radius, color = '0.5', alpha = 0.5)\n\n if ModelProperties is not False:\n\n ax.axhline(ModelProperties[filter]['photometry']['total'].flux, color = '0.5', alpha = 0.5, ls = ':')\n ax.plot(ModelProperties[filter]['photometry']['aperture'].radii, ModelProperties[filter]['photometry']['aperture'].flux, c = '0.5', ls = ':', label = 'true curve-of-growth')\n\n\n\n del properties['photometry']['aperture']\n\n color_idx = np.linspace(0, 1, len(properties['photometry']))\n\n for c_idx, (phot_type, p) in zip(color_idx, properties['photometry'].items()):\n\n ax.axhline(p.flux, label = phot_type, color = cm.viridis(c_idx))\n ax.axhspan(p.flux-p.error, p.flux+p.error, color = cm.viridis(c_idx), alpha=0.5)\n if phot_type == 'optimum_aperture': ax.axvline(p.radius, color = cm.viridis(c_idx), alpha = 0.5)\n\n ax.legend(bbox_to_anchor=(1.1, 1.0), fontsize = 8)\n\n if filename:\n plt.savefig(filename)\n if show:\n plt.show()\n\n plt.close(fig)\n\n\n\ndef SED_plot(Properties, ModelProperties = False, FilterInfo = False, phot_type = 'optimum_aperture', filename = False, show = False):\n\n\n # if not FilterInfo:\n\n fig, ax = plt.subplots(1, 1, figsize = (3,2), dpi = 200)\n plt.subplots_adjust(left=0.2, top=0.85, bottom=0.25, right=0.9, wspace=0.2, hspace=0.0)\n\n color_idx = np.linspace(0, 1, len(Properties))\n\n for c_idx, (filter, properties) in zip(color_idx, Properties.items()):\n\n pivwv = FilterInfo[filter].pivwv()/1E4\n\n ax.scatter(pivwv, properties['photometry'][phot_type].flux, color = cm.viridis(c_idx))\n ax.plot([pivwv]*2, [properties['photometry'][phot_type].flux - properties['photometry'][phot_type].error, properties['photometry'][phot_type].flux + properties['photometry'][phot_type].error], color = 'k', lw = 1)\n\n if ModelProperties is not False:\n\n ax.scatter(pivwv, ModelProperties[filter]['photometry']['total'].flux, color = cm.viridis(c_idx), alpha = 0.5)\n\n\n\n ax.set_xlabel(r'$\\lambda/\\mu m$')\n ax.set_ylabel(r'$f_{\\nu}/nJy$')\n\n if filename:\n plt.savefig(filename)\n if show:\n plt.show()\n\n plt.close(fig)\n\n\n\n\ndef size_plot(img, p, ExclusionMask, threshold = 2.5, signficance_plot = False, filename = False, show = False, add_contours = False):\n\n\n width = img.sci.shape[0]\n\n fig, ax = plt.subplots(1, 1, figsize = (3,3), dpi = width*2)\n plt.subplots_adjust(left=0, top=1, bottom=0, right=1, wspace=0.01, hspace=0.0)\n\n ax.set_axis_off()\n\n sig = (img.sci/img.noise)\n\n ax.imshow(sig, cmap = cm.Greys, vmin = -5.0, vmax = 5.0, origin = 'lower')\n ax.imshow(np.ma.masked_where(sig <= threshold, sig), cmap = cm.plasma, vmin = threshold, vmax = 100, origin = 'lower')\n\n k = 2.5\n\n # --- make mask image including Kron Mask and Exclusion mask\n x = np.linspace(-(width//2), (width//2), width)\n X, Y = np.meshgrid(x, x)\n R2 = X**2 + Y**2\n alpha = np.zeros(img.sci.shape)\n alpha[R2>(k*p['kron_radius'])**2] = 1\n alpha[img.sci